Programs & Examples On #Gedcom

GEDCOM, an acronym for GEnealogical Data COMmunication.

Swift - iOS - Dates and times in different format

As already mentioned you have to use DateFormatter to format your Date objects. The easiest way to do it is creating a read-only computed property Date extension.


Read-Only Computed Properties

A computed property with a getter but no setter is known as a read-only computed property. A read-only computed property always returns a value, and can be accessed through dot syntax, but cannot be set to a different value.

Note:

You must declare computed properties—including read-only computed properties—as variable properties with the var keyword, because their value is not fixed. The let keyword is only used for constant properties, to indicate that their values cannot be changed once they are set as part of instance initialization.

You can simplify the declaration of a read-only computed property by removing the get keyword and its braces:


extension Formatter {
    static let date = DateFormatter()
}

extension Date {
    var europeanFormattedEn_US : String {
        Formatter.date.calendar = Calendar(identifier: .iso8601)
        Formatter.date.locale   = Locale(identifier: "en_US_POSIX")
        Formatter.date.timeZone = .current
        Formatter.date.dateFormat = "dd/M/yyyy, H:mm"
        return Formatter.date.string(from: self)
    }
}

To convert it back you can create another read-only computed property but as a string extension:

 extension String {
    var date: Date? {
        return Formatter.date.date(from: self)
    }
    func dateFormatted(with dateFormat: String = "dd/M/yyyy, H:mm", calendar: Calendar = Calendar(identifier: .iso8601), defaultDate: Date? = nil, locale: Locale = Locale(identifier: "en_US_POSIX"), timeZone: TimeZone = .current) -> Date? {
        Formatter.date.calendar = calendar
        Formatter.date.defaultDate = defaultDate ?? calendar.date(bySettingHour: 12, minute: 0, second: 0, of: Date())
        Formatter.date.locale = locale
        Formatter.date.timeZone = timeZone
        Formatter.date.dateFormat = dateFormat
        return Formatter.date.date(from: self)
    }
}

Usage:

let dateFormatted = Date().europeanFormattedEn_US         //"29/9/2018, 16:16"
if let date = dateFormatted.date {
    print(date.description(with:.current)) // Saturday, September 29, 2018 at 4:16:00 PM Brasilia Standard Time\n"\
    date.europeanFormattedEn_US                         // "29/9/2018, 16:27"
}

let dateString = "14/7/2016"
if let date = dateString.toDateFormatted(with: "dd/M/yyyy") {
    print(date.description(with: .current))
 // Thursday, July 14, 2016 at 12:00:00 PM Brasilia Standard Time\n"
}

Coding Conventions - Naming Enums

This will probably not make me a lot of new friends, but it should be added that the C# people have a different guideline: The enum instances are "Pascal case" (upper/lower case mixed). See stackoverflow discussion and MSDN Enumeration Type Naming Guidelines.

As we are exchanging data with a C# system, I am tempted to copy their enums exactly, ignoring Java's "constants have uppercase names" convention. Thinking about it, I don't see much value in being restricted to uppercase for enum instances. For some purposes .name() is a handy shortcut to get a readable representation of an enum constant and a mixed case name would look nicer.

So, yes, I dare question the value of the Java enum naming convention. The fact that "the other half of the programming world" does indeed use a different style makes me think it is legitimate to doubt our own religion.

How to fix homebrew permissions?

This solved the issue fore me.

sudo chown -R "$USER":admin /Users/$USER/Library/Caches/Homebrew
sudo chown -R "$USER":admin /usr/local

Delete an element in a JSON object

Let's assume you want to overwrite the same file:

import json

with open('data.json', 'r') as data_file:
    data = json.load(data_file)

for element in data:
    element.pop('hours', None)

with open('data.json', 'w') as data_file:
    data = json.dump(data, data_file)

dict.pop(<key>, not_found=None) is probably what you where looking for, if I understood your requirements. Because it will remove the hours key if present and will not fail if not present.

However I am not sure I understand why it makes a difference to you whether the hours key contains some days or not, because you just want to get rid of the whole key / value pair, right?

Now, if you really want to use del instead of pop, here is how you could make your code work:

import json

with open('data.json') as data_file:
    data = json.load(data_file)

for element in data:
    if 'hours' in element:
        del element['hours']

with open('data.json', 'w') as data_file:
    data = json.dump(data, data_file)

EDIT So, as you can see, I added the code to write the data back to the file. If you want to write it to another file, just change the filename in the second open statement.

I had to change the indentation, as you might have noticed, so that the file has been closed during the data cleanup phase and can be overwritten at the end.

with is what is called a context manager, whatever it provides (here the data_file file descriptor) is available ONLY within that context. It means that as soon as the indentation of the with block ends, the file gets closed and the context ends, along with the file descriptor which becomes invalid / obsolete.

Without doing this, you wouldn't be able to open the file in write mode and get a new file descriptor to write into.

I hope it's clear enough...

SECOND EDIT

This time, it seems clear that you need to do this:

with open('dest_file.json', 'w') as dest_file:
    with open('source_file.json', 'r') as source_file:
        for line in source_file:
            element = json.loads(line.strip())
            if 'hours' in element:
                del element['hours']
            dest_file.write(json.dumps(element))

LINQ: Select where object does not contain items from list

In general, you're looking for the "Except" extension.

var rejectStatus = GenerateRejectStatuses();
var fullList = GenerateFullList();
var rejectList = fullList.Where(i => rejectStatus.Contains(i.Status));
var filteredList = fullList.Except(rejectList);

In this example, GenerateRegectStatuses() should be the list of statuses you wish to reject (or in more concrete terms based on your example, a List<int> of IDs)

Add unique constraint to combination of two columns

This can also be done in the GUI:

  1. Under the table "Person", right click Indexes
  2. Click/hover New Index
  3. Click Non-Clustered Index...

enter image description here

  1. A default Index name will be given but you may want to change it.
  2. Check Unique checkbox
  3. Click Add... button

enter image description here

  1. Check the columns you want included

enter image description here

  1. Click OK in each window.

How to run test cases in a specified file?

Visual Studio Code shows a link at the top of a Go test file which lets you run all the tests in just that file.

enter image description here

In the "Output" window, you can see that it automatically generates a regex which contains all of the test names in the current file:

Running tool: C:\Go\bin\go.exe test -timeout 30s -run ^(TestFoo|TestBar|TestBaz)$ rootpackage\mypackage

Note: the very first time you open a Go file in VS Code it automatically offers to install some Go extensions for you. I assume the above requires that you have previously accepted the offer to install.

What is the difference between an abstract function and a virtual function?

An abstract function has no implemention and it can only be declared on an abstract class. This forces the derived class to provide an implementation.

A virtual function provides a default implementation and it can exist on either an abstract class or a non-abstract class.

So for example:

public abstract class myBase
{
    //If you derive from this class you must implement this method. notice we have no method body here either
    public abstract void YouMustImplement();

    //If you derive from this class you can change the behavior but are not required to
    public virtual void YouCanOverride()
    { 
    }
}

public class MyBase
{
   //This will not compile because you cannot have an abstract method in a non-abstract class
    public abstract void YouMustImplement();
}

z-index not working with position absolute

z-index only applies to elements that have been given an explicit position. Add position:relative to #popupContent and you should be good to go.

PHP append one array to another (not array_push or +)

foreach loop is faster than array_merge to append values to an existing array, so choose the loop instead if you want to add an array to the end of another.

// Create an array of arrays
$chars = [];
for ($i = 0; $i < 15000; $i++) {
    $chars[] = array_fill(0, 10, 'a');
}

// test array_merge
$new = [];
$start = microtime(TRUE);
foreach ($chars as $splitArray) {
    $new = array_merge($new, $splitArray);
}
echo microtime(true) - $start; // => 14.61776 sec

// test foreach
$new = [];
$start = microtime(TRUE);
foreach ($chars as $splitArray) {
    foreach ($splitArray as $value) {
        $new[] = $value;
    }
}
echo microtime(true) - $start; // => 0.00900101 sec
// ==> 1600 times faster

How to extract a string using JavaScript Regex?

(.*) instead of (.)* would be a start. The latter will only capture the last character on the line.

Also, no need to escape the :.

How do I find out if first character of a string is a number?

Character.isDigit(string.charAt(0))

Note that this will allow any Unicode digit, not just 0-9. You might prefer:

char c = string.charAt(0);
isDigit = (c >= '0' && c <= '9');

Or the slower regex solutions:

s.substring(0, 1).matches("\\d")
// or the equivalent
s.substring(0, 1).matches("[0-9]")

However, with any of these methods, you must first be sure that the string isn't empty. If it is, charAt(0) and substring(0, 1) will throw a StringIndexOutOfBoundsException. startsWith does not have this problem.

To make the entire condition one line and avoid length checks, you can alter the regexes to the following:

s.matches("\\d.*")
// or the equivalent
s.matches("[0-9].*")

If the condition does not appear in a tight loop in your program, the small performance hit for using regular expressions is not likely to be noticeable.

How to delete an element from an array in C#

Removing from an array itself is not simple, as you then have to deal with resizing. This is one of the great advantages of using something like a List<int> instead. It provides Remove/RemoveAt in 2.0, and lots of LINQ extensions for 3.0.

If you can, refactor to use a List<> or similar.

Implementing INotifyPropertyChanged - does a better way exist?

Prism 5 implementation:

public abstract class BindableBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual bool SetProperty<T>(ref T storage,
                                          T value,
                                          [CallerMemberName] string propertyName = null)
    {
        if (object.Equals(storage, value)) return false;

        storage = value;
        this.OnPropertyChanged(propertyName);

        return true;
    }

    protected void OnPropertyChanged(string propertyName)
    {
        var eventHandler = this.PropertyChanged;
        if (eventHandler != null)
        {
            eventHandler(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    protected void OnPropertyChanged<T>(Expression<Func<T>> propertyExpression)
    {
        var propertyName = PropertySupport.ExtractPropertyName(propertyExpression);
        this.OnPropertyChanged(propertyName);
    }
}

public static class PropertySupport
{
    public static string ExtractPropertyName<T>(Expression<Func<T>> propertyExpression)
    {
        if (propertyExpression == null)
        {
            throw new ArgumentNullException("propertyExpression");
        }

        var memberExpression = propertyExpression.Body as MemberExpression;
        if (memberExpression == null)
        {
            throw new ArgumentException("The expression is not a member access expression.", "propertyExpression");
        }

        var property = memberExpression.Member as PropertyInfo;
        if (property == null)
        {
            throw new ArgumentException("The member access expression does not access a property.", "propertyExpression");
        }

        var getMethod = property.GetMethod;
        if (getMethod.IsStatic)
        {
            throw new ArgumentException("The referenced property is a static property.", "propertyExpression");
        }

        return memberExpression.Member.Name;
    }
}

How to change the blue highlight color of a UITableViewCell?

@IBDesignable class UIDesignableTableViewCell: UITableViewCell {
  @IBInspectable var selectedColor: UIColor = UIColor.clearColor() {
    didSet {
      selectedBackgroundView = UIView()
      selectedBackgroundView?.backgroundColor = selectedColor
    }
  }
}

In your storyboard, set the class of your UITableViewCell to UIDesignableTableViewCell, on the Attributes inspector, you may change the selected color of your cell to any color.

You can use this for all of your cells. This is how your Attributes inspector will look like.

This is how your Attributes inspector will look like

What does the "at" (@) symbol do in Python?

Python decorator is like a wrapper of a function or a class. It’s still too conceptual.

def function_decorator(func):
    def wrapped_func():
        # Do something before the function is executed
        func()
        # Do something after the function has been executed
    return wrapped_func

The above code is a definition of a decorator that decorates a function. function_decorator is the name of the decorator.

wrapped_func is the name of the inner function, which is actually only used in this decorator definition. func is the function that is being decorated. In the inner function wrapped_func, we can do whatever before and after the func is called. After the decorator is defined, we simply use it as follows.

@function_decorator
def func():
    pass

Then, whenever we call the function func, the behaviours we’ve defined in the decorator will also be executed.

EXAMPLE :

from functools import wraps

def mydecorator(f):
    @wraps(f)
    def wrapped(*args, **kwargs):
        print "Before decorated function"
        r = f(*args, **kwargs)
        print "After decorated function"
        return r
    return wrapped

@mydecorator
def myfunc(myarg):
    print "my function", myarg
    return "return value"

r = myfunc('asdf')
print r

Output :

    Before decorated function
    my function asdf
    After decorated function
    return value

Can comments be used in JSON?

No.

The JSON is data only, and if you include a comment, then it will be data too.

You could have a designated data element called "_comment" (or something) that should be ignored by apps that use the JSON data.

You would probably be better having the comment in the processes that generates/receives the JSON, as they are supposed to know what the JSON data will be in advance, or at least the structure of it.

But if you decided to:

{
   "_comment": "comment text goes here...",
   "glossary": {
      "title": "example glossary",
      "GlossDiv": {
         "title": "S",
         "GlossList": {
            "GlossEntry": {
               "ID": "SGML",
               "SortAs": "SGML",
               "GlossTerm": "Standard Generalized Markup Language",
               "Acronym": "SGML",
               "Abbrev": "ISO 8879:1986",
               "GlossDef": {
                  "para": "A meta-markup language, used to create markup languages such as DocBook.",
                  "GlossSeeAlso": ["GML", "XML"]
               },
               "GlossSee": "markup"
            }
         }
      }
   }
}

Angular.js ng-repeat filter by property having one of multiple values (OR of values)

I found a more generic solution with the most angular-native solution I can think. Basically you can pass your own comparator to the default filterFilter function. Here's plunker as well.

Difference between | and || or & and && for comparison

in C (and other languages probably) a single | or & is a bitwise comparison.
The double || or && is a logical comparison.
Edit: Be sure to read Mehrdad's comment below regarding "without short-circuiting"

In practice, since true is often equivalent to 1 and false is often equivalent to 0, the bitwise comparisons can sometimes be valid and return exactly the same result.

There was once a mission critical software component I ran a static code analyzer on and it pointed out that a bitwise comparison was being used where a logical comparison should have been. Since it was written in C and due to the arrangement of logical comparisons, the software worked just fine with either. Example:

if ( (altitide > 10000) & (knots > 100) )
...

What is "git remote add ..." and "git push origin master"?

This is an answer to this question (Export Heroku App to a new GitHub repo) which has been marked as duplicate of this one and redirected here.

I wanted to mirror my repo from Heroku to Github personal so that it shows all commits etc also which I made in Heroku. https://docs.github.com/en/free-pro-team@latest/github/importing-your-projects-to-github/importing-a-git-repository-using-the-command-line in Github documentation was useful.

Android ListView selected item stay highlighted

Simplistic way is,if you are using listview in a xml,use this attributes on your listview,

android:choiceMode="singleChoice"
android:listSelector="#your color code"

if not using xml,by programatically

listview.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);
listview.setSelector(android.R.color.holo_blue_light);

R plot: size and resolution

A reproducible example:

the_plot <- function()
{
  x <- seq(0, 1, length.out = 100)
  y <- pbeta(x, 1, 10)
  plot(
    x,
    y,
    xlab = "False Positive Rate",
    ylab = "Average true positive rate",
    type = "l"
  )
}

James's suggestion of using pointsize, in combination with the various cex parameters, can produce reasonable results.

png(
  "test.png",
  width     = 3.25,
  height    = 3.25,
  units     = "in",
  res       = 1200,
  pointsize = 4
)
par(
  mar      = c(5, 5, 2, 2),
  xaxs     = "i",
  yaxs     = "i",
  cex.axis = 2,
  cex.lab  = 2
)
the_plot()
dev.off()

Of course the better solution is to abandon this fiddling with base graphics and use a system that will handle the resolution scaling for you. For example,

library(ggplot2)

ggplot_alternative <- function()
{
  the_data <- data.frame(
    x <- seq(0, 1, length.out = 100),
    y = pbeta(x, 1, 10)
  )

ggplot(the_data, aes(x, y)) +
    geom_line() +
    xlab("False Positive Rate") +
    ylab("Average true positive rate") +
    coord_cartesian(0:1, 0:1)
}

ggsave(
  "ggtest.png",
  ggplot_alternative(),
  width = 3.25,
  height = 3.25,
  dpi = 1200
)

Any shortcut to initialize all array elements to zero?

While the other answers are correct (int array values are by default initialized to 0), if you wanted to explicitly do so (say for example if you wanted an array filled with the value 42), you can use the fill() method of the Arrays class:

int [] myarray = new int[num_elts];
Arrays.fill(myarray, 42);

Or if you're a fan of 1-liners, you can use the Collections.nCopies() routine:

Integer[] arr = Collections.nCopies(3, 42).toArray(new Integer[0]);

Would give arr the value:

[42, 42, 42]

(though it's Integer, and not int, if you need the primitive type you could defer to the Apache Commons ArrayUtils.toPrimitive() routine:

int [] primarr = ArrayUtils.toPrimitive(arr);

Internal Error 500 Apache, but nothing in the logs?

The answers by @eric-leschinski is correct.

But there is another case if your Server API is FPM/FastCGI (Default on Centos 8 or you can check use phpinfo() function)

In this case:

  1. Run phpinfo() in a php file;
  2. Looking for Loaded Configuration File param to see where is config file for your PHP.
  3. Edit config file like @eric-leschinski 's answer.
  4. Check Server API param. If your server only use apache handle API -> restart apache. If your server use php-fpm you must restart php-fpm service

    systemctl restart php-fpm

    Check the log file in php-fpm log folder. eg /var/log/php-fpm/www-error.log

Highlight all occurrence of a selected word?

First ensure that hlsearch is enabled by issuing the following command

:set hlsearch

You can also add this to your .vimrc file as set

set hlsearch

now when you use the quick search mechanism in command mode or a regular search command, all results will be highlighted. To move forward between results, press 'n' to move backwards press 'N'

In normal mode, to perform a quick search for the word under the cursor and to jump to the next occurrence in one command press '*', you can also search for the word under the cursor and move to the previous occurrence by pressing '#'

In normal mode, quick search can also be invoked with the

/searchterm<Enter>

to remove highlights on ocuurences use, I have bound this to a shortcut in my .vimrc

:nohl

Why is "forEach not a function" for this object?

Object does not have forEach, it belongs to Array prototype. If you want to iterate through each key-value pair in the object and take the values. You can do this:

Object.keys(a).forEach(function (key){
    console.log(a[key]);
});

Usage note: For an object v = {"cat":"large", "dog": "small", "bird": "tiny"};, Object.keys(v) gives you an array of the keys so you get ["cat","dog","bird"]

How to scroll table's "tbody" independent of "thead"?

The missing part is:

thead, tbody {
    display: block;
}

Demo

C compile error: Id returned 1 exit status

Using code::blocks , I have solved this error by doing :

workspace properties > build target > build target files

and checking every project file.

Invoking Java main method with parameters from Eclipse

AFAIK there isn't a built-in mechanism in Eclipse for this.

The closest you can get is to create a wrapper that prompts you for these values and invokes the (hardcoded) main. You then get you execution history as long as you don't clear terminated processes. Two variations on this are either to use JUNit, or to use injection or parameter so that your wrapper always connects to the correct class for its main.

How do I disable the resizable property of a textarea?

If you need deep support, you can use an old school technique:

textarea {
    max-width: /* desired fixed width */ px;
    min-width: /* desired fixed width */ px;
    min-height: /* desired fixed height */ px;
    max-height: /* desired fixed height */ px;
}

Easy way of running the same junit test over and over?

Inspired by the following resources:

Example

Create and use a @Repeat annotation as follows:

public class MyTestClass {

    @Rule
    public RepeatRule repeatRule = new RepeatRule();

    @Test
    @Repeat(10)
    public void testMyCode() {
        //your test code goes here
    }
}

Repeat.java

import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.METHOD;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention( RetentionPolicy.RUNTIME )
@Target({ METHOD, ANNOTATION_TYPE })
public @interface Repeat {
    int value() default 1;
}

RepeatRule.java

import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;

public class RepeatRule implements TestRule {

    private static class RepeatStatement extends Statement {
        private final Statement statement;
        private final int repeat;    

        public RepeatStatement(Statement statement, int repeat) {
            this.statement = statement;
            this.repeat = repeat;
        }

        @Override
        public void evaluate() throws Throwable {
            for (int i = 0; i < repeat; i++) {
                statement.evaluate();
            }
        }

    }

    @Override
    public Statement apply(Statement statement, Description description) {
        Statement result = statement;
        Repeat repeat = description.getAnnotation(Repeat.class);
        if (repeat != null) {
            int times = repeat.value();
            result = new RepeatStatement(statement, times);
        }
        return result;
    }
}

PowerMock

Using this solution with @RunWith(PowerMockRunner.class), requires updating to Powermock 1.6.5 (which includes a patch).

Count number of columns in a table row

<table id="table1">
<tr>
  <td colspan=4><input type="text" value="" /></td>

</tr>
<tr>
  <td><input type="text" value="" /></td>
  <td><input type="text" value="" /></td>
  <td><input type="text" value="" /></td>
  <td><input type="text" value="" /></td>

</tr>
<table>
<script>
    var row=document.getElementById('table1').rows.length;
    for(i=0;i<row;i++){
    console.log('Row '+parseFloat(i+1)+' : '+document.getElementById('table1').rows[i].cells.length +' column');
    }
</script>

Result:

Row 1 : 1 column
Row 2 : 4 column

Try-catch speeding up my code?

I'd have put this in as a comment as I'm really not certain that this is likely to be the case, but as I recall it doesn't a try/except statement involve a modification to the way the garbage disposal mechanism of the compiler works, in that it clears up object memory allocations in a recursive way off the stack. There may not be an object to be cleared up in this case or the for loop may constitute a closure that the garbage collection mechanism recognises sufficient to enforce a different collection method. Probably not, but I thought it worth a mention as I hadn't seen it discussed anywhere else.

I'm getting an error "invalid use of incomplete type 'class map'

Your first usage of Map is inside a function in the combat class. That happens before Map is defined, hence the error.

A forward declaration only says that a particular class will be defined later, so it's ok to reference it or have pointers to objects, etc. However a forward declaration does not say what members a class has, so as far as the compiler is concerned you can't use any of them until Map is fully declared.

The solution is to follow the C++ pattern of the class declaration in a .h file and the function bodies in a .cpp. That way all the declarations appear before the first definitions, and the compiler knows what it's working with.

Rails 3 check if attribute changed

Check out ActiveModel::Dirty (available on all models by default). The documentation is really good, but it lets you do things such as:

@user.street1_changed? # => true/false

Loading DLLs at runtime in C#

Right now, you're creating an instance of every type defined in the assembly. You only need to create a single instance of Class1 in order to call the method:

class Program
{
    static void Main(string[] args)
    {
        var DLL = Assembly.LoadFile(@"C:\visual studio 2012\Projects\ConsoleApplication1\ConsoleApplication1\DLL.dll");

        var theType = DLL.GetType("DLL.Class1");
        var c = Activator.CreateInstance(theType);
        var method = theType.GetMethod("Output");
        method.Invoke(c, new object[]{@"Hello"});

        Console.ReadLine();
    }
}

How to export JavaScript array info to csv (on client side)?

Based on the answers above I created this function that I have tested on IE 11, Chrome 36 and Firefox 29

function exportToCsv(filename, rows) {
    var processRow = function (row) {
        var finalVal = '';
        for (var j = 0; j < row.length; j++) {
            var innerValue = row[j] === null ? '' : row[j].toString();
            if (row[j] instanceof Date) {
                innerValue = row[j].toLocaleString();
            };
            var result = innerValue.replace(/"/g, '""');
            if (result.search(/("|,|\n)/g) >= 0)
                result = '"' + result + '"';
            if (j > 0)
                finalVal += ',';
            finalVal += result;
        }
        return finalVal + '\n';
    };

    var csvFile = '';
    for (var i = 0; i < rows.length; i++) {
        csvFile += processRow(rows[i]);
    }

    var blob = new Blob([csvFile], { type: 'text/csv;charset=utf-8;' });
    if (navigator.msSaveBlob) { // IE 10+
        navigator.msSaveBlob(blob, filename);
    } else {
        var link = document.createElement("a");
        if (link.download !== undefined) { // feature detection
            // Browsers that support HTML5 download attribute
            var url = URL.createObjectURL(blob);
            link.setAttribute("href", url);
            link.setAttribute("download", filename);
            link.style.visibility = 'hidden';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }
    }
}

For example: https://jsfiddle.net/jossef/m3rrLzk0/

How can I fix "Design editor is unavailable until a successful build" error?

In my case, it was because it didn't like that I left the minSDK and targeSdk in the manifest. Go figure.

Submit form and stay on same page?

The HTTP/CGI way to do this would be for your program to return an HTTP status code of 204 (No Content).

Open a link in browser with java button?

private void ButtonOpenWebActionPerformed(java.awt.event.ActionEvent evt) {                                         
    try {
        String url = "https://www.google.com";
        java.awt.Desktop.getDesktop().browse(java.net.URI.create(url));
    } catch (java.io.IOException e) {
        System.out.println(e.getMessage());
    }
}

80-characters / right margin line in Sublime Text 3

Yes, it is possible both in Sublime Text 2 and 3 (which you should really upgrade to if you haven't already). Select View ? Ruler ? 80 (there are several other options there as well). If you like to actually wrap your text at 80 columns, select View ? Word Wrap Column ? 80. Make sure that View ? Word Wrap is selected.

To make your selections permanent (the default for all opened files or views), open Preferences ? Settings—User and use any of the following rules:

{
    // set vertical rulers in specified columns.
    // Use "rulers": [80] for just one ruler
    // default value is []
    "rulers": [80, 100, 120],

    // turn on word wrap for source and text
    // default value is "auto", which means off for source and on for text
    "word_wrap": true,

    // set word wrapping at this column
    // default value is 0, meaning wrapping occurs at window width
    "wrap_width": 80
}

These settings can also be used in a .sublime-project file to set defaults on a per-project basis, or in a syntax-specific .sublime-settings file if you only want them to apply to files written in a certain language (Python.sublime-settings vs. JavaScript.sublime-settings, for example). Access these settings files by opening a file with the desired syntax, then selecting Preferences ? Settings—More ? Syntax Specific—User.

As always, if you have multiple entries in your settings file, separate them with commas , except for after the last one. The entire content should be enclosed in curly braces { }. Basically, make sure it's valid JSON.

If you'd like a key combo to automatically set the ruler at 80 for a particular view/file, or you are interested in learning how to set the value without using the mouse, please see my answer here.

Finally, as mentioned in another answer, you really should be using a monospace font in order for your code to line up correctly. Other types of fonts have variable-width letters, which means one 80-character line may not appear to be the same length as another 80-character line with different content, and your indentations will look all messed up. Sublime has monospace fonts set by default, but you can of course choose any one you want. Personally, I really like Liberation Mono. It has glyphs to support many different languages and Unicode characters, looks good at a variety of different sizes, and (most importantly for a programming font) clearly differentiates between 0 and O (digit zero and capital letter oh) and 1 and l (digit one and lowercase letter ell), which not all monospace fonts do, unfortunately. Version 2.0 and later of the font are licensed under the open-source SIL Open Font License 1.1 (here is the FAQ).

html form - make inputs appear on the same line

This test shows three blocks of two blocks together on the same line.

_x000D_
_x000D_
.group {
    display:block;
    box-sizing:border-box;
}
.group>div {
    display:inline-block;
    padding-bottom:4px;
}
.group>div>span,.group>div>div {
    width:200px;
    height:40px;
    text-align: center;
    padding-top:20px;
    padding-bottom:0px;
    display:inline-block;
    border:1px solid black;
    background-color:blue;
    color:white;
}

input[type=text] {
    height:1em;
}
_x000D_
<div class="group">
    <div>
        <span>First Name</span>
        <span><input type="text"/></span>
    </div>
    <div>
        <div>Last Name</div>
        <div><input type="text"/></div>
    </div>
    <div>
        <div>Address</div>
        <div><input type="text"/></div>
    </div>
</div>
_x000D_
_x000D_
_x000D_

PDO Prepared Inserts multiple rows in single query

This is how I did it:

First define the column names you'll use, or leave it blank and pdo will assume you want to use all the columns on the table - in which case you'll need to inform the row values in the exact order they appear on the table.

$cols = 'name', 'middleName', 'eMail';
$table = 'people';

Now, suppose you have a two dimensional array already prepared. Iterate it, and construct a string with your row values, as such:

foreach ( $people as $person ) {
if(! $rowVals ) {
$rows = '(' . "'$name'" . ',' . "'$middleName'" . ',' .           "'$eMail'" . ')';
} else { $rowVals  = '(' . "'$name'" . ',' . "'$middleName'" . ',' . "'$eMail'" . ')';
}

Now, what you just did was check if $rows was already defined, and if not, create it and store row values and the necessary SQL syntax so it will be a valid statement. Note that strings should go inside double quotes and single quotes, so they will be promptly recognized as such.

All it's left to do is prepare the statement and execute, as such:

$stmt = $db->prepare ( "INSERT INTO $table $cols VALUES $rowVals" );
$stmt->execute ();

Tested with up to 2000 rows so far, and the execution time is dismal. Will run some more tests and will get back here in case I have something further to contribute.

Regards.

How to add a new line in textarea element?

T.innerText = "Position of LF: " + t.value.indexOf("\n");

p3.innerText = t.value.replace("\n", "");

<textarea id="t">Line 1&#10;Line 2</textarea>

<p id='p3'></p>

Align labels in form next to input

While the solutions here are workable, more recent technology has made for what I think is a better solution. CSS Grid Layout allows us to structure a more elegant solution.

The CSS below provides a 2-column "settings" structure, where the first column is expected to be a right-aligned label, followed by some content in the second column. More complicated content can be presented in the second column by wrapping it in a <div>.

[As a side-note: I use CSS to add the ':' that trails each label, as this is a stylistic element - my preference.]

_x000D_
_x000D_
/* CSS */_x000D_
_x000D_
div.settings {_x000D_
    display:grid;_x000D_
    grid-template-columns: max-content max-content;_x000D_
    grid-gap:5px;_x000D_
}_x000D_
div.settings label       { text-align:right; }_x000D_
div.settings label:after { content: ":"; }
_x000D_
<!-- HTML -->_x000D_
_x000D_
<div class="settings">_x000D_
    <label>Label #1</label>_x000D_
    <input type="text" />_x000D_
_x000D_
    <label>Long Label #2</label>_x000D_
    <span>Display content</span>_x000D_
_x000D_
    <label>Label #3</label>_x000D_
    <input type="text" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

Stream file using ASP.NET MVC FileContentResult in a browser with a name?

This might be helpful for whoever else faces this problem. I finally figured out a solution. Turns out, even if we use the inline for "content-disposition" and specify a file name, the browsers still do not use the file name. Instead browsers try and interpret the file name based on the Path/URL.

You can read further on this URL: Securly download file inside browser with correct filename

This gave me an idea, I just created my URL route that would convert the URL and end it with the name of the file I wanted to give the file. So for e.g. my original controller call just consisted of passing the Order Id of the Order being printed. I was expecting the file name to be of the format Order{0}.pdf where {0} is the Order Id. Similarly for quotes, I wanted Quote{0}.pdf.

In my controller, I just went ahead and added an additional parameter to accept the file name. I passed the filename as a parameter in the URL.Action method.

I then created a new route that would map that URL to the format: http://localhost/ShoppingCart/PrintQuote/1054/Quote1054.pdf


routes.MapRoute("", "{controller}/{action}/{orderId}/{fileName}",
                new { controller = "ShoppingCart", action = "PrintQuote" }
                , new string[] { "x.x.x.Controllers" }
            );

This pretty much solved my issue. Hoping this helps someone!

Cheerz, Anup

Get Value From Select Option in Angular 4

_x000D_
_x000D_
export class MyComponent implements OnInit {_x000D_
_x000D_
  items: any[] = [_x000D_
    { id: 1, name: 'one' },_x000D_
    { id: 2, name: 'two' },_x000D_
    { id: 3, name: 'three' },_x000D_
    { id: 4, name: 'four' },_x000D_
    { id: 5, name: 'five' },_x000D_
    { id: 6, name: 'six' }_x000D_
  ];_x000D_
  selected: number = 1;_x000D_
_x000D_
  constructor() {_x000D_
  }_x000D_
  _x000D_
  ngOnInit() {_x000D_
  }_x000D_
  _x000D_
  selectOption(id: number) {_x000D_
    //getted from event_x000D_
    console.log(id);_x000D_
    //getted from binding_x000D_
    console.log(this.selected)_x000D_
  }_x000D_
_x000D_
}
_x000D_
<div>_x000D_
  <select (change)="selectOption($event.target.value)"_x000D_
  [(ngModel)]="selected">_x000D_
  <option [value]="item.id" *ngFor="let item of items">{{item.name}}</option>_x000D_
   </select>_x000D_
</div> 
_x000D_
_x000D_
_x000D_

How does one check if a table exists in an Android SQLite database?

Yep, turns out the theory in my edit was right: the problem that was causing the onCreate method not to run, was the fact that SQLiteOpenHelper objects should refer to databases, and not have a separate one for each table. Packing both tables into one SQLiteOpenHelper solved the problem.

Builder Pattern in Effective Java

Make the builder a static class. Then it will work. If it is non-static, it would require an instance of its owning class - and the point is not to have an instance of it, and even to forbid making instances without the builder.

public class NutritionFacts {
    public static class Builder {
    }
}

Reference: Nested classes

How does RewriteBase work in .htaccess

AFAIK, RewriteBase is only used to fix cases where mod_rewrite is running in a .htaccess file not at the root of a site and it guesses the wrong web path (as opposed to filesystem path) for the folder it is running in. So if you have a RewriteRule in a .htaccess in a folder that maps to http://example.com/myfolder you can use:

RewriteBase myfolder

If mod_rewrite isn't working correctly.

Trying to use it to achieve something unusual, rather than to fix this problem sounds like a recipe to getting very confused.

How do I check if an HTML element is empty using jQuery?

I found this to be the only reliable way (since Chrome & FF consider whitespaces and linebreaks as elements):

if($.trim($("selector").html())=='')

Passing headers with axios POST request

To set headers in an Axios POST request, pass the third object to the axios.post() call.

const token = '..your token..'

axios.post(url, {
  //...data
}, {
  headers: {
    'Authorization': `Basic ${token}` 
  }
})

To set headers in an Axios GET request, pass a second object to the axios.get() call.

const token = '..your token..' 

axios.get(url, {
  headers: {
    'Authorization': `Basic ${token}`
  }
})

Cheers!! Read Simple Write Simple

How can I change an element's class with JavaScript?

classList DOM API:

A very convenient manner of adding and removing classes is the classList DOM API. This API allows us to select all classes of a specific DOM element in order to modify the list using javascript. For example:

_x000D_
_x000D_
const el = document.getElementById("main");_x000D_
console.log(el.classList);
_x000D_
<div class="content wrapper animated" id="main"></div>
_x000D_
_x000D_
_x000D_

We can observe in the log that we are getting back an object with not only the classes of the element, but also many auxiliary methods and properties. This object inherits from the interface DOMTokenList, an interface which is used in the DOM to represent a set of space separated tokens (like classes).

Example:

_x000D_
_x000D_
const el = document.getElementById('container');_x000D_
_x000D_
_x000D_
function addClass () {_x000D_
   el.classList.add('newclass');_x000D_
}_x000D_
_x000D_
_x000D_
function replaceClass () {_x000D_
     el.classList.replace('foo', 'newFoo');_x000D_
}_x000D_
_x000D_
_x000D_
function removeClass () {_x000D_
       el.classList.remove('bar');_x000D_
}
_x000D_
button{_x000D_
  margin: 20px;_x000D_
}_x000D_
_x000D_
.foo{_x000D_
  color: red;_x000D_
}_x000D_
_x000D_
.newFoo {_x000D_
  color: blue;_x000D_
}_x000D_
_x000D_
.bar{_x000D_
  background-color:powderblue;_x000D_
}_x000D_
_x000D_
.newclass{_x000D_
  border: 2px solid green;_x000D_
}
_x000D_
<div class="foo bar" id="container">_x000D_
  "Sed ut perspiciatis unde omnis _x000D_
  iste natus error sit voluptatem accusantium doloremque laudantium, _x000D_
  totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et _x000D_
  quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam _x000D_
  voluptatem quia voluptas _x000D_
 </div>_x000D_
  _x000D_
<button onclick="addClass()">AddClass</button>_x000D_
  _x000D_
<button onclick="replaceClass()">ReplaceClass</button>_x000D_
  _x000D_
<button onclick="removeClass()">removeClass</button>_x000D_
  
_x000D_
_x000D_
_x000D_

How to do Base64 encoding in node.js?

crypto now supports base64 (reference):

cipher.final('base64') 

So you could simply do:

var cipher = crypto.createCipheriv('des-ede3-cbc', encryption_key, iv);
var ciph = cipher.update(plaintext, 'utf8', 'base64');
ciph += cipher.final('base64');

var decipher = crypto.createDecipheriv('des-ede3-cbc', encryption_key, iv);
var txt = decipher.update(ciph, 'base64', 'utf8');
txt += decipher.final('utf8');

Colon (:) in Python list index

a[len(a):] - This gets you the length of a to the end. It selects a range. If you reverse a[:len(a)] it will get you the beginning to whatever is len(a).

Class Diagrams in VS 2017

the following procedure worked for me:

  • Close VS.
  • Run Visual Studio Installer.
  • Click on the 'Modify' button under 'Visual Studio Professional 2017'
  • In the new window, scroll down and select 'Visual Studio Extension Development' under 'Other Toolsets'.
  • Then on the right, if not selected yet, click on 'Class Designer'
  • Click on 'Modify' to confirm

How to convert int to float in python?

Other than John's answer, you could also make one of the variable float, and the result will yield float.

>>> 144 / 314.0
0.4585987261146497

How to convert View Model into JSON object in ASP.NET MVC?

<htmltag id=’elementId’ data-ZZZZ’=’@Html.Raw(Json.Encode(Model))’ />

Refer https://highspeedlowdrag.wordpress.com/2014/08/23/mvc-data-to-jquery-data/

I did below and it works like charm.

<input id="hdnElement" class="hdnElement" type="hidden" value='@Html.Raw(Json.Encode(Model))'>

Open a file with Notepad in C#

this will open the file with the default windows program (notepad if you haven't changed it);

Process.Start(@"c:\myfile.txt")

How to display the value of the bar on each bar with pyplot.barh()?

Check this link Matplotlib Gallery This is how I used the code snippet of autolabel.

    def autolabel(rects):
    """Attach a text label above each bar in *rects*, displaying its height."""
    for rect in rects:
        height = rect.get_height()
        ax.annotate('{}'.format(height),
                    xy=(rect.get_x() + rect.get_width() / 2, height),
                    xytext=(0, 3),  # 3 points vertical offset
                    textcoords="offset points",
                    ha='center', va='bottom')
        
temp = df_launch.groupby(['yr_mt','year','month'])['subs_trend'].agg(subs_count='sum').sort_values(['year','month']).reset_index()
_, ax = plt.subplots(1,1, figsize=(30,10))
bar = ax.bar(height=temp['subs_count'],x=temp['yr_mt'] ,color ='g')
autolabel(bar)

ax.set_title('Monthly Change in Subscribers from Launch Date')
ax.set_ylabel('Subscriber Count Change')
ax.set_xlabel('Time')
plt.show()

pros and cons between os.path.exists vs os.path.isdir

Most of the time, it is the same.

But, path can exist physically whereas path.exists() returns False. This is the case if os.stat() returns False for this file.

If path exists physically, then path.isdir() will always return True. This does not depend on platform.

Sqlite in chrome

You can use Web SQL API which is an ordinary SQLite database in your browser and you can open/modify it like any other SQLite databases for example with Lita.

Chrome locates databases automatically according to domain names or extension id. A few months ago I posted on my blog short article on how to delete Chrome's database because when you're testing some functionality it's quite useful.

SQL: capitalize first letter only

Are you asking for renaming column itself or capitalise the data inside column? If its data you've to change, then use this:

UPDATE [yourtable]
SET word=UPPER(LEFT(word,1))+LOWER(SUBSTRING(word,2,LEN(word)))

If you just wanted to change it only for displaying and do not need the actual data in table to change:

SELECT UPPER(LEFT(word,1))+LOWER(SUBSTRING(word,2,LEN(word))) FROM [yourtable]

Hope this helps.

EDIT: I realised about the '-' so here is my attempt to solve this problem in a function.

CREATE FUNCTION [dbo].[CapitalizeFirstLetter]
(
--string need to format
@string VARCHAR(200)--increase the variable size depending on your needs.
)
RETURNS VARCHAR(200)
AS

BEGIN
--Declare Variables
DECLARE @Index INT,
@ResultString VARCHAR(200)--result string size should equal to the @string variable size
--Initialize the variables
SET @Index = 1
SET @ResultString = ''
--Run the Loop until END of the string

WHILE (@Index <LEN(@string)+1)
BEGIN
IF (@Index = 1)--first letter of the string
BEGIN
--make the first letter capital
SET @ResultString =
@ResultString + UPPER(SUBSTRING(@string, @Index, 1))
SET @Index = @Index+ 1--increase the index
END

-- IF the previous character is space or '-' or next character is '-'

ELSE IF ((SUBSTRING(@string, @Index-1, 1) =' 'or SUBSTRING(@string, @Index-1, 1) ='-' or SUBSTRING(@string, @Index+1, 1) ='-') and @Index+1 <> LEN(@string))
BEGIN
--make the letter capital
SET
@ResultString = @ResultString + UPPER(SUBSTRING(@string,@Index, 1))
SET
@Index = @Index +1--increase the index
END
ELSE-- all others
BEGIN
-- make the letter simple
SET
@ResultString = @ResultString + LOWER(SUBSTRING(@string,@Index, 1))
SET
@Index = @Index +1--incerase the index
END
END--END of the loop

IF (@@ERROR
<> 0)-- any error occur return the sEND string
BEGIN
SET
@ResultString = @string
END
-- IF no error found return the new string
RETURN @ResultString
END

So then the code would be:

UPDATE [yourtable]
SET word=dbo.CapitalizeFirstLetter([STRING TO GO HERE])

Is it possible to play music during calls so that the partner can hear it ? Android

Yes it is possible in Sony ericssion xylophone w20 .I have got this phone in 2010.but yet this type of phone I have not seen.

How to set root password to null

My variant for MySQL 5.7:

Stop service mysql:

$ sudo service mysql stop

Running in Safe Mode:

$ sudo mysqld_safe --skip-grant-tables --skip-networking

(above line is the whole command)

Open a new terminal window:

$ mysql -u root

$ mysql use mysql;

$ mysql update user set authentication_string=password('password') where user='root';

$ mysql update user set plugin="mysql_native_password" where User='root';

$ mysql flush privileges;
$ mysql quit;

Run the mysql service:

$ sudo service mysql start

SVN Error: Commit blocked by pre-commit hook (exit code 1) with output: Error: n/a (6)

Could it be that you have not entered a commit message? According to their twitter feed: "New functionality added. Block users from committing work without writing a log message. Find in the resources section of your control panel".

"Continue" (to next iteration) on VBScript

I use to use the Do, Loop a lot but I have started using a Sub or a Function that I could exit out of instead. It just seemed cleaner to me. If any variables you need are not global you will need to pass them to the Sub also.

For i=1 to N
 DoWork i
Next

Sub DoWork(i)
    [Code]
    If Condition1 Then
      Exit Sub
    End If

    [MoreCode]
    If Condition2 Then
      Exit Sub
    End If

    [MoreCode]
    If Condition2 Then
      Exit Sub
    End If

    [...]
End Sub

Best way to format integer as string with leading zeros?

You can use the zfill() method to pad a string with zeros:

In [3]: str(1).zfill(2)
Out[3]: '01'

Combine Multiple child rows into one row MYSQL

Joe Edel's answer to himself is actually the right approach to resolve the pivot problem.

Basically the idea is to list out the columns in the base table firstly, and then any number of options.value from the joint option table. Just left join the same option table multiple times in order to get all the options.

What needs to be done by the programming language is to build this query dynamically according to a list of options needs to be queried.

Leave only two decimal places after the dot

double doublVal = 123.45678;

There are two ways.

  1. for display in string:

    String.Format("{0:0.00}", doublVal );
    
  2. for geting again Double

    doublVal = Convert.ToDouble(String.Format("{0:0.00}", doublVal ));
    

How to modify STYLE attribute of element with known ID using JQuery

Not sure I completely understand the question but:

$(":button.brown").click(function() {
  $(":button.brown.selected").removeClass("selected");
  $(this).addClass("selected");
});

seems to be along the lines of what you want.

I would certainly recommend using classes instead of directly setting CSS, which is problematic for several reasons (eg removing styles is non-trivial, removing classes is easy) but if you do want to go that way:

$("...").css("background", "brown");

But when you want to reverse that change, what do you set it to?

Does bootstrap have builtin padding and margin classes?

Bootstrap versions before 4 and 5 do not define ml, mr, pl, and pr.

Bootstrap versions 4 and 5 define the classes of ml, mr, pl, and pr.

For example:

mr--1
ml--1
pr--1
pl--1

Random String Generator Returning Same String

Yet another version of string generator. Simple, without fancy math and magic digits. But with some magic string which specifies allowed characters.

Update: I made generator static, so it will not return same string when called multiple times. However this code is not thread-safe and is definitely not cryptographically secure.

For password generation System.Security.Cryptography.RNGCryptoServiceProvider should be used.

private Random _random = new Random(Environment.TickCount);

public string RandomString(int length)
{
    string chars = "0123456789abcdefghijklmnopqrstuvwxyz";
    StringBuilder builder = new StringBuilder(length);

    for (int i = 0; i < length; ++i)
        builder.Append(chars[_random.Next(chars.Length)]);

    return builder.ToString();
}

Connect multiple devices to one device via Bluetooth

Yes you can do so and I have created a library for the same.
This allows you to connect up-to four devices to the main server device creating different channels for each client and running interactions on different threads.
To use this library simple add compile com.mdg.androble:library:0.1.2 in dependency section of your build.gradle .

getResourceAsStream returns null

Roughly speaking:

getClass().getResource("/") ~= Thread.currentThread().getContextClassLoader().getResource(".")

Suppose your project structure is like the following:

+-- src
¦   +-- main
¦   +-- test
¦   +-- test
¦       +-- java
¦       ¦   +-- com
¦       ¦       +-- github
¦       ¦           +-- xyz
¦       ¦               +-- proj
¦       ¦                   +-- MainTest.java
¦       ¦                   +-- TestBase.java
¦       +-- resources
¦           +-- abcd.txt
+-- target
    +-- test-classes
        +-- com
        +-- abcd.txt

// in MainClass.java
this.getClass.getResource("/") -> "~/proj_dir/target/test-classes/"
this.getClass.getResource(".") -> "~/proj_dir/target/test-classes/com/github/xyz/proj/"
Thread.currentThread().getContextClassLoader().getResources(".") -> "~/proj_dir/target/test-classes/"
Thread.currentThread().getContextClassLoader().getResources("/") ->  null

Creating a folder if it does not exists - "Item already exists"

I was not even concentrating, here is how to do it

$DOCDIR = [Environment]::GetFolderPath("MyDocuments")
$TARGETDIR = '$DOCDIR\MatchedLog'
if(!(Test-Path -Path $TARGETDIR )){
    New-Item -ItemType directory -Path $TARGETDIR
}

How to create a jQuery plugin with methods?

According to the jQuery Plugin Authoring page (http://docs.jquery.com/Plugins/Authoring), it's best not to muddy up the jQuery and jQuery.fn namespaces. They suggest this method:

(function( $ ){

    var methods = {
        init : function(options) {

        },
        show : function( ) {    },// IS
        hide : function( ) {  },// GOOD
        update : function( content ) {  }// !!!
    };

    $.fn.tooltip = function(methodOrOptions) {
        if ( methods[methodOrOptions] ) {
            return methods[ methodOrOptions ].apply( this, Array.prototype.slice.call( arguments, 1 ));
        } else if ( typeof methodOrOptions === 'object' || ! methodOrOptions ) {
            // Default to "init"
            return methods.init.apply( this, arguments );
        } else {
            $.error( 'Method ' +  methodOrOptions + ' does not exist on jQuery.tooltip' );
        }    
    };


})( jQuery );

Basically you store your functions in an array (scoped to the wrapping function) and check for an entry if the parameter passed is a string, reverting to a default method ("init" here) if the parameter is an object (or null).

Then you can call the methods like so...

$('div').tooltip(); // calls the init method
$('div').tooltip({  // calls the init method
  foo : 'bar'
});
$('div').tooltip('hide'); // calls the hide method
$('div').tooltip('update', 'This is the new tooltip content!'); // calls the update method

Javascripts "arguments" variable is an array of all the arguments passed so it works with arbitrary lengths of function parameters.

Create a GUID in Java

It depends what kind of UUID you want.

  • The standard Java UUID class generates Version 4 (random) UUIDs. (UPDATE - Version 3 (name) UUIDs can also be generated.) It can also handle other variants, though it cannot generate them. (In this case, "handle" means construct UUID instances from long, byte[] or String representations, and provide some appropriate accessors.)

  • The Java UUID Generator (JUG) implementation purports to support "all 3 'official' types of UUID as defined by RFC-4122" ... though the RFC actually defines 4 types and mentions a 5th type.

For more information on UUID types and variants, there is a good summary in Wikipedia, and the gory details are in RFC 4122 and the other specifications.

Streaming a video file to an html5 video player with Node.js so that the video controls continue to work?

Firstly create app.js file in the directory you want to publish.

var http = require('http');
var fs = require('fs');
var mime = require('mime');
http.createServer(function(req,res){
    if (req.url != '/app.js') {
    var url = __dirname + req.url;
        fs.stat(url,function(err,stat){
            if (err) {
            res.writeHead(404,{'Content-Type':'text/html'});
            res.end('Your requested URI('+req.url+') wasn\'t found on our server');
            } else {
            var type = mime.getType(url);
            var fileSize = stat.size;
            var range = req.headers.range;
                if (range) {
                    var parts = range.replace(/bytes=/, "").split("-");
                var start = parseInt(parts[0], 10);
                    var end = parts[1] ? parseInt(parts[1], 10) : fileSize-1;
                    var chunksize = (end-start)+1;
                    var file = fs.createReadStream(url, {start, end});
                    var head = {
                'Content-Range': `bytes ${start}-${end}/${fileSize}`,
                'Accept-Ranges': 'bytes',
                'Content-Length': chunksize,
                'Content-Type': type
                }
                    res.writeHead(206, head);
                    file.pipe(res);
                    } else {    
                    var head = {
                'Content-Length': fileSize,
                'Content-Type': type
                    }
                res.writeHead(200, head);
                fs.createReadStream(url).pipe(res);
                    }
            }
        });
    } else {
    res.writeHead(403,{'Content-Type':'text/html'});
    res.end('Sorry, access to that file is Forbidden');
    }
}).listen(8080);

Simply run node app.js and your server shall be running on port 8080. Besides video it can stream all kinds of files.

How to find the lowest common ancestor of two nodes in any binary tree?

In scala, you can:

  abstract class Tree
  case class Node(a:Int, left:Tree, right:Tree) extends Tree
  case class Leaf(a:Int) extends Tree

  def lca(tree:Tree, a:Int, b:Int):Tree = {
    tree match {
      case Node(ab,l,r) => {
        if(ab==a || ab ==b) tree else {
          val temp = lca(l,a,b);
          val temp2 = lca(r,a,b);
          if(temp!=null && temp2 !=null)
            tree
          else if (temp==null && temp2==null)
            null
          else if (temp==null) r else l
        }

      }
      case Leaf(ab) => if(ab==a || ab ==b) tree else null
    }
  }

How to set a parameter in a HttpServletRequest?

The most upvoted solution generally works but for Spring and/or Spring Boot, the values will not wire to parameters in controller methods annotated with @RequestParam unless you specifically implemented getParameterValues(). I combined the solution(s) here and from this blog:

import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

public class MutableHttpRequest extends HttpServletRequestWrapper {

    private final Map<String, String[]> mutableParams = new HashMap<>();

    public MutableHttpRequest(final HttpServletRequest request) {
        super(request);
    }

    public MutableHttpRequest addParameter(String name, String value) {
        if (value != null)
            mutableParams.put(name, new String[] { value });

        return this;
    }

    @Override
    public String getParameter(final String name) {
        String[] values = getParameterMap().get(name);

        return Arrays.stream(values)
                .findFirst()
                .orElse(super.getParameter(name));
    }

    @Override
    public Map<String, String[]> getParameterMap() {
        Map<String, String[]> allParameters = new HashMap<>();
        allParameters.putAll(super.getParameterMap());
        allParameters.putAll(mutableParams);

        return Collections.unmodifiableMap(allParameters);
    }

    @Override
    public Enumeration<String> getParameterNames() {
        return Collections.enumeration(getParameterMap().keySet());
    }

    @Override
    public String[] getParameterValues(final String name) {
        return getParameterMap().get(name);
    }
}

note that this code is not super-optimized but it works.

Javascript counting number of objects in object

The easiest way to do this, with excellent performance and compatibility with both old and new browsers, is to include either Lo-Dash or Underscore in your page.

Then you can use either _.size(object) or _.keys(object).length

For your obj.Data, you could test this with:

console.log( _.size(obj.Data) );

or:

console.log( _.keys(obj.Data).length );

Lo-Dash and Underscore are both excellent libraries; you would find either one very useful in your code. (They are rather similar to each other; Lo-Dash is a newer version with some advantanges.)

Alternatively, you could include this function in your code, which simply loops through the object's properties and counts them:

function ObjectLength( object ) {
    var length = 0;
    for( var key in object ) {
        if( object.hasOwnProperty(key) ) {
            ++length;
        }
    }
    return length;
};

You can test this with:

console.log( ObjectLength(obj.Data) );

That code is not as fast as it could be in modern browsers, though. For a version that's much faster in modern browsers and still works in old ones, you can use:

function ObjectLength_Modern( object ) {
    return Object.keys(object).length;
}

function ObjectLength_Legacy( object ) {
    var length = 0;
    for( var key in object ) {
        if( object.hasOwnProperty(key) ) {
            ++length;
        }
    }
    return length;
}

var ObjectLength =
    Object.keys ? ObjectLength_Modern : ObjectLength_Legacy;

and as before, test it with:

console.log( ObjectLength(obj.Data) );

This code uses Object.keys(object).length in modern browsers and falls back to counting in a loop for old browsers.

But if you're going to all this work, I would recommend using Lo-Dash or Underscore instead and get all the benefits those libraries offer.

I set up a jsPerf that compares the speed of these various approaches. Please run it in any browsers you have handy to add to the tests.

Thanks to Barmar for suggesting Object.keys for newer browsers in his answer.

format a number with commas and decimals in C# (asp.net MVC3)

Try with

ToString("#,##0.###")

Produces:

1234.55678 => 1,234.556

1234 => 1,234

How to encrypt a large file in openssl using public key

I found the instructions at http://www.czeskis.com/random/openssl-encrypt-file.html useful.

To paraphrase the linked site with filenames from your example:

Generate a symmetric key because you can encrypt large files with it

openssl rand -base64 32 > key.bin

Encrypt the large file using the symmetric key

openssl enc -aes-256-cbc -salt -in myLargeFile.xml \
  -out myLargeFile.xml.enc -pass file:./key.bin

Encrypt the symmetric key so you can safely send it to the other person

openssl rsautl -encrypt -inkey public.pem -pubin -in key.bin -out key.bin.enc

Destroy the un-encrypted symmetric key so nobody finds it

shred -u key.bin

At this point, you send the encrypted symmetric key (key.bin.enc) and the encrypted large file (myLargeFile.xml.enc) to the other person

The other person can then decrypt the symmetric key with their private key using

openssl rsautl -decrypt -inkey private.pem -in key.bin.enc -out key.bin

Now they can use the symmetric key to decrypt the file

openssl enc -d -aes-256-cbc -in myLargeFile.xml.enc \
  -out myLargeFile.xml -pass file:./key.bin

And you're done. The other person has the decrypted file and it was safely sent.

Collection was modified; enumeration operation may not execute in ArrayList

You are removing the item during a foreach, yes? Simply, you can't. There are a few common options here:

  • use List<T> and RemoveAll with a predicate
  • iterate backwards by index, removing matching items

    for(int i = list.Count - 1; i >= 0; i--) {
        if({some test}) list.RemoveAt(i);
    }
    
  • use foreach, and put matching items into a second list; now enumerate the second list and remove those items from the first (if you see what I mean)

Checking for an empty file in C++

C++17 solution:

#include <filesystem>

const auto filepath = <path to file> (as a std::string or std::filesystem::path)

auto isEmpty = (std::filesystem::file_size(filepath) == 0);

Assumes you have the filepath location stored, I don't think you can extract a filepath from an std::ifstream object.

How do I stop Notepad++ from showing autocomplete for all words in the file

Notepad++ provides 2 types of features:

  • Auto-completion that read the open file and provide suggestion of words and/or functions within the file
  • Suggestion with the arguments of functions (specific to the language)

Based on what you write, it seems what you want is auto-completion on function only + suggestion on arguments.

To do that, you just need to change a setting.

  1. Go to Settings > Preferences... > Auto-completion
  2. Check Enable Auto-completion on each input
  3. Select Function completion and not Word completion
  4. Check Function parameter hint on input (if you have this option)

On version 6.5.5 of Notepad++, I have this setting settings

Some documentation about auto-completion is available in Notepad++ Wiki.

Using CSS how to change only the 2nd column of a table

You could designate a class for each cell in the second column.

<table>
<tr><td>Column 1</td><td class="col2">Col 2</td></tr>
<tr><td>Column 1</td><td class="col2">Col 2</td></tr>
<tr><td>Column 1</td><td class="col2">Col 2</td></tr>
<tr><td>Column 1</td><td class="col2">Col 2</td></tr>
</table>

Clone only one branch

From the announcement Git 1.7.10 (April 2012):

  • git clone learned --single-branch option to limit cloning to a single branch (surprise!); tags that do not point into the history of the branch are not fetched.

Git actually allows you to clone only one branch, for example:

git clone -b mybranch --single-branch git://sub.domain.com/repo.git

Note: Also you can add another single branch or "undo" this action.

Java Refuses to Start - Could not reserve enough space for object heap

Steps to be execute .... to resolve the Error occurred during initialization of VM Could not reserve enough space for object heap Could not create the Java virtual machine.

Step 1: Reduce the memory what earlier you used.. java -Xms128m -Xmx512m -cp simple.jar

step 2: Remove the RAM some time from the mother board and plug it and restart * may it will release the blocking heap area memory.. java -Xms512m -Xmx1024m -cp simple.jar

Hope it will work well now... :-)

AngularJS - convert dates in controller

All solutions here doesn't really bind the model to the input because you will have to change back the dateAsString to be saved as date in your object (in the controller after the form will be submitted).

If you don't need the binding effect, but just to show it in the input,

a simple could be:

<input type="date" value="{{ item.date | date: 'yyyy-MM-dd' }}" id="item_date" />

Then, if you like, in the controller, you can save the edited date in this way:

  $scope.item.date = new Date(document.getElementById('item_date').value).getTime();

be aware: in your controller, you have to declare your item variable as $scope.item in order for this to work.

Bootstrap 3 dropdown select

The dropdown list appearing like that depends on what your browser is, as it is not possible to style this away for some. It looks like yours is IE9, but would look quite different in Chrome.

You could look to use something like this:

http://silviomoreto.github.io/bootstrap-select/

Which will make your selectboxes more consistent cross browser.

The simplest way to comma-delimit a list?

Java 8 provides several new ways to do this:

Example:

// Util method for strings and other char sequences
List<String> strs = Arrays.asList("1", "2", "3");
String listStr1 = String.join(",", strs);

// For any type using streams and collectors
List<Object> objs = Arrays.asList(1, 2, 3);
String listStr2 = objs.stream()
    .map(Object::toString)
    .collect(joining(",", "[", "]"));

// Using the new StringJoiner class
StringJoiner joiner = new StringJoiner(", ", "[", "]");
joiner.setEmptyValue("<empty>");
for (Integer i : objs) {
  joiner.add(i.toString());
}
String listStr3 = joiner.toString();

The approach using streams assumes import static java.util.stream.Collectors.joining;.

About the Full Screen And No Titlebar from manifest

In AndroidManifest.xml, set android:theme="@android:style/Theme.NoTitleBar.Fullscreen"in application tag.

Individual activities can override the default by setting their own theme attributes.

Resizing image in Java

If you have an java.awt.Image, rezising it doesn't require any additional libraries. Just do:

Image newImage = yourImage.getScaledInstance(newWidth, newHeight, Image.SCALE_DEFAULT);

Ovbiously, replace newWidth and newHeight with the dimensions of the specified image.
Notice the last parameter: it tells to the runtime the algorithm you want to use for resizing.

There are algorithms that produce a very precise result, however these take a large time to complete.
You can use any of the following algorithms:

See the Javadoc for more info.

Jackson how to transform JsonNode to ArrayNode without casting?

I would assume at the end of the day you want to consume the data in the ArrayNode by iterating it. For that:

Iterator<JsonNode> iterator = datasets.withArray("datasets").elements();
while (iterator.hasNext()) 
        System.out.print(iterator.next().toString() + " "); 

or if you're into streams and lambda functions:

import com.google.common.collect.Streams;
Streams.stream(datasets.withArray("datasets").elements())
    .forEach( item -> System.out.print(item.toString()) )

This Handler class should be static or leaks might occur: IncomingHandler

This way worked well for me, keeps code clean by keeping where you handle the message in its own inner class.

The handler you wish to use

Handler mIncomingHandler = new Handler(new IncomingHandlerCallback());

The inner class

class IncomingHandlerCallback implements Handler.Callback{

        @Override
        public boolean handleMessage(Message message) {

            // Handle message code

            return true;
        }
}

Algorithm to calculate the number of divisors of a given number

i guess this one will be handy as well as precise

script.pyton

>>>factors=[ x for x in range (1,n+1) if n%x==0] print len(factors)

adding x and y axis labels in ggplot2

[Note: edited to modernize ggplot syntax]

Your example is not reproducible since there is no ex1221new (there is an ex1221 in Sleuth2, so I guess that is what you meant). Also, you don't need (and shouldn't) pull columns out to send to ggplot. One advantage is that ggplot works with data.frames directly.

You can set the labels with xlab() and ylab(), or make it part of the scale_*.* call.

library("Sleuth2")
library("ggplot2")
ggplot(ex1221, aes(Discharge, Area)) +
  geom_point(aes(size=NO3)) + 
  scale_size_area() + 
  xlab("My x label") +
  ylab("My y label") +
  ggtitle("Weighted Scatterplot of Watershed Area vs. Discharge and Nitrogen Levels (PPM)")

enter image description here

ggplot(ex1221, aes(Discharge, Area)) +
  geom_point(aes(size=NO3)) + 
  scale_size_area("Nitrogen") + 
  scale_x_continuous("My x label") +
  scale_y_continuous("My y label") +
  ggtitle("Weighted Scatterplot of Watershed Area vs. Discharge and Nitrogen Levels (PPM)")

enter image description here

An alternate way to specify just labels (handy if you are not changing any other aspects of the scales) is using the labs function

ggplot(ex1221, aes(Discharge, Area)) +
  geom_point(aes(size=NO3)) + 
  scale_size_area() + 
  labs(size= "Nitrogen",
       x = "My x label",
       y = "My y label",
       title = "Weighted Scatterplot of Watershed Area vs. Discharge and Nitrogen Levels (PPM)")

which gives an identical figure to the one above.

Bootstrap Modal Backdrop Remaining

Using the code below continuously adds 7px padding on the body element every time you open and close a modal.

$('modalId').modal('hide');
$('body').removeClass('modal-open');
$('.modal-backdrop').remove();`

For those who still use Bootstrap 3, here is a hack'ish workaround.

$('#modalid').modal('hide');
$('.modal-backdrop').hide();
document.body.style.paddingRight = '0'
document.getElementsByTagName("body")[0].style.overflowY = "auto";

How do I change the default index page in Apache?

You can also set DirectoryIndex in apache's httpd.conf file.

CentOS keeps this file in /etc/httpd/conf/httpd.conf Debian: /etc/apache2/apache2.conf

Open the file in your text editor and find the line starting with DirectoryIndex

To load landing.html as a default (but index.html if that's not found) change this line to read:

DirectoryIndex  landing.html index.html

How do I set up access control in SVN?

One gotcha which caught me out:

[repos:/path/to/dir/] # this won't work

but

[repos:/path/to/dir]  # this is right

You need to not include a trailing slash on the directory, or you'll see 403 for the OPTIONS request.

Differences between key, superkey, minimal superkey, candidate key and primary key

I have always found it difficult to remember all the keys; so I keep the below notes handy, hope they help someone! Let me know if it can be improved.

  • Key: An attribute or combination of attributes that uniquely identify an entity/record in a relational table.

  • PK: A single key that is unique and not-null. It is one of the candidate keys.

  • Foreign Key: FK is a key in one table (child) that uniquely identifies a row of another table (parent). A FK is not-unique in the child table. It is a candidate key in the parent table. Referential integrity is maintained as the value in FK is present as a value in PK in parent table else it is NULL.

  • Unique Key: A unique key that may or may not be NULL

  • Natural key: PK in OLTP. It may be a PK in OLAP.

  • Surrogate Key: It is the Surrogate PK in OLAP acting as the substitute of the PK in OLTP. Artificial key generated internally in OLAP.

  • Composite Key: PK made up of multiple attributes

  • SuperKey: A key that can be uniquely used to identify a database record, that may contain extra attributes that are not necessary to uniquely identify records.

  • Candidate Key: A candidate key can be uniquely used to identify a database record without any extraneous data. They are Not Null and unique. It is a minimal super-key.

  • Alternate Key: A candidate key that is not the primary key is called an alternate key.

  • Candidate Key/s with Extraneous data: Consider that can be used to identify a record in the Employee table but candidate key alone is sufficient for this task. So becomes the extraneous data.

Note that the PK, Foreign Key, Unique Key, Natural key, Surrogate Key, Composite Key are defined as Database objects; where the Natural key is a PK in the OLTP and could be a PK in the target OLAP. For the rest of the keys, it's up to the DB designer/architect to decide whether unique/not-null/referential integrity constraints need to enforced or not.

Below I have tried to use set theory to simplify the representation of the membership of the keys w.r.t. each other.

key = { All of the below keys   }
PK  = { PK  }
Foreign Key = { Key with Not Null constraint    }
Unique Key  = { {Candidate Key/s}, {attributes containing NULL} }
Natural key = { PK  }
Surrogate Key   = { PK  }
Composite Key   = { PK  }
Super Key   = { {Candidate Key/s}, {Candidate Key/s with Extraneous data}   }
Candidate Key   = { PK, {Alternate Key/s}   }
Alternate Key   = { {Candidate Keys} - PK   }
Candidate Key/s with Extraneous data    = {     }

I have summarized it below:

Database Keys

Notes: an-overview-of-the-database-keys-primary-key-composite-key-surrogate-key-et-al

How to check postgres user and password?

You will not be able to find out the password he chose. However, you may create a new user or set a new password to the existing user.

Usually, you can login as the postgres user:

Open a Terminal and do sudo su postgres. Now, after entering your admin password, you are able to launch psql and do

CREATE USER yourname WITH SUPERUSER PASSWORD 'yourpassword';

This creates a new admin user. If you want to list the existing users, you could also do

\du

to list all users and then

ALTER USER yourusername WITH PASSWORD 'yournewpass';

How do I compare two files using Eclipse? Is there any option provided by Eclipse?

If your compairing javascript you might find it not displaying.

https://bugs.eclipse.org/bugs/show_bug.cgi?id=509820

Here is a workround...

  • Window > Preferences > Compare/Patch > General Tab
  • Deselect checkbox next to "Open structure compare automatically"

How can I shrink the drawable on a button?

I have found a very simple and effective XML solution that doesn't require ImageButton

Make a drawable file for your image as below and use it for android:drawableLeft

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item
    android:id="@+id/half_overlay"
    android:drawable="@drawable/myDrawable"
    android:width="40dp"
    android:height="40dp"
    />

</layer-list>

You can set the image size with android:width and android:height properties.

This way you could at least get the same size for different screens.

The drawback is that it is not exactly like fitXY which would scale image width to fit X and scale image height accordingly.

git returns http error 407 from proxy after CONNECT

Maybe you are already using the system proxy setting - in this case unset all git proxies will work:

git config --global --unset http.proxy
git config --global --unset https.proxy

Add querystring parameters to link_to

If you want to keep existing params and not expose yourself to XSS attacks, be sure to clean the params hash, leaving only the params that your app can be sending:

# inline
<%= link_to 'Link', params.slice(:sort).merge(per_page: 20) %>

 

If you use it in multiple places, clean the params in the controller:

# your_controller.rb
@params = params.slice(:sort, :per_page)

# view
<%= link_to 'Link', @params.merge(per_page: 20) %>

Replace whole line containing a string using Sed

In my makefile I use this:

@sed -i '/.*Revision:.*/c\'"`svn info -R main.cpp | awk '/^Rev/'`"'' README.md

PS: DO NOT forget that the -i changes actually the text in the file... so if the pattern you defined as "Revision" will change, you will also change the pattern to replace.

Example output:

Abc-Project written by John Doe

Revision: 1190

So if you set the pattern "Revision: 1190" it's obviously not the same as you defined them as "Revision:" only...

Use and meaning of "in" in an if statement?

This may be a very late answer. in operator checks for memberships. That is, it checks if its left operand is a member of its right operand. In this case, raw_input() returns an str object of what is supplied by the user at the standard input. So, the if condition checks whether the input contains substrings "0" or "1". Considering the typecasting (int()) in the following line, the if condition essentially checks if the input contains digits 0 or 1.

maven command line how to point to a specific settings.xml for a single command?

You can simply use:

mvn --settings YourOwnSettings.xml clean install

or

mvn -s YourOwnSettings.xml clean install

Can there exist two main methods in a Java program?

Yes it is possible to have two main() in the same program. For instance, if I have a class Demo1 as below. Compiling this file will generate Demo1.class file. And once you run this it will run the main() having array of String arguments by default. It won't even sniff at the main() with int argument.

class Demo1 {   
static int a, b;    
public static void main(int args) {
     System.out.println("Using Demo1 class Main with int arg");
     a =30;
     b =40;
     System.out.println("Product is: "+a*b);
 }
public static void main(String[] args) {
      System.out.println("Using Demo1 class Main with string arg");
      a =10;
      b =20;
      System.out.println("Product is: "+a*b);

 }
 }      

Output:
Using Demo1 class Main with string arg
Product is: 200

But if I add another class named Anonym and save the file as Anonym.java. Inside this I call the Demo1 class main()[either int argument or string argument one]. After compiling this Anonym.class file gets generated.

class Demo1 {   
    static int a, b;    
public static void main(int args) {
    System.out.println("Using Demo1 class Main with int arg");
    a =30;
    b =40;
    System.out.println("Product is: "+a*b);
}
public static void main(String[] args) {
    System.out.println("Using Demo1 class Main with string arg");
     a =10;
     b =20;
     System.out.println("Product is: "+a*b);        
} 
}       

class Anonym{
public static void main(String arg[])
{

    Demo1.main(1);
    Demo1.main(null);
}
}


Output:
Using Demo1 class Main with int arg
Product is: 1200
Using Demo1 class Main with string arg
Product is: 200

HTML: Changing colors of specific words in a string of text

<p style="font-size:14px; color:#538b01; font-weight:bold; font-style:italic;">
    Enter the competition by <span style="color:#FF0000">January 30, 2011</span> and you could win up to $$$$ — including amazing <span style="color:#0000A0">summer</span> trips!
</p>

The span elements are inline an thus don't break the flow of the paragraph, only style in between the tags.

Cloning git repo causes error - Host key verification failed. fatal: The remote end hung up unexpectedly

The issue could be that Github isn't present in your ~/.ssh/known_hosts file.

Append GitHub to the list of authorized hosts:

ssh-keyscan -H github.com >> ~/.ssh/known_hosts

Android: How to rotate a bitmap on a center point

You can use something like following:


Matrix matrix = new Matrix();
matrix.setRotate(mRotation,source.getWidth()/2,source.getHeight()/2);
RectF rectF = new RectF(0, 0, source.getWidth(), source.getHeight());
matrix.mapRect(rectF);
Bitmap targetBitmap = Bitmap.createBitmap(rectF.width(), rectF.height(), config);
Canvas canvas = new Canvas(targetBitmap);
canvas.drawBitmap(source, matrix, new Paint());

How do I find the index of a character within a string in C?

This should do it:

//Returns the index of the first occurence of char c in char* string. If not found -1 is returned.
int get_index(char* string, char c) {
    char *e = strchr(string, c);
    if (e == NULL) {
        return -1;
    }
    return (int)(e - string);
}

How to add anything in <head> through jquery/javascript?

You can select it and add to it as normal:

$('head').append('<link />');

Android Studio with Google Play Services

In my case google-play-services_lib are integrate as module (External Libs) for Google map & GCM in my project.

Now, these time require to implement Google Places Autocomplete API but problem is that's code are new and my libs are old so some class not found:

following these steps...

1> Update Google play service into SDK Manager

2> select new .jar file of google play service (Sdk/extras/google/google_play_services/libproject/google-play-services_lib/libs) replace with old one

i got success...!!!

How to set TLS version on apache HttpClient

Using -Dhttps.protocols=TLSv1.2 JVM argument didn't work for me. What worked is the following code

RequestConfig.Builder requestBuilder = RequestConfig.custom();
//other configuration, for example
requestBuilder = requestBuilder.setConnectTimeout(1000);

SSLContext sslContext = SSLContextBuilder.create().useProtocol("TLSv1.2").build();

HttpClientBuilder builder = HttpClientBuilder.create();
builder.setDefaultRequestConfig(requestBuilder.build());
builder.setProxy(new HttpHost("your.proxy.com", 3333)); //if you have proxy
builder.setSSLContext(sslContext);

HttpClient client = builder.build();

Use the following JVM argument to verify

-Djavax.net.debug=all

C++: Print out enum value as text

This solution doesn't require you to use any data structures or make a different file.

Basically, you define all your enum values in a #define, then use them in the operator <<. Very similar to @jxh's answer.

ideone link for final iteration: http://ideone.com/hQTKQp

Full code:

#include <iostream>

#define ERROR_VALUES ERROR_VALUE(NO_ERROR)\
ERROR_VALUE(FILE_NOT_FOUND)\
ERROR_VALUE(LABEL_UNINITIALISED)

enum class Error
{
#define ERROR_VALUE(NAME) NAME,
    ERROR_VALUES
#undef ERROR_VALUE
};

inline std::ostream& operator<<(std::ostream& os, Error err)
{
    int errVal = static_cast<int>(err);
    switch (err)
    {
#define ERROR_VALUE(NAME) case Error::NAME: return os << "[" << errVal << "]" #NAME;
    ERROR_VALUES
#undef ERROR_VALUE
    default:
        // If the error value isn't found (shouldn't happen)
        return os << errVal;
    }
}

int main() {
    std::cout << "Error: " << Error::NO_ERROR << std::endl;
    std::cout << "Error: " << Error::FILE_NOT_FOUND << std::endl;
    std::cout << "Error: " << Error::LABEL_UNINITIALISED << std::endl;
    return 0;
}

Output:

Error: [0]NO_ERROR
Error: [1]FILE_NOT_FOUND
Error: [2]LABEL_UNINITIALISED

A nice thing about doing it this way is that you can also specify your own custom messages for each error if you think you need them:

#include <iostream>

#define ERROR_VALUES ERROR_VALUE(NO_ERROR, "Everything is fine")\
ERROR_VALUE(FILE_NOT_FOUND, "File is not found")\
ERROR_VALUE(LABEL_UNINITIALISED, "A component tried to the label before it was initialised")

enum class Error
{
#define ERROR_VALUE(NAME,DESCR) NAME,
    ERROR_VALUES
#undef ERROR_VALUE
};

inline std::ostream& operator<<(std::ostream& os, Error err)
{
    int errVal = static_cast<int>(err);
    switch (err)
    {
#define ERROR_VALUE(NAME,DESCR) case Error::NAME: return os << "[" << errVal << "]" #NAME <<"; " << DESCR;
    ERROR_VALUES
#undef ERROR_VALUE
    default:
        return os << errVal;
    }
}

int main() {
    std::cout << "Error: " << Error::NO_ERROR << std::endl;
    std::cout << "Error: " << Error::FILE_NOT_FOUND << std::endl;
    std::cout << "Error: " << Error::LABEL_UNINITIALISED << std::endl;
    return 0;
}

Output:

Error: [0]NO_ERROR; Everything is fine
Error: [1]FILE_NOT_FOUND; File is not found
Error: [2]LABEL_UNINITIALISED; A component tried to the label before it was initialised

If you like making your error codes/descriptions very descriptive, you might not want them in production builds. Turning them off so only the value is printed is easy:

inline std::ostream& operator<<(std::ostream& os, Error err)
{
    int errVal = static_cast<int>(err);
    switch (err)
    {
    #ifndef PRODUCTION_BUILD // Don't print out names in production builds
    #define ERROR_VALUE(NAME,DESCR) case Error::NAME: return os << "[" << errVal << "]" #NAME <<"; " << DESCR;
        ERROR_VALUES
    #undef ERROR_VALUE
    #endif
    default:
        return os << errVal;
    }
}

Output:

Error: 0
Error: 1
Error: 2

If this is the case, finding error number 525 would be a PITA. We can manually specify the numbers in the initial enum like this:

#define ERROR_VALUES ERROR_VALUE(NO_ERROR, 0, "Everything is fine")\
ERROR_VALUE(FILE_NOT_FOUND, 1, "File is not found")\
ERROR_VALUE(LABEL_UNINITIALISED, 2, "A component tried to the label before it was initialised")\
ERROR_VALUE(UKNOWN_ERROR, -1, "Uh oh")

enum class Error
{
#define ERROR_VALUE(NAME,VALUE,DESCR) NAME=VALUE,
    ERROR_VALUES
#undef ERROR_VALUE
};

inline std::ostream& operator<<(std::ostream& os, Error err)
{
    int errVal = static_cast<int>(err);
    switch (err)
    {
#ifndef PRODUCTION_BUILD // Don't print out names in production builds
#define ERROR_VALUE(NAME,VALUE,DESCR) case Error::NAME: return os << "[" #VALUE  "]" #NAME <<"; " << DESCR;
    ERROR_VALUES
#undef ERROR_VALUE
#endif
    default:
        return os <<errVal;
    }
}
    ERROR_VALUES
#undef ERROR_VALUE
#endif
    default:
    {
        // If the error value isn't found (shouldn't happen)
        return os << static_cast<int>(err);
        break;
    }
    }
}

Output:

Error: [0]NO_ERROR; Everything is fine
Error: [1]FILE_NOT_FOUND; File is not found
Error: [2]LABEL_UNINITIALISED; A component tried to the label before it was initialised
Error: [-1]UKNOWN_ERROR; Uh oh

What is the difference between float and double?

When using floating point numbers you cannot trust that your local tests will be exactly the same as the tests that are done on the server side. The environment and the compiler are probably different on you local system and where the final tests are run. I have seen this problem many times before in some TopCoder competitions especially if you try to compare two floating point numbers.

WCF named pipe minimal example

I created this simple example from different search results on the internet.

public static ServiceHost CreateServiceHost(Type serviceInterface, Type implementation)
{
  //Create base address
  string baseAddress = "net.pipe://localhost/MyService";

  ServiceHost serviceHost = new ServiceHost(implementation, new Uri(baseAddress));

  //Net named pipe
  NetNamedPipeBinding binding = new NetNamedPipeBinding { MaxReceivedMessageSize = 2147483647 };
  serviceHost.AddServiceEndpoint(serviceInterface, binding, baseAddress);

  //MEX - Meta data exchange
  ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
  serviceHost.Description.Behaviors.Add(behavior);
  serviceHost.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexNamedPipeBinding(), baseAddress + "/mex/");

  return serviceHost;
}

Using the above URI I can add a reference in my client to the web service.

How to set UICollectionViewCell Width and Height programmatically

Try below method

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    return CGSize(width: 100.0, height: 100.0)
}

Capitalize first letter. MySQL

This should work nicely:

UPDATE tb_Company SET CompanyIndustry = 
CONCAT(UPPER(LEFT(CompanyIndustry, 1)), SUBSTRING(CompanyIndustry, 2))

Implementing autocomplete

I'd like to add something that no one has yet mentioned: ng2-input-autocomplete

NPM: https://www.npmjs.com/package/ng2-input-autocomplete

GitHub: https://github.com/liuy97/ng2-input-autocomplete#readme

Could not find a base address that matches scheme https for the endpoint with binding WebHttpBinding. Registered base address schemes are [http]

To make it work you have to replace a run this line of code serviceMetadata httpGetEnabled="true"/> http instead of https and security mode="None" />

C# Checking if button was clicked

button1, button2 and button3 have same even handler

private void button1_Click(Object sender, EventArgs e)
    {
        Button btnSender = (Button)sender;
        if (btnSender == button1 || btnSender == button2)
        {
            //some code here
        }
        else if (btnSender == button3)
            //some code here
    }

How to get subarray from array?

For a simple use of slice, use my extension to Array Class:

Array.prototype.subarray = function(start, end) {
    if (!end) { end = -1; } 
    return this.slice(start, this.length + 1 - (end * -1));
};

Then:

var bigArr = ["a", "b", "c", "fd", "ze"];

Test1:

bigArr.subarray(1, -1);

< ["b", "c", "fd", "ze"]

Test2:

bigArr.subarray(2, -2);

< ["c", "fd"]

Test3:

bigArr.subarray(2);

< ["c", "fd","ze"]

Might be easier for developers coming from another language (i.e. Groovy).

What's the difference between Visual Studio Community and other, paid versions?

All these answers are partially wrong.

Microsoft has clarified that Community is for ANY USE as long as your revenue is under $1 Million US dollars. That is literally the only difference between Pro and Community. Corporate or free or not, irrelevant.

Even the lack of TFS support is not true. I can verify it is present and works perfectly.

EDIT: Here is an MSDN post regarding the $1M limit: MSDN (hint: it's in the VS 2017 license)

EDIT: Even over the revenue limit, open source is still free.

How to change a TextView's style at runtime

I did this by creating a new XML file res/values/style.xml as follows:

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <style name="boldText">
        <item name="android:textStyle">bold|italic</item>
        <item name="android:textColor">#FFFFFF</item>
    </style>

    <style name="normalText">
        <item name="android:textStyle">normal</item>
        <item name="android:textColor">#C0C0C0</item>
    </style>

</resources>

I also have an entries in my "strings.xml" file like this:

<color name="highlightedTextViewColor">#000088</color>
<color name="normalTextViewColor">#000044</color>

Then, in my code I created a ClickListener to trap the tap event on that TextView: EDIT: As from API 23 'setTextAppearance' is deprecated

    myTextView.setOnClickListener(new View.OnClickListener() {
                public void onClick(View view){
                    //highlight the TextView
                    //myTextView.setTextAppearance(getApplicationContext(), R.style.boldText);
    if (Build.VERSION.SDK_INT < 23) {
       myTextView.setTextAppearance(getApplicationContext(), R.style.boldText);
    } else {
       myTextView.setTextAppearance(R.style.boldText);
    }
     myTextView.setBackgroundResource(R.color.highlightedTextViewColor);
                }
            });

To change it back, you would use this:

if (Build.VERSION.SDK_INT < 23) {
    myTextView.setTextAppearance(getApplicationContext(), R.style.normalText);
} else{
   myTextView.setTextAppearance(R.style.normalText);
}
myTextView.setBackgroundResource(R.color.normalTextViewColor);

Fit cell width to content

For me, this is the best autofit and autoresize for table and its columns (use css !important ... only if you can't without)

.myclass table {
    table-layout: auto !important;
}

.myclass th, .myclass td, .myclass thead th, .myclass tbody td, .myclass tfoot td, .myclass tfoot th {
    width: auto !important;
}

Don't specify css width for table or for table columns. If table content is larger it will go over screen size to.

Home does not contain an export named Home

I just ran into this error message (after upgrading to nextjs 9 some transpiled imports started giving this error). I managed to fix them using syntax like this:

import * as Home from './layouts/Home';

How to delete files older than X hours

Here is the approach that worked for me (and I don't see it being used above)

$ find /path/to/the/folder -name *.* -mmin +59 -delete > /dev/null

deleting all the files older than 59 minutes while leaving the folders intact.

How to access Session variables and set them in javascript?

I was able to solve a similar problem with simple URL parameters and auto refresh.

You can get the values from the URL parameters, do whatever you want with them and simply refresh the page.

HTML:

<a href=\"webpage.aspx?parameterName=parameterValue"> LinkText </a>

C#:

string variable = Request.QueryString["parameterName"];
if (parameterName!= null)
{
   Session["sessionVariable"] += parameterName;
   Response.AddHeader("REFRESH", "1;URL=webpage.aspx");
}

ASP.Net MVC - Read File from HttpPostedFileBase without save

byte[] data; using(Stream inputStream=file.InputStream) { MemoryStream memoryStream = inputStream as MemoryStream; if (memoryStream == null) { memoryStream = new MemoryStream(); inputStream.CopyTo(memoryStream); } data = memoryStream.ToArray(); }

How do I count unique visitors to my site?

I have edited the "Best answer" code, though I found a useful thing that was missing. This is will also track the ip of a user if they are using a Proxy or simply if the server has nginx installed as a proxy reverser.

I added this code to his script at the top of the function:

function getRealIpAddr()
{
    if (!empty($_SERVER['HTTP_CLIENT_IP']))   //check ip from share internet
    {
      $ip=$_SERVER['HTTP_CLIENT_IP'];
    }
    elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))   //to check ip is pass from proxy
    {
      $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    else
    {
      $ip=$_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}
$adresseip = getRealIpAddr();

Afther that I edited his code.

Find the line that says the following:

// get the user name if it is logged, or the visitors IP (and add the identifier)

    $uvon = isset($_SESSION['nume']) ? $_SESSION['nume'] : $_SERVER['SERVER_ADDR']. $vst_id;

and replace it with this:

$uvon = isset($_SESSION['nume']) ? $_SESSION['nume'] : $adresseip. $vst_id;

This will work.

Here is the full code if anything happens:

<?php

function getRealIpAddr()
{
    if (!empty($_SERVER['HTTP_CLIENT_IP']))   //check ip from share internet
    {
      $ip=$_SERVER['HTTP_CLIENT_IP'];
    }
    elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))   //to check ip is pass from proxy
    {
      $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    else
    {
      $ip=$_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}
$adresseip = getRealIpAddr();

// Script Online Users and Visitors - http://coursesweb.net/php-mysql/
if(!isset($_SESSION)) session_start();        // start Session, if not already started

$filetxt = 'userson.txt';  // the file in which the online users /visitors are stored
$timeon = 120;             // number of secconds to keep a user online
$sep = '^^';               // characters used to separate the user name and date-time
$vst_id = '-vst-';        // an identifier to know that it is a visitor, not logged user

/*
 If you have an user registration script,
 replace $_SESSION['nume'] with the variable in which the user name is stored.
 You can get a free registration script from:  http://coursesweb.net/php-mysql/register-login-script-users-online_s2
*/

// get the user name if it is logged, or the visitors IP (and add the identifier)

    $uvon = isset($_SESSION['nume']) ? $_SESSION['nume'] : $_SERVER['SERVER_ADDR']. $vst_id;

$rgxvst = '/^([0-9\.]*)'. $vst_id. '/i';         // regexp to recognize the line with visitors
$nrvst = 0;                                       // to store the number of visitors

// sets the row with the current user /visitor that must be added in $filetxt (and current timestamp)

    $addrow[] = $uvon. $sep. time();

// check if the file from $filetxt exists and is writable

    if(is_writable($filetxt)) {
      // get into an array the lines added in $filetxt
      $ar_rows = file($filetxt, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
      $nrrows = count($ar_rows);

            // number of rows

  // if there is at least one line, parse the $ar_rows array

      if($nrrows>0) {
        for($i=0; $i<$nrrows; $i++) {
          // get each line and separate the user /visitor and the timestamp
          $ar_line = explode($sep, $ar_rows[$i]);
      // add in $addrow array the records in last $timeon seconds
          if($ar_line[0]!=$uvon && (intval($ar_line[1])+$timeon)>=time()) {
            $addrow[] = $ar_rows[$i];
          }
        }
      }
    }

$nruvon = count($addrow);                   // total online
$usron = '';                                    // to store the name of logged users
// traverse $addrow to get the number of visitors and users
for($i=0; $i<$nruvon; $i++) {
 if(preg_match($rgxvst, $addrow[$i])) $nrvst++;       // increment the visitors
 else {
   // gets and stores the user's name
   $ar_usron = explode($sep, $addrow[$i]);
   $usron .= '<br/> - <i>'. $ar_usron[0]. '</i>';
 }
}
$nrusr = $nruvon - $nrvst;              // gets the users (total - visitors)

// the HTML code with data to be displayed
$reout = '<div id="uvon"><h4>Online: '. $nruvon. '</h4>Visitors: '. $nrvst. '<br/>Users: '. $nrusr. $usron. '</div>';

// write data in $filetxt
if(!file_put_contents($filetxt, implode("\n", $addrow))) $reout = 'Error: Recording file not exists, or is not writable';

// if access from <script>, with GET 'uvon=showon', adds the string to return into a JS statement
// in this way the script can also be included in .html files
if(isset($_GET['uvon']) && $_GET['uvon']=='showon') $reout = "document.write('$reout');";

echo $reout;             // output /display the result

Haven't tested this on the Sql script yet.

Click event doesn't work on dynamically generated elements

Add this function in your js file. It will work on every browser

_x000D_
_x000D_
$(function() {_x000D_
    $(document).on("click", '#mydiv', function() {_x000D_
        alert("You have just clicked on ");_x000D_
    });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id='mydiv'>Div</div>
_x000D_
_x000D_
_x000D_

ClientAbortException: java.net.SocketException: Connection reset by peer: socket write error

Your log indicates ClientAbortException, which occurs when your HTTP client drops the connection with the server and this happened before server could close the server socket Connection.

Android: Storing username and password?

With the new (Android 6.0) fingerprint hardware and API you can do it as in this github sample application.

How do I overload the [] operator in C#

The [] operator is called an indexer. You can provide indexers that take an integer, a string, or any other type you want to use as a key. The syntax is straightforward, following the same principles as property accessors.

For example, in your case where an int is the key or index:

public int this[int index]
{
    get => GetValue(index);
}

You can also add a set accessor so that the indexer becomes read and write rather than just read-only.

public int this[int index]
{
    get => GetValue(index);
    set => SetValue(index, value);
}

If you want to index using a different type, you just change the signature of the indexer.

public int this[string index]
...

'cannot find or open the pdb file' Visual Studio C++ 2013

A bit late but I thought I'd share in case it helps anyone: what is most likely the problem is simply that your Debug Console (the command line window that opens when run your project if it is a Windows Console Application) is still open from the last time you ran the code. Just close that window, then rebuild and run: Ctrl + B and F5, respectively.

Not an enclosing class error Android Studio

you are calling the context of not existing activity...so just replace your code in onClick(View v) as Intent intent=new Intent(this,Katra_home.class); startActivity(intent); it will definitely works....

best way to preserve numpy arrays on disk

I've compared performance (space and time) for a number of ways to store numpy arrays. Few of them support multiple arrays per file, but perhaps it's useful anyway.

benchmark for numpy array storage

Npy and binary files are both really fast and small for dense data. If the data is sparse or very structured, you might want to use npz with compression, which'll save a lot of space but cost some load time.

If portability is an issue, binary is better than npy. If human readability is important, then you'll have to sacrifice a lot of performance, but it can be achieved fairly well using csv (which is also very portable of course).

More details and the code are available at the github repo.

How to get rid of "Unnamed: 0" column in a pandas DataFrame?

Simple do this:

df = df.loc[:, ~df.columns.str.contains('^Unnamed')]

Return Max Value of range that is determined by an Index & Match lookup

You can easily change the match-type to 1 when you are looking for the greatest value or to -1 when looking for the smallest value.

Is there a workaround for ORA-01795: maximum number of expressions in a list is 1000 error?

There's also workaround doing disjunction of your array, worked for me as other solutions were hard to implement using some old framework.

select * from tableA where id = 1 or id = 2 or id = 3 ...

But for better perfo, I would use Nikolai Nechai's solution with unions, if possible.

HTML5 live streaming

You can use a fantastic library name Videojs. You will find more useful informations here. But with quick start you can do something like this:

<link href="//vjs.zencdn.net/5.11/video-js.min.css" rel="stylesheet">
<script src="//vjs.zencdn.net/5.11/video.min.js"></script>
<video 
id="Video" 
class="video-js vjs-default-skin vjs-big-play-centered" 
controls 
preload="none" 
width="auto" 
height="auto" 
poster="poster.jpg" 
data-setup='{"techOrder": ["flash", "html5", "other supported tech"], "nativeControlsForTouch": true, "controlBar": { "muteToggle": false, "volumeControl": false, "timeDivider": false, "durationDisplay": false, "progressControl": false } }'
>
<source src="rtmp://{domain_server}/{publisher}" type='rtmp/mp4'/>
</video>
<script>
var player = videojs('Video');
player.play();
</script>

Remove all occurrences of a value from a list?

I just did this for a list. I am just a beginner. A slightly more advanced programmer can surely write a function like this.

for i in range(len(spam)):
    spam.remove('cat')
    if 'cat' not in spam:
         print('All instances of ' + 'cat ' + 'have been removed')
         break

PHP absolute path to root

This is my way to find the rootstart. Create at ROOT start a file with name mainpath.php

<?php 
## DEFINE ROOTPATH
$check_data_exist = ""; 

$i_surf = 0;

// looking for mainpath.php at the aktiv folder or higher folder

while (!file_exists($check_data_exist."mainpath.php")) {
  $check_data_exist .= "../"; 
  $i_surf++;
  // max 7 folder deep
  if ($i_surf == 7) { 
   return false;
  }
}

define("MAINPATH", ($check_data_exist ? $check_data_exist : "")); 
?>

For me is that the best and easiest way to find them. ^^

Randomize numbers with jQuery?

Javascript has a random() available. Take a look at Math.random().

Git push rejected after feature branch rebase

I would do as below

rebase feature
git checkout -b feature2 origin/feature
git push -u origin feature2:feature2
Delete the old remote branch feature
git push -u origin feature:feature

Now the remote will have feature(rebased on latest master) and feature2(with old master head). This would allow you to compare later if you have done mistakes in reolving conflicts.

Node.js: Python not found exception due to node-sass and node-gyp

My answer might not apply to everyone. Node version: v10.16.0 NPM: 6.9.0

I was having a lot of trouble using node-sass and node-sass-middleware. They are interesting packages because they are widely used (millions of downloads weekly), but their githubs show a limited dependencies and coverage. I was updating an older platform I'd been working on.

What I ended up having to do was:

1) Manually Delete node_modules

2) Manually Delete package-lock.json

3) sudo npm install node-sass --unsafe-perm=true --allow-root

4) sudo npm install node-sass-middleware --unsafe-perm=true --allow-root

I had the following help, thanks!

Pre-built binaries not found for [email protected] and [email protected]

Error: EACCES: permission denied when trying to install ESLint using npm

How to make a shape with left-top round rounded corner and left-bottom rounded corner?

for others there are a solution for any API level , you can place a item on top of each other example :

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

<!-- my firt item with 4 corners radius(8dp)
 -->
    <item>
        <shape>
            <solid
                android:angle="270.0"
                android:color="#3D689A" />

            <corners android:topLeftRadius="8dp" />
        </shape>
    </item>
<!-- my second item is on top right for a fake corner radius(0dp)
 -->
    <item
        android:bottom="30dp"
        android:left="50dp">
        <shape>
            <solid android:color="#5C83AF" />
        </shape>
    </item>
<!-- my third item is on bottom left for a fake corner radius(0dp)
 -->
    <item
        android:right="50dp"
        android:top="30dp">
        <shape>
            <solid android:color="#5C83AF" />
        </shape>
    </item>

</layer-list>

the result with light color to show you the three items :

enter image description here

the final result :

enter image description here

Best regards.

Preview an image before it is uploaded

In React, if the file is in your props, you can use:

{props.value instanceof File && (
    <img src={URL.createObjectURL(props.value)}/>
)}

MySql Query Replace NULL with Empty String in Select

Try this, this should also get rid of those empty lines also:

SELECT prereq FROM test WHERE prereq IS NOT NULL;

How to convert a timezone aware string to datetime in Python without dateutil?

You can convert like this.

date = datetime.datetime.strptime('2019-3-16T5-49-52-595Z','%Y-%m-%dT%H-%M-%S-%f%z')
date_time = date.strftime('%Y-%m-%dT%H:%M:%S.%fZ')

How to add key,value pair to dictionary?

To insert/append to a dictionary

{"0": {"travelkey":"value", "travelkey2":"value"},"1":{"travelkey":"value","travelkey2":"value"}} 

travel_dict={} #initialize dicitionary 
travel_key=0 #initialize counter

if travel_key not in travel_dict: #for avoiding keyerror 0
    travel_dict[travel_key] = {}
travel_temp={val['key']:'no flexible'}  
travel_dict[travel_key].update(travel_temp) # Updates if val['key'] exists, else adds val['key']
travel_key=travel_key+1

Select last N rows from MySQL

SELECT * FROM table ORDER BY id DESC LIMIT 50

save resources make one query, there is no need to make nested queries

How to pass parameters to a modal?

If you're not using AngularJS UI Bootstrap, here's how I did it.

I created a directive that will hold that entire element of your modal, and recompile the element to inject your scope into it.

angular.module('yourApp', []).
directive('myModal',
       ['$rootScope','$log','$compile',
function($rootScope,  $log,  $compile) {
    var _scope = null;
    var _element = null;
    var _onModalShow = function(event) {
        _element.after($compile(event.target)(_scope));
    };

    return {
        link: function(scope, element, attributes) {
            _scope = scope;
            _element = element;
            $(element).on('show.bs.modal',_onModalShow);
        }
    };
}]);

I'm assuming your modal template is inside the scope of your controller, then add directive my-modal to your template. If you saved the clicked user to $scope.aModel, the original template will now work.

Note: The entire scope is now visible to your modal so you can also access $scope.users in it.

<div my-modal id="encouragementModal" class="modal hide fade">
  <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal"
      aria-hidden="true">&times;</button>
    <h3>Confirm encouragement?</h3>
  </div>
  <div class="modal-body">
      Do you really want to encourage <b>{{aModel.userName}}</b>?
  </div>
  <div class="modal-footer">
    <button class="btn btn-info"
      ng-click="encourage('${createLink(uri: '/encourage/')}',{{aModel.userName}})">
      Confirm
    </button>
    <button class="btn" data-dismiss="modal" aria-hidden="true">Never Mind</button>
  </div>
</div>

php mysqli_connect: authentication method unknown to the client [caching_sha2_password]

I tried this in Ubuntu 18.04 and is the only solution that worked for me:

ALTER USER my_user@'%' IDENTIFIED WITH mysql_native_password BY 'password';

href around input type submit

I agree with Quentin. It doesn't make sense as to why you want to do it like that. It's part of the Semantic Web concept. You have to plan out the objects of your web site for future integration/expansion. Another web app or web site cannot interact with your content if it doesn't follow the proper use-case.

IE and Firefox are two different beasts. There are a lot of things that IE allows that Firefox and other standards-aware browsers reject.

If you're trying to create buttons without actually submitting data then use a combination of DIV/CSS.

CSS: center element within a <div> element

If the child element is inline (e.g not a div, table etc) I would wrap it up inside a div or a p and make the wrapper's text align css property equal to center.

    <div id="container">
        This text is aligned to the left.<br>
        So is this text.<br>
        <div style="text-align: center">
            This <button>button</button> is centered.
        </div>
        This text is still aligned left.
    </div>

Otherwise, if the element is a block (display: block, e.g a div or a p) with a fixed width, I'd set its margin left and right css properties to auto.

    <div id="container">
        This text is aligned to the left.<br>
        So is this text.<br>
        <div style="margin: 0 auto; width: 200px; background: red; color: white;">
            My parent is centered.
        </div>
        This text is still aligned left.
    </div>

You could of course add a text-align: center to the wrapper element to make its contents centered as well.

I won't bother with positioning because IMHO its not the way to go for the OPs problem but be sure to check this link out, very helpful.

ReactJS map through Object

Do you get an error when you try to map through the object keys, or does it throw something else.

Also note when you want to map through the keys you make sure to refer to the object keys correctly. Just like this:

{ Object.keys(subjects).map((item, i) => (
   <li className="travelcompany-input" key={i}>
     <span className="input-label">key: {i} Name: {subjects[item]}</span>
    </li>
))}

You need to use {subjects[item]} instead of {subjects[i]} because it refers to the keys of the object. If you look for subjects[i] you will get undefined.

Java NIO: What does IOException: Broken pipe mean?

Broken pipe means you wrote to a connection that is already closed by the other end.

isConnected() does not detect this condition. Only a write does.

is it wise to always call SocketChannel.isConnected() before attempting a SocketChannel.write()

It is pointless. The socket itself is connected. You connected it. What may not be connected is the connection itself, and you can only determine that by trying it.

Concatenating elements in an array to a string

Using Guava's Joiner (which in r18 internally uses StringBuilder)

String[]  arr= {"1","2","3"};
Joiner noSpaceJoiner = Joiner.on("");
noSpaceJoiner.join(arr))

Joiner is useful because it is thread-safe and immutable and can be reused in many places without having to duplicate code. In my opinion it also is more readable.


Using Java 8's Stream support, we can also reduce this down to a one-liner.

String concat = Stream.of(arr).collect(Collectors.joining());

Both outputs in this case are 123

How to recover the deleted files using "rm -R" command in linux server?

since answers are disappointing I would like suggest a way in which I got deleted stuff back.

I use an ide to code and accidently I used rm -rf from terminal to remove complete folder. Thanks to ide I recoved it back by reverting the change from ide's local history.

(my ide is intelliJ but all ide's support history backup)

Difference between objectForKey and valueForKey?

Here's a great reason to use objectForKey: wherever possible instead of valueForKey: - valueForKey: with an unknown key will throw NSUnknownKeyException saying "this class is not key value coding-compliant for the key ".

Python: How to get stdout after running os.system?

I had to use os.system, since subprocess was giving me a memory error for larger tasks. Reference for this problem here. So, in order to get the output of the os.system command I used this workaround:

import os

batcmd = 'dir'
result_code = os.system(batcmd + ' > output.txt')
if os.path.exists('output.txt'):
    fp = open('output.txt', "r")
    output = fp.read()
    fp.close()
    os.remove('output.txt')
    print(output)

OSError [Errno 22] invalid argument when use open() in Python

Just replace with "/" for file path :

   open("description_files/program_description.txt","r")

What is output buffering?

UPDATE 2019. If you have dedicated server and SSD or better NVM, 3.5GHZ. You shouldn't use buffering to make faster loaded website in 100ms-150ms.

Becouse network is slowly than proccesing script in the 2019 with performance servers (severs,memory,disk) and with turn on APC PHP :) To generated script sometimes need only 70ms another time is only network takes time, from 10ms up to 150ms from located user-server.

so if you want be fast 150ms, buffering make slowl, becouse need extra collection buffer data it make extra cost. 10 years ago when server make 1s script, it was usefull.

Please becareful output_buffering have limit if you would like using jpg to loading it can flush automate and crash sending.

Cheers.

You can make fast river or You can make safely tama :)

Automated way to convert XML files to SQL database?

There is a project on CodeProject that makes it simple to convert an XML file to SQL Script. It uses XSLT. You could probably modify it to generate the DDL too.

And See this question too : Generating SQL using XML and XSLT

How to URL encode a string in Ruby

Nowadays, you should use ERB::Util.url_encode or CGI.escape. The primary difference between them is their handling of spaces:

>> ERB::Util.url_encode("foo/bar? baz&")
=> "foo%2Fbar%3F%20baz%26"

>> CGI.escape("foo/bar? baz&")
=> "foo%2Fbar%3F+baz%26"

CGI.escape follows the CGI/HTML forms spec and gives you an application/x-www-form-urlencoded string, which requires spaces be escaped to +, whereas ERB::Util.url_encode follows RFC 3986, which requires them to be encoded as %20.

See "What's the difference between URI.escape and CGI.escape?" for more discussion.

MySQL show current connection info

If you want to know the port number of your local host on which Mysql is running you can use this query on MySQL Command line client --

SHOW VARIABLES WHERE Variable_name = 'port';


mysql> SHOW VARIABLES WHERE Variable_name = 'port';
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| port          | 3306  |
+---------------+-------+
1 row in set (0.00 sec)

It will give you the port number on which MySQL is running.


If you want to know the hostname of your Mysql you can use this query on MySQL Command line client --

SHOW VARIABLES WHERE Variable_name = 'hostname';


mysql> SHOW VARIABLES WHERE Variable_name = 'hostname';
+-------------------+-------+
| Variable_name     | Value |
+-------------------+-------+
| hostname          | Dell  |
+-------------------+-------+
1 row in set (0.00 sec)

It will give you the hostname for mysql.


If you want to know the username of your Mysql you can use this query on MySQL Command line client --

select user();   


mysql> select user();
+----------------+
| user()         |
+----------------+
| root@localhost |
+----------------+
1 row in set (0.00 sec)

It will give you the username for mysql.

How to set password for Redis?

open redis configuration file

sudo nano /etc/redis/redis.conf 

set passphrase

replace

# requirepass foobared

with

requirepass YOURPASSPHRASE

restart redis

redis-server restart

Masking password input from the console : Java

The given code given will work absolutely fine if we run from console. and there is no package name in the class

You have to make sure where you have your ".class" file. because, if package name is given for the class, you have to make sure to keep the ".class" file inside the specified folder. For example, my package name is "src.main.code" , I have to create a code folder,inside main folder, inside src folder and put Test.class in code folder. then it will work perfectly.

How can one display images side by side in a GitHub README.md?

This is the best way to make add images/screenshots of your app and keep your repository look clean.

Create a screenshot folder in your repository and add the images you want to display.

Now go to README.md and add this HTML code to form a table.

#### Flutter App Screenshots

<table>
  <tr>
    <td>First Screen Page</td>
     <td>Holiday Mention</td>
     <td>Present day in purple and selected day in pink</td>
  </tr>
  <tr>
    <td><img src="screenshots/Screenshot_1582745092.png" width=270 height=480></td>
    <td><img src="screenshots/Screenshot_1582745125.png" width=270 height=480></td>
    <td><img src="screenshots/Screenshot_1582745139.png" width=270 height=480></td>
  </tr>
 </table>

In the <td><img src="(COPY IMAGE PATH HERE)" width=270 height=480></td>

** To get the image path --> Go to the screenshot folder and open the image and on the right most side, you will find Copy path button.

You will get a table like this in your repository--->

enter image description here

How can I pass a class member function as a callback?

I can see that the init has the following override:

Init(CALLBACK_FUNC_EX callback_func, void * callback_parm)

where CALLBACK_FUNC_EX is

typedef void (*CALLBACK_FUNC_EX)(int, void *);

Using PropertyInfo.GetValue()

In your example propertyInfo.GetValue(this, null) should work. Consider altering GetNamesAndTypesAndValues() as follows:

public void GetNamesAndTypesAndValues()
{
  foreach (PropertyInfo propertyInfo in allClassProperties)
  {
    Console.WriteLine("{0} [type = {1}] [value = {2}]",
      propertyInfo.Name,
      propertyInfo.PropertyType,
      propertyInfo.GetValue(this, null));
  }
}

Dropdown using javascript onchange

Something like this should do the trick

<select id="leave" onchange="leaveChange()">
  <option value="5">Get Married</option>
  <option value="100">Have a Baby</option>
  <option value="90">Adopt a Child</option>
  <option value="15">Retire</option>
  <option value="15">Military Leave</option>
  <option value="15">Medical Leave</option>
</select>

<div id="message"></div>

Javascript

function leaveChange() {
    if (document.getElementById("leave").value != "100"){
        document.getElementById("message").innerHTML = "Common message";
    }     
    else{
        document.getElementById("message").innerHTML = "Having a Baby!!";
    }        
}

jsFiddle Demo

A shorter version and more general could be

HTML

<select id="leave" onchange="leaveChange(this)">
  <option value="5">Get Married</option>
  <option value="100">Have a Baby</option>
  <option value="90">Adopt a Child</option>
  <option value="15">Retire</option>
  <option value="15">Military Leave</option>
  <option value="15">Medical Leave</option>
</select>

Javascript

function leaveChange(control) {
    var msg = control.value == "100" ? "Having a Baby!!" : "Common message";
    document.getElementById("message").innerHTML = msg;
}

passing several arguments to FUN of lapply (and others *apply)

If you look up the help page, one of the arguments to lapply is the mysterious .... When we look at the Arguments section of the help page, we find the following line:

...: optional arguments to ‘FUN’.

So all you have to do is include your other argument in the lapply call as an argument, like so:

lapply(input, myfun, arg1=6)

and lapply, recognizing that arg1 is not an argument it knows what to do with, will automatically pass it on to myfun. All the other apply functions can do the same thing.

An addendum: You can use ... when you're writing your own functions, too. For example, say you write a function that calls plot at some point, and you want to be able to change the plot parameters from your function call. You could include each parameter as an argument in your function, but that's annoying. Instead you can use ... (as an argument to both your function and the call to plot within it), and have any argument that your function doesn't recognize be automatically passed on to plot.

Add leading zeroes/0's to existing Excel values to certain length

The more efficient (less obtrusive) way of doing this is through custom formatting.

  1. Highlight the column/array you want to style.
  2. Click ctrl + 1 or Format -> Format Cells.
  3. In the Number tab, choose Custom.
  4. Set the Custom formatting to 000#. (zero zero zero #)

Note that this does not actually change the value of the cell. It only displays the leading zeroes in the worksheet.

Stretch background image css?

This works flawlessly @ 2019

.marketing-panel  {
    background-image: url("../images/background.jpg");
    background-repeat: no-repeat;
    background-size: auto;
    background-position: center;
}

How does one use glide to download an image into a bitmap?

It looks like overriding the Target class or one of the implementations like BitmapImageViewTarget and overriding the setResource method to capture the bitmap might be the way to go...

This is untested. :-)

    Glide.with(context)
         .load("http://goo.gl/h8qOq7")
         .asBitmap()
         .into(new BitmapImageViewTarget(imageView) {
                     @Override
                     protected void setResource(Bitmap resource) {
                         // Do bitmap magic here
                         super.setResource(resource);
                     }
         });

How can I get table names from an MS Access Database?

Schema information which is designed to be very close to that of the SQL-92 INFORMATION_SCHEMA may be obtained for the Jet/ACE engine (which is what I assume you mean by 'access') via the OLE DB providers.

See:

OpenSchema Method (ADO)

Supported Schema Rowsets

Is there a bash command which counts files?

If you have a lot of files and you don't want to use the elegant shopt -s nullglob and bash array solution, you can use find and so on as long as you don't print out the file name (which might contain newlines).

find -maxdepth 1 -name "log*" -not -name ".*" -printf '%i\n' | wc -l

This will find all files that match log* and that don't start with .* — The "not name .*" is redunant, but it's important to note that the default for "ls" is to not show dot-files, but the default for find is to include them.

This is a correct answer, and handles any type of file name you can throw at it, because the file name is never passed around between commands.

But, the shopt nullglob answer is the best answer!

How to check if a date is greater than another in Java?

You need to use a SimpleDateFormat (dd-MM-yyyy will be the format) to parse the 2 input strings to Date objects and then use the Date#before(otherDate) (or) Date#after(otherDate) to compare them.

Try to implement the code yourself.

How can you have SharePoint Link Lists default to opening in a new window?

The same instance for SP2010; the Links List webpart will not automatically open in a new window, rather user must manually rt click Link object and select Open in New Window.

The add/ insert Link option withkin SP2010 will allow a user to manually configure the link to open in a new window.

Maybe SP2012 release will adrress this...

Undefined reference to vtable

I think it's also worth mentioning that you will also get the message when you try to link to object of any class that has at least one virtual method and linker cannot find the file. For example:

Foo.hpp:

class Foo
{
public:
    virtual void StartFooing();
};

Foo.cpp:

#include "Foo.hpp"

void Foo::StartFooing(){ //fooing }

Compiled with:

g++ Foo.cpp -c

And main.cpp:

#include "Foo.hpp"

int main()
{
    Foo foo;
}

Compiled and linked with:

g++ main.cpp -o main

Gives our favourite error:

/tmp/cclKnW0g.o: In function main': main.cpp:(.text+0x1a): undefined reference tovtable for Foo' collect2: error: ld returned 1 exit status

This occure from my undestanding becasue:

  1. Vtable is created per class at compile time

  2. Linker does not have access to vtable that is in Foo.o

ORA-28040: No matching authentication protocol exception

Except for adding the following to sqlnet.ora

SQLNET.ALLOWED_LOGON_VERSION_CLIENT = 8
SQLNET.ALLOWED_LOGON_VERSION_SERVER = 8

I also added the following to both the Client and Server, which resolved my issue

SQLNET.AUTHENTICATION_SERVICES = (NONE)

Also see post ORA-28040: No matching authentication protocol

How can I pretty-print JSON in a shell script?

A one-line solution using Node.js will look like this:

$ node -e "console.log( JSON.stringify( JSON.parse(require('fs').readFileSync(0) ), 0, 1 ))"

For example:

$ cat test.json | node -e "console.log( JSON.stringify( JSON.parse(require('fs').readFileSync(0) ), 0, 1 ))"

Android MediaPlayer Stop and Play

just in case someone comes to this question, I have the easier version.

public static MediaPlayer mp;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button b = (Button) findViewById(R.id.button);
        Button b2 = (Button) findViewById(R.id.button2);


        b.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                mp = MediaPlayer.create(MainActivity.this, R.raw.game);
                mp.start();
            }
        });

        b2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mp.stop();
               // mp.start();
            }
        });
    }

Mock a constructor with parameter

Mockito has limitations testing final, static, and private methods.

with jMockit testing library, you can do few stuff very easy and straight-forward as below:

Mock constructor of a java.io.File class:

new MockUp<File>(){
    @Mock
    public void $init(String pathname){
        System.out.println(pathname);
        // or do whatever you want
    }
};
  • the public constructor name should be replaced with $init
  • arguments and exceptions thrown remains same
  • return type should be defined as void

Mock a static method:

  • remove static from the method mock signature
  • method signature remains same otherwise

Jquery change background color

try putting a delay on the last color fade.

$("p#44.test").delay(3000).css("background-color","red");

What are valid values for the id attribute in HTML?
ID's cannot start with digits!!!

Disable spell-checking on HTML textfields

While specifying spellcheck="false" in the < tag > will certainly disable that feature, it's handy to be able to toggle that functionality on and off as needed after the page has loaded. So here's a non-jQuery way to set the spellcheck attribute programmatically:

:

<textarea id="my-ta" spellcheck="whatever">abcd dcba</textarea>

:

function setSpellCheck( mode ) {
    var myTextArea = document.getElementById( "my-ta" )
        , myTextAreaValue = myTextArea.value
    ;
    myTextArea.value = '';
    myTextArea.setAttribute( "spellcheck", String( mode ) );
    myTextArea.value = myTextAreaValue;
    myTextArea.focus();
}

:

setSpellCheck( true );
setSpellCheck( 'false' );

The function argument may be either boolean or string.

No need to loop through the textarea contents, we just cut 'n paste what's there, and then set focus.

Tested in blink engines (Chrome(ium), Edge, etc.)

how to rotate text left 90 degree and cell size is adjusted according to text in html

You can do that by applying your rotate CSS to an inner element and then adjusting the height of the element to match its width since the element was rotated to fit it into the <td>.

Also make sure you change your id #rotate to a class since you have multiple.

A 4x3 table with the headers in the first column rotated by 90 degrees

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $('.rotate').css('height', $('.rotate').width());_x000D_
});
_x000D_
td {_x000D_
  border-collapse: collapse;_x000D_
  border: 1px black solid;_x000D_
}_x000D_
tr:nth-of-type(5) td:nth-of-type(1) {_x000D_
  visibility: hidden;_x000D_
}_x000D_
.rotate {_x000D_
  /* FF3.5+ */_x000D_
  -moz-transform: rotate(-90.0deg);_x000D_
  /* Opera 10.5 */_x000D_
  -o-transform: rotate(-90.0deg);_x000D_
  /* Saf3.1+, Chrome */_x000D_
  -webkit-transform: rotate(-90.0deg);_x000D_
  /* IE6,IE7 */_x000D_
  filter: progid: DXImageTransform.Microsoft.BasicImage(rotation=0.083);_x000D_
  /* IE8 */_x000D_
  -ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=0.083)";_x000D_
  /* Standard */_x000D_
  transform: rotate(-90.0deg);_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<table cellpadding="0" cellspacing="0" align="center">_x000D_
  <tr>_x000D_
    <td>_x000D_
      <div class='rotate'>10kg</div>_x000D_
    </td>_x000D_
    <td>B</td>_x000D_
    <td>C</td>_x000D_
    <td>D</td>_x000D_
    <td>E</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>_x000D_
      <div class='rotate'>20kg</div>_x000D_
    </td>_x000D_
    <td>G</td>_x000D_
    <td>H</td>_x000D_
    <td>I</td>_x000D_
    <td>J</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>_x000D_
      <div class='rotate'>30kg</div>_x000D_
    </td>_x000D_
    <td>L</td>_x000D_
    <td>M</td>_x000D_
    <td>N</td>_x000D_
    <td>O</td>_x000D_
  </tr>_x000D_
_x000D_
_x000D_
</table>
_x000D_
_x000D_
_x000D_

JavaScript

The equivalent to the above in pure JavaScript is as follows:

jsFiddle

window.addEventListener('load', function () {
    var rotates = document.getElementsByClassName('rotate');
    for (var i = 0; i < rotates.length; i++) {
        rotates[i].style.height = rotates[i].offsetWidth + 'px';
    }
});

Select <a> which href ends with some string

$("a[href*=ABC]").addClass('selected');

If statement for strings in python?

Python is a case-sensitive language. All Python keywords are lowercase. Use if, not If.

Also, don't put a colon after the call to print(). Also, indent the print() and exit() calls, as Python uses indentation rather than brackets to represent code blocks.

And also, proceed = "y" or "Y" won't do what you want. Use proceed = "y" and if answer.lower() == proceed:, or something similar.

There's also the fact that your program will exit as long as the input value is not the single character "y" or "Y", which contradicts the prompting of "N" for the alternate case. Instead of your else clause there, use elif answer.lower() == info_incorrect:, with info_incorrect = "n" somewhere beforehand. Then just reprompt for the response or something if the input value was something else.


I'd recommend going through the tutorial in the Python documentation if you're having this much trouble the way you're learning now. http://docs.python.org/tutorial/index.html

How to do sed like text replace with python?

I wanted to be able to find and replace text but also include matched groups in the content I insert. I wrote this short script to do that:

https://gist.github.com/turtlemonvh/0743a1c63d1d27df3f17

The key component of that is something that looks like like this:

print(re.sub(pattern, template, text).rstrip("\n"))

Here's an example of how that works:

# Find everything that looks like 'dog' or 'cat' followed by a space and a number
pattern = "((cat|dog) (\d+))"

# Replace with 'turtle' and the number. '3' because the number is the 3rd matched group.
# The double '\' is needed because you need to escape '\' when running this in a python shell
template = "turtle \\3"

# The text to operate on
text = "cat 976 is my favorite"

Calling the above function with this yields:

turtle 976 is my favorite

Create random list of integers in Python

All the random methods end up calling random.random() so the best way is to call it directly:

[int(1000*random.random()) for i in xrange(10000)]

For example,

  • random.randint calls random.randrange.
  • random.randrange has a bunch of overhead to check the range before returning istart + istep*int(self.random() * n).

NumPy is much faster still of course.

How do I mock a service that returns promise in AngularJS Jasmine unit test?

Honestly.. you are going about this the wrong way by relying on inject to mock a service instead of module. Also, calling inject in a beforeEach is an anti-pattern as it makes mocking difficult on a per test basis.

Here is how I would do this...

module(function ($provide) {
  // By using a decorator we can access $q and stub our method with a promise.
  $provide.decorator('myOtherService', function ($delegate, $q) {

    $delegate.makeRemoteCallReturningPromise = function () {
      var dfd = $q.defer();
      dfd.resolve('some value');
      return dfd.promise;
    };
  });
});

Now when you inject your service it will have a properly mocked method for usage.