Programs & Examples On #Blame

Blame is the annotation of source code showing who last edited each section or line.

Git blame -- prior commits?

Build on stangls's answer, I put this script in my PATH (even on Windows) as git-bh:

That allows me to look for all commits where a word was involved:

git bh path/to/myfile myWord

Script:

#!/bin/bash
f=$1
shift
csha=""
{ git log --pretty=format:%H -- "$f"; echo; } | {
  while read hash; do
    res=$(git blame -L"/$1/",+1 $hash -- "$f" 2>/dev/null | sed 's/^/  /')
    sha=${res%% (*}
    if [[ "${res}" != "" && "${csha}" != "${sha}" ]]; then
      echo "--- ${hash}"
      echo "${res}"
      csha="${sha}"
    fi
  done
}

Retrieving an element from array list in Android?

In arraylist you have a positional order and not a nominal order, so you need to know in advance the element position you need to select or you must loop between elements until you find the element that you need to use. To do this you can use an iterator and an if, for example:

Iterator iter = list.iterator();
while (iter.hasNext())
{
    // if here          
    System.out.println("string " + iter.next());
}

Creating runnable JAR with Gradle

Have you tried the 'installApp' task? Does it not create a full directory with a set of start scripts?

http://www.gradle.org/docs/current/userguide/application_plugin.html

Does C++ support 'finally' blocks? (And what's this 'RAII' I keep hearing about?)

why is it that even managed languages provide a finally-block despite resources being deallocated automatically by the garbage collector anyway?

Actually, languages based on Garbage collectors need "finally" more. A garbage collector does not destroy your objects in a timely manner, so it can not be relied upon to clean up non-memory related issues correctly.

In terms of dynamically-allocated data, many would argue that you should be using smart-pointers.

However...

RAII moves the responsibility of exception safety from the user of the object to the designer

Sadly this is its own downfall. Old C programming habits die hard. When you're using a library written in C or a very C style, RAII won't have been used. Short of re-writing the entire API front-end, that's just what you have to work with. Then the lack of "finally" really bites.

Reset Entity-Framework Migrations

In EF6

  1. Delete all your files in 'migrations' folder... But not the 'initial create' or 'config'.
  2. Delete the database.
  3. Now run Add-Migration Initial.
  4. Now you can 'update-database' and all will be well.

How to change the background color on a Java panel?

I think what he is trying to say is to use the getContentPane().setBackground(Color.the_Color_you_want_here)

but if u want to set the color to any other then the JFrame, you use the object.setBackground(Color.the_Color_you_want_here)

Eg:

jPanel.setbackground(Color.BLUE)

Best way to replace multiple characters in a string?

Replacing two characters

I timed all the methods in the current answers along with one extra.

With an input string of abc&def#ghi and replacing & -> \& and # -> \#, the fastest way was to chain together the replacements like this: text.replace('&', '\&').replace('#', '\#').

Timings for each function:

  • a) 1000000 loops, best of 3: 1.47 µs per loop
  • b) 1000000 loops, best of 3: 1.51 µs per loop
  • c) 100000 loops, best of 3: 12.3 µs per loop
  • d) 100000 loops, best of 3: 12 µs per loop
  • e) 100000 loops, best of 3: 3.27 µs per loop
  • f) 1000000 loops, best of 3: 0.817 µs per loop
  • g) 100000 loops, best of 3: 3.64 µs per loop
  • h) 1000000 loops, best of 3: 0.927 µs per loop
  • i) 1000000 loops, best of 3: 0.814 µs per loop

Here are the functions:

def a(text):
    chars = "&#"
    for c in chars:
        text = text.replace(c, "\\" + c)


def b(text):
    for ch in ['&','#']:
        if ch in text:
            text = text.replace(ch,"\\"+ch)


import re
def c(text):
    rx = re.compile('([&#])')
    text = rx.sub(r'\\\1', text)


RX = re.compile('([&#])')
def d(text):
    text = RX.sub(r'\\\1', text)


def mk_esc(esc_chars):
    return lambda s: ''.join(['\\' + c if c in esc_chars else c for c in s])
esc = mk_esc('&#')
def e(text):
    esc(text)


def f(text):
    text = text.replace('&', '\&').replace('#', '\#')


def g(text):
    replacements = {"&": "\&", "#": "\#"}
    text = "".join([replacements.get(c, c) for c in text])


def h(text):
    text = text.replace('&', r'\&')
    text = text.replace('#', r'\#')


def i(text):
    text = text.replace('&', r'\&').replace('#', r'\#')

Timed like this:

python -mtimeit -s"import time_functions" "time_functions.a('abc&def#ghi')"
python -mtimeit -s"import time_functions" "time_functions.b('abc&def#ghi')"
python -mtimeit -s"import time_functions" "time_functions.c('abc&def#ghi')"
python -mtimeit -s"import time_functions" "time_functions.d('abc&def#ghi')"
python -mtimeit -s"import time_functions" "time_functions.e('abc&def#ghi')"
python -mtimeit -s"import time_functions" "time_functions.f('abc&def#ghi')"
python -mtimeit -s"import time_functions" "time_functions.g('abc&def#ghi')"
python -mtimeit -s"import time_functions" "time_functions.h('abc&def#ghi')"
python -mtimeit -s"import time_functions" "time_functions.i('abc&def#ghi')"

Replacing 17 characters

Here's similar code to do the same but with more characters to escape (\`*_{}>#+-.!$):

def a(text):
    chars = "\\`*_{}[]()>#+-.!$"
    for c in chars:
        text = text.replace(c, "\\" + c)


def b(text):
    for ch in ['\\','`','*','_','{','}','[',']','(',')','>','#','+','-','.','!','$','\'']:
        if ch in text:
            text = text.replace(ch,"\\"+ch)


import re
def c(text):
    rx = re.compile('([&#])')
    text = rx.sub(r'\\\1', text)


RX = re.compile('([\\`*_{}[]()>#+-.!$])')
def d(text):
    text = RX.sub(r'\\\1', text)


def mk_esc(esc_chars):
    return lambda s: ''.join(['\\' + c if c in esc_chars else c for c in s])
esc = mk_esc('\\`*_{}[]()>#+-.!$')
def e(text):
    esc(text)


def f(text):
    text = text.replace('\\', '\\\\').replace('`', '\`').replace('*', '\*').replace('_', '\_').replace('{', '\{').replace('}', '\}').replace('[', '\[').replace(']', '\]').replace('(', '\(').replace(')', '\)').replace('>', '\>').replace('#', '\#').replace('+', '\+').replace('-', '\-').replace('.', '\.').replace('!', '\!').replace('$', '\$')


def g(text):
    replacements = {
        "\\": "\\\\",
        "`": "\`",
        "*": "\*",
        "_": "\_",
        "{": "\{",
        "}": "\}",
        "[": "\[",
        "]": "\]",
        "(": "\(",
        ")": "\)",
        ">": "\>",
        "#": "\#",
        "+": "\+",
        "-": "\-",
        ".": "\.",
        "!": "\!",
        "$": "\$",
    }
    text = "".join([replacements.get(c, c) for c in text])


def h(text):
    text = text.replace('\\', r'\\')
    text = text.replace('`', r'\`')
    text = text.replace('*', r'\*')
    text = text.replace('_', r'\_')
    text = text.replace('{', r'\{')
    text = text.replace('}', r'\}')
    text = text.replace('[', r'\[')
    text = text.replace(']', r'\]')
    text = text.replace('(', r'\(')
    text = text.replace(')', r'\)')
    text = text.replace('>', r'\>')
    text = text.replace('#', r'\#')
    text = text.replace('+', r'\+')
    text = text.replace('-', r'\-')
    text = text.replace('.', r'\.')
    text = text.replace('!', r'\!')
    text = text.replace('$', r'\$')


def i(text):
    text = text.replace('\\', r'\\').replace('`', r'\`').replace('*', r'\*').replace('_', r'\_').replace('{', r'\{').replace('}', r'\}').replace('[', r'\[').replace(']', r'\]').replace('(', r'\(').replace(')', r'\)').replace('>', r'\>').replace('#', r'\#').replace('+', r'\+').replace('-', r'\-').replace('.', r'\.').replace('!', r'\!').replace('$', r'\$')

Here's the results for the same input string abc&def#ghi:

  • a) 100000 loops, best of 3: 6.72 µs per loop
  • b) 100000 loops, best of 3: 2.64 µs per loop
  • c) 100000 loops, best of 3: 11.9 µs per loop
  • d) 100000 loops, best of 3: 4.92 µs per loop
  • e) 100000 loops, best of 3: 2.96 µs per loop
  • f) 100000 loops, best of 3: 4.29 µs per loop
  • g) 100000 loops, best of 3: 4.68 µs per loop
  • h) 100000 loops, best of 3: 4.73 µs per loop
  • i) 100000 loops, best of 3: 4.24 µs per loop

And with a longer input string (## *Something* and [another] thing in a longer sentence with {more} things to replace$):

  • a) 100000 loops, best of 3: 7.59 µs per loop
  • b) 100000 loops, best of 3: 6.54 µs per loop
  • c) 100000 loops, best of 3: 16.9 µs per loop
  • d) 100000 loops, best of 3: 7.29 µs per loop
  • e) 100000 loops, best of 3: 12.2 µs per loop
  • f) 100000 loops, best of 3: 5.38 µs per loop
  • g) 10000 loops, best of 3: 21.7 µs per loop
  • h) 100000 loops, best of 3: 5.7 µs per loop
  • i) 100000 loops, best of 3: 5.13 µs per loop

Adding a couple of variants:

def ab(text):
    for ch in ['\\','`','*','_','{','}','[',']','(',')','>','#','+','-','.','!','$','\'']:
        text = text.replace(ch,"\\"+ch)


def ba(text):
    chars = "\\`*_{}[]()>#+-.!$"
    for c in chars:
        if c in text:
            text = text.replace(c, "\\" + c)

With the shorter input:

  • ab) 100000 loops, best of 3: 7.05 µs per loop
  • ba) 100000 loops, best of 3: 2.4 µs per loop

With the longer input:

  • ab) 100000 loops, best of 3: 7.71 µs per loop
  • ba) 100000 loops, best of 3: 6.08 µs per loop

So I'm going to use ba for readability and speed.

Addendum

Prompted by haccks in the comments, one difference between ab and ba is the if c in text: check. Let's test them against two more variants:

def ab_with_check(text):
    for ch in ['\\','`','*','_','{','}','[',']','(',')','>','#','+','-','.','!','$','\'']:
        if ch in text:
            text = text.replace(ch,"\\"+ch)

def ba_without_check(text):
    chars = "\\`*_{}[]()>#+-.!$"
    for c in chars:
        text = text.replace(c, "\\" + c)

Times in µs per loop on Python 2.7.14 and 3.6.3, and on a different machine from the earlier set, so cannot be compared directly.

?-------------------------------------------------------------?
¦ Py, input  ¦  ab  ¦ ab_with_check ¦  ba  ¦ ba_without_check ¦
¦------------+------+---------------+------+------------------¦
¦ Py2, short ¦ 8.81 ¦    4.22       ¦ 3.45 ¦    8.01          ¦
¦ Py3, short ¦ 5.54 ¦    1.34       ¦ 1.46 ¦    5.34          ¦
+------------+------+---------------+------+------------------¦
¦ Py2, long  ¦ 9.3  ¦    7.15       ¦ 6.85 ¦    8.55          ¦
¦ Py3, long  ¦ 7.43 ¦    4.38       ¦ 4.41 ¦    7.02          ¦
+-------------------------------------------------------------+

We can conclude that:

  • Those with the check are up to 4x faster than those without the check

  • ab_with_check is slightly in the lead on Python 3, but ba (with check) has a greater lead on Python 2

  • However, the biggest lesson here is Python 3 is up to 3x faster than Python 2! There's not a huge difference between the slowest on Python 3 and fastest on Python 2!

How do I do an OR filter in a Django query?

Similar to older answers, but a bit simpler, without the lambda:

filter_kwargs = {
    'field_a': 123,
    'field_b__in': (3, 4, 5, ),
}

To filter these two conditions using OR:

Item.objects.filter(Q(field_a=123) | Q(field_b__in=(3, 4, 5, ))

To get the same result programmatically:

list_of_Q = [Q(**{key: val}) for key, val in filter_kwargs.items()]
Item.objects.filter(reduce(operator.or_, list_of_Q))

(broken in two lines here, for clarity)

operator is in standard library: import operator
From docstring:

or_(a, b) -- Same as a | b.

For Python3, reduce is not a builtin any more but is still in the standard library: from functools import reduce


P.S.

Don't forget to make sure list_of_Q is not empty - reduce() will choke on empty list, it needs at least one element.

Detect iPad users using jQuery?

I use this:

function fnIsAppleMobile() 
{
    if (navigator && navigator.userAgent && navigator.userAgent != null) 
    {
        var strUserAgent = navigator.userAgent.toLowerCase();
        var arrMatches = strUserAgent.match(/(iphone|ipod|ipad)/);
        if (arrMatches != null) 
             return true;
    } // End if (navigator && navigator.userAgent) 

    return false;
} // End Function fnIsAppleMobile


var bIsAppleMobile = fnIsAppleMobile(); // TODO: Write complaint to CrApple asking them why they don't update SquirrelFish with bugfixes, then remove

What to do with branch after merge

I prefer RENAME rather than DELETE

All my branches are named in the form of

  • Fix/fix-<somedescription> or
  • Ftr/ftr-<somedescription> or
  • etc.

Using Tower as my git front end, it neatly organizes all the Ftr/, Fix/, Test/ etc. into folders.
Once I am done with a branch, I rename them to Done/...-<description>.

That way they are still there (which can be handy to provide history) and I can always go back knowing what it was (feature, fix, test, etc.)

How to remove the left part of a string?

Another simple one-liner that hasn't been mentioned here:

value = line.split("Path=", 1)[-1]

This will also work properly for various edge cases:

>>> print("prefixfoobar".split("foo", 1)[-1])
"bar"

>>> print("foofoobar".split("foo", 1)[-1])
"foobar"

>>> print("foobar".split("foo", 1)[-1])
"bar"

>>> print("bar".split("foo", 1)[-1])
"bar"

>>> print("".split("foo", 1)[-1])
""

How to check if current thread is not main thread

Allow me to preface this with: I acknowledged this post has the 'Android' tag, however, my search had nothing to do with 'Android' and this was my top result. To that end, for the non-Android SO Java users landing here, don't forget about:

public static void main(String[] args{
    Thread.currentThread().setName("SomeNameIChoose");
    /*...the rest of main...*/
}

After setting this, elsewhere in your code, you can easily check if you're about to execute on the main thread with:

if(Thread.currentThread().getName().equals("SomeNameIChoose"))
{
    //do something on main thread
}

A bit embarrassed I had searched before remembering this, but hopefully it will help someone else!

Is it possible to assign numeric value to an enum in Java?

Yes, and then some, example from documentation:

public enum Planet {
    MERCURY (3.303e+23, 2.4397e6),
    VENUS   (4.869e+24, 6.0518e6),
    EARTH   (5.976e+24, 6.37814e6),
    MARS    (6.421e+23, 3.3972e6),
    JUPITER (1.9e+27,   7.1492e7),
    SATURN  (5.688e+26, 6.0268e7),
    URANUS  (8.686e+25, 2.5559e7),
    NEPTUNE (1.024e+26, 2.4746e7);

    // in kilograms
    private final double mass;
    // in meters
    private final double radius;
    Planet(double mass, double radius) {
        this.mass = mass;
        this.radius = radius;
    }
    private double mass() { return mass; }
    private double radius() { return radius; }

    // universal gravitational 
    // constant  (m3 kg-1 s-2)
    public static final double G = 6.67300E-11;

    double surfaceGravity() {
        return G * mass / (radius * radius);
    }
    double surfaceWeight(double otherMass) {
        return otherMass * surfaceGravity();
    }
    public static void main(String[] args) {
        if (args.length != 1) {
            System.err.println("Usage: java Planet <earth_weight>");
            System.exit(-1);
        }
        double earthWeight = Double.parseDouble(args[0]);
        double mass = earthWeight/EARTH.surfaceGravity();
        for (Planet p : Planet.values())
           System.out.printf("Your weight on %s is %f%n",
                             p, p.surfaceWeight(mass));
    }
}

htaccess - How to force the client's browser to clear the cache?

As other answers have said, changing the URL is a good cache busting technique, however it is alot of work to go through a bigger site, change all the URLs and also move the files.

A similar technique is to just add a version parameter to the URL string which is either a random string / number or a version number, and target the changed files only.

For instance if you change your sites CSS and it looks wonky until you do a force refresh, simply add ?ver=1.1 to the CSS import at the head of the file. This to the browser is a different file, but you only need to change the import, not the actual location or name of the file.

e.g:

<link href="assets/css/style.css" rel="stylesheet" type="text/css" />

becomes

<link href="assets/css/style.css?ver=1.1" rel="stylesheet" type="text/css" />

Works great for javascript files also.

String replacement in Objective-C

You could use the method

- (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target 
                                        withString:(NSString *)replacement

...to get a new string with a substring replaced (See NSString documentation for others)

Example use

NSString *str = @"This is a string";

str = [str stringByReplacingOccurrencesOfString:@"string"
                                     withString:@"duck"];

Parsing JSON in Java without knowing JSON format

JSON of unknown format to HashMap

writing JSON And reading Json

public static JsonParser parser = new JsonParser();
public static void main(String args[]) {
     writeJson("JsonFile.json");
     readgson("JsonFile.json");
}
public static void readgson(String file) {
    try {
        System.out.println( "Reading JSON file from Java program" );

        FileReader fileReader = new FileReader( file );
        com.google.gson.JsonObject object = (JsonObject) parser.parse( fileReader );

        Set <java.util.Map.Entry<String, com.google.gson.JsonElement>> keys = object.entrySet();
        if ( keys.isEmpty() ) {
            System.out.println( "Empty JSON Object" );
        }else {
            Map<String, Object> map = json_UnKnown_Format( keys );
            System.out.println("Json 2 Map : "+map);
        }

    } catch (IOException ex) {
        System.out.println("Input File Does not Exists.");
    }
}
public static Map<String, Object> json_UnKnown_Format( Set <java.util.Map.Entry<String, com.google.gson.JsonElement>> keys ){
    Map<String, Object> jsonMap = new HashMap<String, Object>();
    for (Entry<String, JsonElement> entry : keys) {
        String keyEntry = entry.getKey();
        System.out.println(keyEntry + " : ");
        JsonElement valuesEntry =  entry.getValue();
        if (valuesEntry.isJsonNull()) {
            System.out.println(valuesEntry);
            jsonMap.put(keyEntry, valuesEntry);
        }else if (valuesEntry.isJsonPrimitive()) {
            System.out.println("P - "+valuesEntry);
            jsonMap.put(keyEntry, valuesEntry);
        }else if (valuesEntry.isJsonArray()) {
            JsonArray array = valuesEntry.getAsJsonArray();
            List<Object> array2List = new ArrayList<Object>();
            for (JsonElement jsonElements : array) {
                System.out.println("A - "+jsonElements);
                array2List.add(jsonElements);
            }
            jsonMap.put(keyEntry, array2List);
        }else if (valuesEntry.isJsonObject()) {             
             com.google.gson.JsonObject obj = (JsonObject) parser.parse(valuesEntry.toString());                    
             Set <java.util.Map.Entry<String, com.google.gson.JsonElement>> obj_key = obj.entrySet();
             jsonMap.put(keyEntry, json_UnKnown_Format(obj_key));
        }
    }
    return jsonMap;
}
@SuppressWarnings("unchecked")
public static void writeJson( String file ) {

    JSONObject json = new JSONObject();

    json.put("Key1", "Value");
    json.put("Key2", 777); // Converts to "777"
    json.put("Key3", null);
    json.put("Key4", false);

        JSONArray jsonArray = new JSONArray();
        jsonArray.put("Array-Value1");
        jsonArray.put(10); 
        jsonArray.put("Array-Value2");

    json.put("Array : ", jsonArray); // "Array":["Array-Value1", 10,"Array-Value2"]

        JSONObject jsonObj = new JSONObject();
        jsonObj.put("Obj-Key1", 20);
        jsonObj.put("Obj-Key2", "Value2");
        jsonObj.put(4, "Value2"); // Converts to "4"

    json.put("InnerObject", jsonObj);

        JSONObject jsonObjArray = new JSONObject();
            JSONArray objArray = new JSONArray();
            objArray.put("Obj-Array1");
            objArray.put(0, "Obj-Array3");
        jsonObjArray.put("ObjectArray", objArray);

    json.put("InnerObjectArray", jsonObjArray);

        Map<String, Integer> sortedTree = new TreeMap<String, Integer>();
        sortedTree.put("Sorted1", 10);
        sortedTree.put("Sorted2", 103);
        sortedTree.put("Sorted3", 14);

    json.put("TreeMap", sortedTree);        

    try {
        System.out.println("Writting JSON into file ...");
        System.out.println(json);
        FileWriter jsonFileWriter = new FileWriter(file);
        jsonFileWriter.write(json.toJSONString());
        jsonFileWriter.flush();
        jsonFileWriter.close();
        System.out.println("Done");

    } catch (IOException e) { 
        e.printStackTrace();
    }

}

How to get a password from a shell script without echoing

One liner:

read -s -p "Password: " password

Under Linux (and cygwin) this form works in bash and sh. It may not be standard Unix sh, though.

For more info and options, in bash, type "help read".

$ help read
read: read [-ers] [-a array] [-d delim] [-i text] [-n nchars] [-N nchars] [-p prompt] [-t timeout] [-u fd] [name ...]
Read a line from the standard input and split it into fields.
  ...
  -p prompt output the string PROMPT without a trailing newline before
            attempting to read
  ...
  -s                do not echo input coming from a terminal

pip installing in global site-packages instead of virtualenv

Go to bin directory in your virtual environment and write like this:

./pip3 install <package-name>

How to create an alert message in jsp page after submit process is complete

You can also create a new jsp file sayng that form is submited and in your main action file just write its file name

Eg. Your form is submited is in a file succes.jsp Then your action file will have

Request.sendRedirect("success.jsp")

Cannot resolve symbol HttpGet,HttpClient,HttpResponce in Android Studio

please add these codes to your dependencies. It will work.

implementation 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'
dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    implementation 'com.android.support:appcompat-v7:23.1.0'
    implementation 'com.android.support:design:23.1.0'
    implementation 'com.android.support:cardview-v7:23.1.0'
    implementation 'com.android.support:recyclerview-v7:23.1.0'

    implementation 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'
}

Set a thin border using .css() in javascript

After a few futile hours battling with a 'SyntaxError: missing : after property id' message I can now expand on this topic:

border-width is a valid css property but it is not included in the jQuery css oject definition, so .css({border-width: '2px'}) will cause an error, but it's quite happy with .css({'border-width': '2px'}), presumably property names in quotes are just passed on as received.

How to preview a part of a large pandas DataFrame, in iPython notebook?

In Python pandas provide head() and tail() to print head and tail data respectively.

import pandas as pd
train = pd.read_csv('file_name')
train.head() # it will print 5 head row data as default value is 5
train.head(n) # it will print n head row data
train.tail() #it will print 5 tail row data as default value is 5
train.tail(n) #it will print n tail row data

How to bind bootstrap popover on dynamic elements

This is how I made the code so it can handle dynamically created elements using popover feature. Using this code, you can trigger the popover to show by default.

HTML:

<div rel="this-should-be-the-target">
</div>

JQuery:

$(function() {
    var targetElement = 'rel="this-should-be-the-target"';
    initPopover(targetElement, "Test Popover Content");

    // use this line if you want it to show by default
    $(targetElement).popover('show');
    
    function initPopover(target, popOverContent) {
        $(target).each(function(i, obj) {
            $(this).popover({
                placement : 'auto',
                trigger : 'hover',
                "html": true,
                content: popOverContent
            });
         });
     }
});

WebDriverException: unknown error: DevToolsActivePort file doesn't exist while trying to initiate Chrome Browser

I had the same problem in python. The above helped. Here is what I used in python -

chrome_options = Options()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')
driver = webdriver.Chrome('/path/to/your_chrome_driver_dir/chromedriver',chrome_options=chrome_options)

Draw a connecting line between two elements

mxGraph — used by draw.io — supports this use case, with its Grapheditor example. Documentation. Examples.

This answer is based off of Vainbhav Jain's answer.

Pagination response payload from a RESTful API

just add in your backend API new property's into response body. from example .net core:

[Authorize]
[HttpGet]
public async Task<IActionResult> GetUsers([FromQuery]UserParams userParams)
{
  var users = await _repo.GetUsers(userParams);
  var usersToReturn = _mapper.Map<IEnumerable<UserForListDto>>(users);


  // create new object and add into it total count param etc
  var UsersListResult = new
  {
    usersToReturn,
    currentPage = users.CurrentPage,
    pageSize = users.PageSize,
    totalCount = users.TotalCount,
    totalPages = users.TotalPages
  };

  return Ok(UsersListResult);
}

In body response it look like this

{
"usersToReturn": [
    {
        "userId": 1,
        "username": "[email protected]",
        "firstName": "Joann",
        "lastName": "Wilson",
        "city": "Armstrong",
        "phoneNumber": "+1 (893) 515-2172"
    },
    {
        "userId": 2,
        "username": "[email protected]",
        "firstName": "Booth",
        "lastName": "Drake",
        "city": "Franks",
        "phoneNumber": "+1 (800) 493-2168"
    }
],
// metadata to pars in client side
"currentPage": 1,
"pageSize": 2,
"totalCount": 87,
"totalPages": 44

}

Get ID of element that called a function

i also want this to happen , so just pass the id of the element in the called function and used in my js file :

function copy(i,n)
{
 var range = document.createRange();
range.selectNode(document.getElementById(i));
window.getSelection().removeAllRanges();
window.getSelection().addRange(range); 
document.execCommand('copy');
window.getSelection().removeAllRanges();
document.getElementById(n).value = "Copied";
}

Error: Could not create the Java Virtual Machine Mac OSX Mavericks

So try uninstalling all other versions other than the one you need, then set the JAVA_HOMEpath variable for that JDK remaining, and you're done.

That's worked for me, I have two JDK (version 8 & 11) installed on my local mac, that causes the issue, for uninstalling, I followed these two steps:

  • cd /Library/Java/JavaVirtualMachines
  • rm -rf openjdk-11.0.1.jdk

Create list or arrays in Windows Batch

@echo off

set array=

setlocal ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION

set nl=^&echo(

set array=auto blue ^!nl!^
  bycicle green ^!nl!^
  buggy   red

echo convert the String in indexed arrays

set /a index=0

for /F "tokens=1,2,3*" %%a in ( 'echo(!array!' ) do (

 echo(vehicle[!index!]=%%a color[!index!]=%%b 
 set vehicle[!index!]=%%a
 set color[!index!]=%%b
 set /a index=!index!+1   

)

echo use the arrays

echo(%vehicle[1]% %color[1]%
echo oder

set index=1
echo(!vehicle[%index%]! !color[%index%]!

Foreign key referencing a 2 columns primary key in SQL Server

The key is "the order of the column should be the same"

Example:

create Table A (
    A_ID char(3) primary key,
    A_name char(10) primary key,
    A_desc desc char(50)
)

create Table B (
    B_ID char(3) primary key,
    B_A_ID char(3),
    B_A_Name char(10),
    constraint [Fk_B_01] foreign key (B_A_ID,B_A_Name) references A(A_ID,A_Name)
)

the column order on table A should be --> A_ID then A_Name; defining the foreign key should follow the same order as well.

CSS word-wrapping in div

As Andrew said, your text should be doing just that.

There is one instance that I can think of that will behave in the manner you suggest, and that is if you have the whitespace property set.

See if you don't have the following in your CSS somewhere:

white-space: nowrap

That will cause text to continue on the same line until interrupted by a line break.

OK, my apologies, not sure if edited or added the mark-up afterwards (didn't see it at first).

The overflow-x property is what's causing the scroll bar to appear. Remove that and the div will adjust to as high as it needs to be to contain all your text.

Pass user defined environment variable to tomcat

My recipe to fix it:

  1. DID NOT WORK >> Set as system environment variable: I had set the environment variable in my mac bash_profile, however, Tomcat did not see that variable.

  2. DID NOT WORK >> setenv.sh: Apache's recommendation was to have user-defined environment variables in setenv.sh file and I did that.

  3. THIS WORKED!! >> After a little research into Tomcat startup scripts, I found that environment variables set using setenv.sh are lost during the startup. So I had to edit my catalina.sh against the recommendation of Apache and that did the trick.

Add your -DUSER_DEFINED variable in the run command in catalina.sh.

eval exec "\"$_RUNJAVA\"" "\"$LOGGING_CONFIG\"" $LOGGING_MANAGER $JAVA_OPTS $CATALINA_OPTS \
  -classpath "\"$CLASSPATH\"" \
  -Djava.security.manager \
  -Djava.security.policy=="\"$CATALINA_BASE/conf/catalina.policy\"" \
  -Dcatalina.base="\"$CATALINA_BASE\"" \
  -Dcatalina.home="\"$CATALINA_HOME\"" \
  -Djava.io.tmpdir="\"$CATALINA_TMPDIR\"" \
  -DUSER_DEFINED="$USER_DEFINED" \
  org.apache.catalina.startup.Bootstrap "$@" start

P.S: This problem could have been local to my computer. Others would have different problems. Adding my answer to this post just in case anyone is still facing issues with Tomcat not seeing the environment vars after trying out all recommended approaches.

AngularJs - ng-model in a SELECT

Select's default value should be one of its value in the list. In order to load the select with default value you can use ng-options. A scope variable need to be set in the controller and that variable is assigned as ng-model in HTML's select tag.

View this plunker for any references:

http://embed.plnkr.co/hQiYqaQXrtpxQ96gcZhq/preview

How to store the hostname in a variable in a .bat file?

I'm using the environment variable COMPUTERNAME:

copy "C:\Program Files\Windows Resource Kits\Tools\" %SYSTEMROOT%\system32
srvcheck \\%COMPUTERNAME% > c:\shares.txt
echo %COMPUTERNAME%

Delete data with foreign key in SQL Server table

So, you need to DELETE related rows from conflicted tables or more logical to UPDATE their FOREIGN KEY column to reference other PRIMARY KEY's from the parent table.

Also, you may want to read this article Don’t Delete – Just Don’t

In Python, what does dict.pop(a,b) mean?

def func(*args): 
    pass

When you define a function this way, *args will be array of arguments passed to the function. This allows your function to work without knowing ahead of time how many arguments are going to be passed to it.

You do this with keyword arguments too, using **kwargs:

def func2(**kwargs): 
    pass

See: Arbitrary argument lists


In your case, you've defined a class which is acting like a dictionary. The dict.pop method is defined as pop(key[, default]).

Your method doesn't use the default parameter. But, by defining your method with *args and passing *args to dict.pop(), you are allowing the caller to use the default parameter.

In other words, you should be able to use your class's pop method like dict.pop:

my_a = a()
value1 = my_a.pop('key1')       # throw an exception if key1 isn't in the dict
value2 = my_a.pop('key2', None) # return None if key2 isn't in the dict

Replace whitespaces with tabs in linux

Using Perl:

perl -p -i -e 's/ /\t/g' file.txt

How to add row in JTable?

The TableModel behind the JTable handles all of the data behind the table. In order to add and remove rows from a table, you need to use a DefaultTableModel

To create the table with this model:

JTable table = new JTable(new DefaultTableModel(new Object[]{"Column1", "Column2"}));

To add a row:

DefaultTableModel model = (DefaultTableModel) table.getModel();
model.addRow(new Object[]{"Column 1", "Column 2", "Column 3"});

You can also remove rows with this method.

Full details on the DefaultTableModel can be found here

Backbone.js fetch with parameters

You can also set processData to true:

collection.fetch({ 
    data: { page: 1 },
    processData: true
});

Jquery will auto process data object into param string,

but in Backbone.sync function, Backbone turn the processData off because Backbone will use other method to process data in POST,UPDATE...

in Backbone source:

if (params.type !== 'GET' && !Backbone.emulateJSON) {
    params.processData = false;
}

Iterating C++ vector from the end to the beginning

If you can use The Boost Library, there is the Boost.Range that provides the reverse range adapter by including:

#include <boost/range/adaptor/reversed.hpp>

Then, in combination with a C++11's range-for loop, you can just write the following:

for (auto& elem: boost::adaptors::reverse(my_vector)) {
   // ...
}

Since this code is briefer than the one using the iterator pair, it may be more readable and less prone to errors as there are fewer details to pay attention to.

Avoid printStackTrace(); use a logger call instead

Let's talk in from company concept. Log gives you flexible levels (see Difference between logger.info and logger.debug). Different people want to see different levels, like QAs, developers, business people. But e.printStackTrace() will print out everything. Also, like if this method will be restful called, this same error may print several times. Then the Devops or Tech-Ops people in your company may be crazy because they will receive the same error reminders. I think a better replacement could be log.error("errors happend in XXX", e) This will also print out whole information which is easy reading than e.printStackTrace()

Substring a string from the end of the string

I will trim the end for unwanted characters:

s = s.TrimEnd(' ', '!');

To ensure it works even with more spaces. Or better if you want to ensure it works always, since the input text seems to come from the user:

Regex r = new Regex(@"(?'purged'(\w|\s)+\w)");
Match m = r.Match("Hello Marco   !!");
if (m.Success)
{
    string result = m.Groups["purged"].Value;
}

With this you are safer. A purge based on the fact the last two characters has to be removed is too weak.

Drawing an image from a data URL to a canvas

function drawDataURIOnCanvas(strDataURI, canvas) {
    "use strict";
    var img = new window.Image();
    img.addEventListener("load", function () {
        canvas.getContext("2d").drawImage(img, 0, 0);
    });
    img.setAttribute("src", strDataURI);
}

Getting a slice of keys from a map

I made a sketchy benchmark on the three methods described in other responses.

Obviously pre-allocating the slice before pulling the keys is faster than appending, but surprisingly, the reflect.ValueOf(m).MapKeys() method is significantly slower than the latter:

? go run scratch.go
populating
filling 100000000 slots
done in 56.630774791s
running prealloc
took: 9.989049786s
running append
took: 18.948676741s
running reflect
took: 25.50070649s

Here's the code: https://play.golang.org/p/Z8O6a2jyfTH (running it in the playground aborts claiming that it takes too long, so, well, run it locally.)

How to add a fragment to a programmatically generated layout?

Below is a working code to add a fragment e.g 3 times to a vertical LinearLayout (xNumberLinear). You can change number 3 with any other number or take a number from a spinner!

for (int i = 0; i < 3; i++) {
            LinearLayout linearDummy = new LinearLayout(getActivity());
            linearDummy.setOrientation(LinearLayout.VERTICAL);
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {

                Toast.makeText(getActivity(), "This function works on newer versions of android", Toast.LENGTH_LONG).show();

            } else {
                linearDummy.setId(View.generateViewId());
            }
            fragmentManager.beginTransaction().add(linearDummy.getId(), new SomeFragment(),"someTag1").commit();

            xNumberLinear.addView(linearDummy);
        }

error: strcpy was not declared in this scope

Observations:

  • #include <cstring> should introduce std::strcpy().
  • using namespace std; (as written in medico.h) introduces any identifiers from std:: into the global namespace.

Aside from using namespace std; being somewhat clumsy once the application grows larger (as it introduces one hell of a lot of identifiers into the global namespace), and that you should never use using in a header file (see below!), using namespace does not affect identifiers introduced after the statement.

(using namespace std is written in the header, which is included in medico.cpp, but #include <cstring> comes after that.)

My advice: Put the using namespace std; (if you insist on using it at all) into medico.cpp, after any includes, and use explicit std:: in medico.h.


strcmpi() is not a standard function at all; while being defined on Windows, you have to solve case-insensitive compares differently on Linux.

(On general terms, I would like to point to this answer with regards to "proper" string handling in C and C++ that takes Unicode into account, as every application should. Summary: The standard cannot handle these things correctly; do use ICU.)


warning: deprecated conversion from string constant to ‘char*’

A "string constant" is when you write a string literal (e.g. "Hello") in your code. Its type is const char[], i.e. array of constant characters (as you cannot change the characters). You can assign an array to a pointer, but assigning to char *, i.e. removing the const qualifier, generates the warning you are seeing.


OT clarification: using in a header file changes visibility of identifiers for anyone including that header, which is usually not what the user of your header file wants. For example, I could use std::string and a self-written ::string just perfectly in my code, unless I include your medico.h, because then the two classes will clash.

Don't use using in header files.

And even in implementation files, it can introduce lots of ambiguity. There is a case to be made to use explicit namespacing in implementation files as well.

How to call execl() in C with the proper arguments?

If you need just to execute your VLC playback process and only give control back to your application process when it is done and nothing more complex, then i suppose you can use just:

system("The same thing you type into console");

How to roundup a number to the closest ten?

You could also use CEILING which rounds up to an integer or desired multiple of significance

ie
=CEILING(A1,10)
rounds up to a multiple of 10

12340.0001 will become 12350

Convert a bitmap into a byte array

Try the following:

MemoryStream stream = new MemoryStream();
Bitmap bitmap = new Bitmap();
bitmap.Save(stream, ImageFormat.Jpeg);

byte[] byteArray = stream.GetBuffer();

Make sure you are using:

System.Drawing & using System.Drawing.Imaging;

How do I create dynamic properties in C#?

Couldn't you just have your class expose a Dictionary object? Instead of "attaching more properties to the object", you could simply insert your data (with some identifier) into the dictionary at run time.

Initializing a dictionary in python with a key value and no corresponding values

It would be good to know what your purpose is, why you want to initialize the keys in the first place. I am not sure you need to do that at all.

1) If you want to count the number of occurrences of keys, you can just do:

Definition = {}
# ...
Definition[key] = Definition.get(key, 0) + 1

2) If you want to get None (or some other value) later for keys that you did not encounter, again you can just use the get() method:

Definition.get(key)  # returns None if key not stored
Definition.get(key, default_other_than_none)

3) For all other purposes, you can just use a list of the expected keys, and check if the keys found later match those.

For example, if you only want to store values for those keys:

expected_keys = ['apple', 'banana']
# ...
if key_found in expected_keys:
    Definition[key_found] = value

Or if you want to make sure all expected keys were found:

assert(all(key in Definition for key in expected_keys))

How to use pip with Python 3.x alongside Python 2.x

This worked for me on OS X: (I say this because sometimes is a pain that mac has "its own" version of every open source tool, and you cannot remove it because "its improvements" make it unique for other apple stuff to work, and if you remove it things start falling appart)

I followed the steps provided by @Lennart Regebro to get pip for python 3, nevertheless pip for python 2 was still first on the path, so... what I did is to create a symbolic link to python 3 inside /usr/bin (in deed I did the same to have my 2 pythons running in peace):

ln -s /Library/Frameworks/Python.framework/Versions/3.4/bin/pip /usr/bin/pip3

Notice that I added a 3 at the end, so basically what you have to do is to use pip3 instead of just pip.

The post is old but I hope this helps someone someday. this should theoretically work for any LINUX system.

how to access downloads folder in android?

You need to set this permission in your manifest.xml file

android.permission.WRITE_EXTERNAL_STORAGE

How to generate a create table script for an existing table in phpmyadmin?

Export whole database select format as SQL. Now, open that SQL file which you have downloaded using notepad, notepad++ or any editor. You will see all the tables and insert queries of your database. All scripts will be available there.

How can I install a local gem?

Also, you can use gem install --local path_to_gem/filename.gem

This will skip the usual gem repository scan that happens when you leave off --local.

You can find other magic with gem install --help.

Java - get index of key in HashMap?

Use LinkedHashMap instead of HashMap It will always return keys in same order (as insertion) when calling keySet()

For more detail, see Class LinkedHashMap

How do I set a Windows scheduled task to run in the background?

Assuming the application you are attempting to run in the background is CLI based, you can try calling the scheduled jobs using Hidden Start

Also see: http://www.howtogeek.com/howto/windows/hide-flashing-command-line-and-batch-file-windows-on-startup/

Str_replace for multiple items

str_replace() can take an array, so you could do:

$new_str = str_replace(str_split('\\/:*?"<>|'), ' ', $string);

Alternatively you could use preg_replace():

$new_str = preg_replace('~[\\\\/:*?"<>|]~', ' ', $string);

jQuery $.ajax(), $.post sending "OPTIONS" as REQUEST_METHOD in Firefox

This PHP at the top of the responding script seems to work. (With Firefox 3.6.11. I have not yet done a lot of testing.)

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Max-Age: 1000');
if(array_key_exists('HTTP_ACCESS_CONTROL_REQUEST_HEADERS', $_SERVER)) {
    header('Access-Control-Allow-Headers: '
           . $_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']);
} else {
    header('Access-Control-Allow-Headers: *');
}

if("OPTIONS" == $_SERVER['REQUEST_METHOD']) {
    exit(0);
}

C++ Fatal Error LNK1120: 1 unresolved externals

You must reference it. To do this, open the shortcut menu for the project in Solution Explorer, and then choose References. In the Property Pages dialog box, expand the Common Properties node, select Framework and References, and then choose the Add New Reference button.

How to represent multiple conditions in a shell if statement?

you can chain more than 2 conditions too :

if [ \( "$1" = '--usage' \) -o \( "$1" = '' \) -o \( "$1" = '--help' \) ]
then
   printf "\033[2J";printf "\033[0;0H"
   cat << EOF_PRINT_USAGE

   $0 - Purpose: upsert qto http json data to postgres db

   USAGE EXAMPLE:

   $0 -a foo -a bar



EOF_PRINT_USAGE
   exit 1
fi

getElementsByClassName not working

If you want to do it by ClassName you could do:

<script type="text/javascript">
function hideTd(className){
    var elements;

    if (document.getElementsByClassName)
    {
        elements = document.getElementsByClassName(className);
    }
    else
    {
        var elArray = [];
        var tmp = document.getElementsByTagName(elements);  
        var regex = new RegExp("(^|\\s)" + className+ "(\\s|$)");
        for ( var i = 0; i < tmp.length; i++ ) {

            if ( regex.test(tmp[i].className) ) {
                elArray.push(tmp[i]);
            }
        }

        elements = elArray;
    }

    for(var i = 0, i < elements.length; i++) {
       if( elements[i].textContent == ''){
          elements[i].style.display = 'none';
       } 
    }

  }
</script>

How do I increase modal width in Angular UI Bootstrap?

I found it easier to just take over the template from Bootstrap-ui. I have left the commented HTML still in-place to show what I changed.

Overwrite their default template:

<script type="text/ng-template" id="myDlgTemplateWrapper.html">
    <div tabindex="-1" role="dialog" class="modal fade" ng-class="{in: animate}" 
         ng-style="{'z-index': 1050 + index*10, display: 'block'}" ng-click="close($event)"> 
        <!-- <div class="modal-dialog"
            ng-class="{'modal-sm': size == 'sm', 'modal-lg': size == 'lg'}"
            >
            <div class="modal-content"  modal-transclude></div>
        </div>--> 

        <div modal-transclude>
            <!-- Your content goes here -->
        </div>
    </div>
</script>

Modify your dialog template (note the wrapper DIVs containing "modal-dialog" class and "modal-content" class):

<script type="text/ng-template" id="myModalContent.html">
    <div class="modal-dialog {{extraDlgClass}}"
         style="width: {{width}}; max-width: {{maxWidth}}; min-width: {{minWidth}}; ">
        <div class="modal-content">
            <div class="modal-header bg-primary">
                <h3>I am a more flexible modal!</h3>
            </div>
            <div class="modal-body"
                 style="min-height: {{minHeight}}; height: {{height}}; max-height {{maxHeight}}; ">
                <p>Make me any size you want</p>
            </div>
            <div class="modal-footer">
                <button class="btn btn-primary" ng-click="ok()">OK</button>
                <button class="btn btn-warning" ng-click="cancel()">Cancel</button>
            </div>
        </div>
    </div>
</script>

And then call the modal with whatever CSS class or style parameters you wish to change (assuming you have already defined "app" somewhere else):

<script type="text/javascript">
    app.controller("myTest", ["$scope", "$modal", function ($scope, $modal)
    {
        //  Adjust these with your parameters as needed

        $scope.extraDlgClass = undefined;

        $scope.width = "70%";
        $scope.height = "200px";
        $scope.maxWidth = undefined;
        $scope.maxHeight = undefined;
        $scope.minWidth = undefined;
        $scope.minHeight = undefined;

        $scope.open = function ()
        {
            $scope.modalInstance = $modal.open(
            {
                backdrop: 'static',
                keyboard: false,
                modalFade: true,

                templateUrl: "myModalContent.html",
                windowTemplateUrl: "myDlgTemplateWrapper.html",
                scope: $scope,
                //size: size,   - overwritten by the extraDlgClass below (use 'modal-lg' or 'modal-sm' if desired)

                extraDlgClass: $scope.extraDlgClass,

                width: $scope.width,
                height: $scope.height,
                maxWidth: $scope.maxWidth,
                maxHeight: $scope.maxHeight,
                minWidth: $scope.minWidth,
                minHeight: $scope.minHeight
            });

            $scope.modalInstance.result.then(function ()
            {
                console.log('Modal closed at: ' + new Date());
            },
            function ()
            {
                console.log('Modal dismissed at: ' + new Date());
            });
        };

        $scope.ok = function ($event)
        {
            if ($event)
                $event.preventDefault();
            $scope.modalInstance.close("OK");
        };

        $scope.cancel = function ($event)
        {
            if ($event)
                $event.preventDefault();
            $scope.modalInstance.dismiss('cancel');
        };

        $scope.openFlexModal = function ()
        {
            $scope.open();
        }

    }]);
</script>

Add an "open" button and fire away.

    <button ng-controller="myTest" class="btn btn-default" type="button" ng-click="openFlexModal();">Open Flex Modal!</button>

Now you can add whatever extra class you want, or simply change width/height sizes as necessary.

I further enclosed it within a wrapper directive, which is should be trivial from this point forward.

Cheers.

How to add a WiX custom action that happens only on uninstall (via MSI)?

The biggest problem with a batch script is handling rollback when the user clicks cancel (or something goes wrong during your install). The correct way to handle this scenario is to create a CustomAction that adds temporary rows to the RemoveFiles table. That way the Windows Installer handles the rollback cases for you. It is insanely simpler when you see the solution.

Anyway, to have an action only execute during uninstall add a Condition element with:

REMOVE ~= "ALL"

the ~= says compare case insensitive (even though I think ALL is always uppercaesd). See the MSI SDK documentation about Conditions Syntax for more information.

PS: There has never been a case where I sat down and thought, "Oh, batch file would be a good solution in an installation package." Actually, finding an installation package that has a batch file in it would only encourage me to return the product for a refund.

How to automatically indent source code?

I have tried both ways, and from the Edit|Advanced menu, and they are not doing anything to my source code. Other options like line indent are working. What could be wrong? – Chucky Jul 12 '13 at 11:06

Sometimes if it doesnt work, try to select a couple lines above and below or the whole block of code (whole function, whole cycle, whole switch, etc.), so that it knows how to indent.

Like for example if you copy/paste something into a case statement of a switch and it has wrong indentation, you need to select the text + the line with the case statement above to get it to work.

Read lines from a file into a Bash array

Your first attempt was close. Here is the simplistic approach using your idea.

file="somefileondisk"
lines=`cat $file`
for line in $lines; do
        echo "$line"
done

Convert regular Python string to raw string

With a little bit correcting @Jolly1234's Answer: here is the code:

raw_string=path.encode('unicode_escape').decode()

Deleting DataFrame row in Pandas based on column value

The given answer is correct nontheless as someone above said you can use df.query('line_race != 0') which depending on your problem is much faster. Highly recommend.

Keep placeholder text in UITextField on input in IOS

Instead of using the placeholder text, you'll want to set the actual text property of the field to MM/YYYY, set the delegate of the text field and listen for this method:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {     // update the text of the label } 

Inside that method, you can figure out what the user has typed as they type, which will allow you to update the label accordingly.

Difference between _self, _top, and _parent in the anchor tag target attribute

Below is an image showing nested frames and the effect of different target values, followed by an explanation of the image.

Different target values.1

Imagine a webpage containing 3 nested <iframe> aka "frame"/"frameset". So:

  • the outermost webpage/browser is the starting context
  • the outermost webpage is the parent of frame 3
  • frame 3 is the parent of frame 2
  • frame 2 is the parent of frame 1
  • frame 1 is the innermost frame

Then target attributes have these effects:

  • If frame 1 has a link with target="_self", the link targets frame 1 (i.e. the link targets the frame containing the link (i.e. targets itself))
  • If frame 1 has a link with target="_parent", the link targets frame 2 (i.e. the link targets the parent frame)
  • If frame 1 has a link with target="_top", the link targets the initial webpage (i.e. the link targets the topmost/outermost frame; (in this case; the link skips past the grandparent frame 3))
    • If frame 2 has a link with target="_top", the link also targets the initial webpage (i.e. again, the link targets the topmost/outermost frame)
  • If any of these frames has a link with target="_blank", the link targets an auxiliary browsing context, aka a "new window"/"new tab"

Defining a HTML template to append using JQuery

Other alternative: Pure

I use it and it has helped me a lot. An example shown on their website:

HTML

<div class="who">
</div>

JSON

{
  "who": "Hello Wrrrld"
}

Result

<div class="who">
  Hello Wrrrld
</div>

How to use ClassLoader.getResources() correctly?

The Spring Framework has a class which allows to recursively search through the classpath:

PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
resolver.getResources("classpath*:some/package/name/**/*.xml");

How to use Collections.sort() in Java?

The answer given by NINCOMPOOP can be made simpler using Lambda Expressions:

Collections.sort(recipes, (Recipe r1, Recipe r2) ->
r1.getID().compareTo(r2.getID()));

Also introduced after Java 8 is the comparator construction methods in the Comparator interface. Using these, one can further reduce this to 1:

recipes.sort(comparingInt(Recipe::getId));

1 Bloch, J. Effective Java (3rd Edition). 2018. Item 42, p. 194.

What does mysql error 1025 (HY000): Error on rename of './foo' (errorno: 150) mean?

averageRatings= FOREACH groupedRatings GENERATE group AS movieID, AVG(ratings.rating) AS avgRating, COUNT(ratings.rating) AS numRatings;

If you are using any command like above you must use group in small letters. This may solve your problem it solved mine. At least in PIG script.

CSS3 transform: rotate; in IE9

I know this is old, but I was having this same issue, found this post, and while it didn't explain exactly what was wrong, it helped me to the right answer - so hopefully my answer helps someone else who might be having a similar problem to mine.

I had an element I wanted rotated vertical, so naturally I added the filter: for IE8 and then the -ms-transform property for IE9. What I found is that having the -ms-transform property AND the filter applied to the same element causes IE9 to render the element very poorly. My solution:

  1. If you are using the transform-origin property, add one for MS too (-ms-transform-origin: left bottom;). If you don't see your element, it could be that it's rotating on it's middle axis and thus leaving the page somehow - so double check that.

  2. Move the filter: property for IE7&8 to a separate style sheet and use an IE conditional to insert that style sheet for browsers less than IE9. This way it doesn't affect the IE9 styles and all should work fine.

  3. Make sure to use the correct DOCTYPE tag as well; if you have it wrong IE9 will not work properly.

Java: Most efficient method to iterate over all elements in a org.w3c.dom.Document?

Basically you have two ways to iterate over all elements:

1. Using recursion (the most common way I think):

public static void main(String[] args) throws SAXException, IOException,
        ParserConfigurationException, TransformerException {

    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
        .newInstance();
    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
    Document document = docBuilder.parse(new File("document.xml"));
    doSomething(document.getDocumentElement());
}

public static void doSomething(Node node) {
    // do something with the current node instead of System.out
    System.out.println(node.getNodeName());

    NodeList nodeList = node.getChildNodes();
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node currentNode = nodeList.item(i);
        if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
            //calls this method for all the children which is Element
            doSomething(currentNode);
        }
    }
}

2. Avoiding recursion using getElementsByTagName() method with * as parameter:

public static void main(String[] args) throws SAXException, IOException,
        ParserConfigurationException, TransformerException {

    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
            .newInstance();
    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
    Document document = docBuilder.parse(new File("document.xml"));

    NodeList nodeList = document.getElementsByTagName("*");
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node node = nodeList.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            // do something with the current element
            System.out.println(node.getNodeName());
        }
    }
}

I think these ways are both efficient.
Hope this helps.

Php header location redirect not working

Try adding

ob_start();

at the top of the code i.e. before the include statement.

how to parse xml to java object?

JAXB is a reliable choice as it does xml to java classes mapping smoothely. But there are other frameworks available, here is one such:

https://code.google.com/p/xmappr/

Count number of rows per group and add result to original data frame

One simple line in base R:

df$count = table(interaction(df[, (c("name", "type"))]))[interaction(df[, (c("name", "type"))])]

Same in two lines, for clarity/efficiency:

fact = interaction(df[, (c("name", "type"))])
df$count = table(fact)[fact]

Eliminating NAs from a ggplot

Not sure if you have solved the problem. For this issue, you can use the "filter" function in the dplyr package. The idea is to filter the observations/rows whose values of the variable of your interest is not NA. Next, you make the graph with these filtered observations. You can find my codes below, and note that all the name of the data frame and variable is copied from the prompt of your question. Also, I assume you know the pipe operators.

library(tidyverse) 

MyDate %>%
   filter(!is.na(the_variable)) %>%
     ggplot(aes(x= the_variable, fill=the_variable)) + 
        geom_bar(stat="bin") 

You should be able to remove the annoying NAs on your plot. Hope this works :)

How to format a DateTime in PowerShell

The question is answered, but there is some more information missing:

Variable vs. Cmdlet

You have a value in the $Date variable and the -f operator does work in this form: 'format string' -f values. If you call Get-Date -format "yyyyMMdd" you call a cmdlet with some parameters. The value "yyyyMMdd" is the value for parameter Format (try help Get-Date -param Format).

-f operator

There are plenty of format strings. Look at least at part1 and part2. She uses string.Format('format string', values'). Think of it as 'format-string' -f values, because the -f operator works very similarly as string.Format method (although there are some differences (for more information look at question at Stack Overflow: How exactly does the RHS of PowerShell's -f operator work?).

Python Tkinter clearing a frame

pack_forget and grid_forget will only remove widgets from view, it doesn't destroy them. If you don't plan on re-using the widgets, your only real choice is to destroy them with the destroy method.

To do that you have two choices: destroy each one individually, or destroy the frame which will cause all of its children to be destroyed. The latter is generally the easiest and most effective.

Since you claim you don't want to destroy the container frame, create a secondary frame. Have this secondary frame be the container for all the widgets you want to delete, and then put this one frame inside the parent you do not want to destroy. Then, it's just a matter of destroying this one frame and all of the interior widgets will be destroyed along with it.

Parsing JSON using C

Json isn't a huge language to start with, so libraries for it are likely to be small(er than Xml libraries, at least).

There are a whole ton of C libraries linked at Json.org. Maybe one of them will work well for you.

Extract substring in Bash

There's also the bash builtin 'expr' command:

INPUT="someletters_12345_moreleters.ext"  
SUBSTRING=`expr match "$INPUT" '.*_\([[:digit:]]*\)_.*' `  
echo $SUBSTRING

How to detect when facebook's FB.init is complete

Update on Jan 04, 2012

It seems like you can't just call FB-dependent methods (for example FB.getAuthResponse()) right after FB.init() like before, as FB.init() seems to be asynchronous now. Wrapping your code into FB.getLoginStatus() response seems to do the trick of detecting when API is fully ready:

window.fbAsyncInit = function() {
    FB.init({
        //...
    });

    FB.getLoginStatus(function(response){
        runFbInitCriticalCode(); 
    });

};  

or if using fbEnsureInit() implementation from below:

window.fbAsyncInit = function() {
    FB.init({
        //...
    });

    FB.getLoginStatus(function(response){
        fbApiInit = true;
    });

};  

Original Post:

If you want to just run some script when FB is initialized you can put some callback function inside fbAsyncInit:

  window.fbAsyncInit = function() {
    FB.init({
      appId  : '<?php echo $conf['fb']['appid']; ?>',
      status : true, // check login status
      cookie : true, // enable cookies to allow the server to access the session
      xfbml  : true  // parse XFBML
    });
    FB.Canvas.setAutoResize();

    runFbInitCriticalCode(); //function that contains FB init critical code
  };

If you want exact replacement of FB.ensureInit then you would have to write something on your own as there is no official replacement (big mistake imo). Here is what I use:

  window.fbAsyncInit = function() {
    FB.init({
      appId  : '<?php echo $conf['fb']['appid']; ?>',
      status : true, // check login status
      cookie : true, // enable cookies to allow the server to access the session
      xfbml  : true  // parse XFBML
    });
    FB.Canvas.setAutoResize();

    fbApiInit = true; //init flag
  };

  function fbEnsureInit(callback) {
        if(!window.fbApiInit) {
            setTimeout(function() {fbEnsureInit(callback);}, 50);
        } else {
            if(callback) {
                callback();
            }
        }
    }

Usage:

fbEnsureInit(function() {
    console.log("this will be run once FB is initialized");
});

Github "Updates were rejected because the remote contains work that you do not have locally."

The error possibly comes because of the different structure of the code that you are committing and that present on GitHub. It creates conflicts which can be solved by

git pull

Merge conflicts resolving:

git push

If you confirm that your new code is all fine you can use:

git push -f origin master

Where -f stands for "force commit".

Check if decimal value is null

If you're pulling this value directly from a SQL Database and the value is null in there, it will actually be the DBNull object rather than null. Either place a check prior to your conversion & use a default value in the event of DBNull, or replace your null check afterwards with a check on rdrSelect[23] for DBNull.

Cannot catch toolbar home button click event

    mActionBarDrawerToggle = mNavigationDrawerFragment.getActionBarDrawerToggle();
    mActionBarDrawerToggle.setToolbarNavigationClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // event when click home button
        }
    });

in mycase this code work perfect

Getting cursor position in Python

I found a way to do it that doesn't depend on non-standard libraries!

Found this in Tkinter

self.winfo_pointerxy()

Twitter bootstrap modal-backdrop doesn't disappear

the initial value of your data-backdrop attribute can be

"static","true", "false" .

static and true add the modal shadow, while false disable the shadow, so you just need to change this value with the first click to false . like this:

_x000D_
_x000D_
$(document).on('ready',function(){_x000D_
 _x000D_
 var count=0;_x000D_
 _x000D_
$('#id-which-triggers-modal').on('click',function(){_x000D_
  _x000D_
  if(count>0){_x000D_
  _x000D_
   $(this).attr('data-backdrop','false')_x000D_
  }_x000D_
  count++;_x000D_
});_x000D_
_x000D_
_x000D_
});
_x000D_
_x000D_
_x000D_

jQuery ajax upload file in asp.net mvc

Upload files using AJAX in ASP.Net MVC

Things have changed since HTML5

JavaScript

document.getElementById('uploader').onsubmit = function () {
    var formdata = new FormData(); //FormData object
    var fileInput = document.getElementById('fileInput');
    //Iterating through each files selected in fileInput
    for (i = 0; i < fileInput.files.length; i++) {
        //Appending each file to FormData object
        formdata.append(fileInput.files[i].name, fileInput.files[i]);
    }
    //Creating an XMLHttpRequest and sending
    var xhr = new XMLHttpRequest();
    xhr.open('POST', '/Home/Upload');
    xhr.send(formdata);
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
            alert(xhr.responseText);
        }
    }
    return false;
}   

Controller

public JsonResult Upload()
{
    for (int i = 0; i < Request.Files.Count; i++)
    {
        HttpPostedFileBase file = Request.Files[i]; //Uploaded file
        //Use the following properties to get file's name, size and MIMEType
        int fileSize = file.ContentLength;
        string fileName = file.FileName;
        string mimeType = file.ContentType;
        System.IO.Stream fileContent = file.InputStream;
        //To save file, use SaveAs method
        file.SaveAs(Server.MapPath("~/")+ fileName ); //File will be saved in application root
    }
    return Json("Uploaded " + Request.Files.Count + " files");
}

EDIT : The HTML

<form id="uploader">
    <input id="fileInput" type="file" multiple>
    <input type="submit" value="Upload file" />
</form>

Close window automatically after printing dialog closes

try this:

var xxx = window.open("","Printing...");
xxx.onload = function () {
     setTimeout(function(){xxx.print();}, 500);
     xxx.onfocus = function () {
        xxx.close();
     }  
}

Open files always in a new tab

Essentially, there are three settings that one has to update (Preference >> settings):

  • workbench.editor.enablePreview: set this to globally enable or disable preview editors

  • workbench.editor.enablePreviewFromQuickOpen: set this to enable or disable preview editors when opened from Quick Open

  • workbench.editor.showTabs: finally one will need to set this
    otherwise, there will be no tabs displayed and you will just be
    wondering why setting/unsetting the above two did not work

Counting the number of elements in array

This expands on the answer by Denis Bubnov.

I used this to find child values of array elements—namely if there was a anchor field in paragraphs on a Drupal 8 site to build a table of contents.

{% set count = 0 %}
{% for anchor in items %}
    {% if anchor.content['#paragraph'].field_anchor_link.0.value %}
        {% set count = count + 1 %}
    {% endif %}
{% endfor %}

{% if count > 0 %}
 ---  build the toc here --
{% endif %}

Convert a Unix timestamp to time in JavaScript

I'm partial to Jacob Wright's Date.format() library, which implements JavaScript date formatting in the style of PHP's date() function.

new Date(unix_timestamp * 1000).format('h:i:s')

Convert String array to ArrayList

Using Collections#addAll()

String[] words = {"ace","boom","crew","dog","eon"};
List<String> arrayList = new ArrayList<>(); 
Collections.addAll(arrayList, words); 

Find (and kill) process locking port 3000 on Mac

Find the open connection

lsof -i -P | grep -i "listen"

Kill by process ID

kill -9 'PID'

sudo echo "something" >> /etc/privilegedFile doesn't work

Use tee --append or tee -a.

echo 'deb blah ... blah' | sudo tee -a /etc/apt/sources.list

Make sure to avoid quotes inside quotes.

To avoid printing data back to the console, redirect the output to /dev/null.

echo 'deb blah ... blah' | sudo tee -a /etc/apt/sources.list > /dev/null

Remember about the (-a/--append) flag! Just tee works like > and will overwrite your file. tee -a works like >> and will write at the end of the file.

Execute command without keeping it in history

This command might come in handy. This will not record the command that is executed

history -d $((HISTCMD-1)) && <Your Command Here>

Position DIV relative to another DIV?

You want to use position: absolute while inside the other div.

DEMO

Angular 4 - Observable catch error

If you want to use the catch() of the Observable you need to use Observable.throw() method before delegating the error response to a method

_x000D_
_x000D_
import { Injectable } from '@angular/core';_x000D_
import { Headers, Http, ResponseOptions} from '@angular/http';_x000D_
import { AuthHttp } from 'angular2-jwt';_x000D_
_x000D_
import { MEAT_API } from '../app.api';_x000D_
_x000D_
import { Observable } from 'rxjs/Observable';_x000D_
import 'rxjs/add/operator/map';_x000D_
import 'rxjs/add/operator/catch';_x000D_
_x000D_
@Injectable()_x000D_
export class CompareNfeService {_x000D_
_x000D_
_x000D_
  constructor(private http: AuthHttp) {}_x000D_
_x000D_
  envirArquivos(order): Observable < any > {_x000D_
    const headers = new Headers();_x000D_
    return this.http.post(`${MEAT_API}compare/arquivo`, order,_x000D_
        new ResponseOptions({_x000D_
          headers: headers_x000D_
        }))_x000D_
      .map(response => response.json())_x000D_
      .catch((e: any) => Observable.throw(this.errorHandler(e)));_x000D_
  }_x000D_
_x000D_
  errorHandler(error: any): void {_x000D_
    console.log(error)_x000D_
  }_x000D_
}
_x000D_
_x000D_
_x000D_

Using Observable.throw() worked for me

R data formats: RData, Rda, Rds etc

In addition to @KenM's answer, another important distinction is that, when loading in a saved object, you can assign the contents of an Rds file. Not so for Rda

> x <- 1:5
> save(x, file="x.Rda")
> saveRDS(x, file="x.Rds")
> rm(x)

## ASSIGN USING readRDS
> new_x1 <- readRDS("x.Rds")
> new_x1
[1] 1 2 3 4 5

## 'ASSIGN' USING load -- note the result
> new_x2 <- load("x.Rda")
loading in to  <environment: R_GlobalEnv> 
> new_x2
[1] "x"
# NOTE: `load()` simply returns the name of the objects loaded. Not the values. 
> x
[1] 1 2 3 4 5

How can I check MySQL engine type for a specific table?

Yet another way, perhaps the shortest to get status of a single or matched set of tables:

SHOW TABLE STATUS LIKE 'table';

You can then use LIKE operators for example:

SHOW TABLE STATUS LIKE 'field_data_%';

Why I am getting Cannot pass parameter 2 by reference error when I am using bindParam with a constant value?

If you want to insert NULL only when the value is empty or '', but insert the value when it is available.

A) Receives the form data using POST method, and calls function insert with those values.

insert( $_POST['productId'], // Will be set to NULL if empty    
        $_POST['productName'] ); // Will be to NULL if empty                                

B) Evaluates if a field was not filled up by the user, and inserts NULL if that's the case.

public function insert( $productId, $productName )
{ 
    $sql = "INSERT INTO products (  productId, productName ) 
                VALUES ( :productId, :productName )";

    //IMPORTANT: Repace $db with your PDO instance
    $query = $db->prepare($sql); 

    //Works with INT, FLOAT, ETC.
    $query->bindValue(':productId',  !empty($productId)   ? $productId   : NULL, PDO::PARAM_INT); 

    //Works with strings.
    $query->bindValue(':productName',!empty($productName) ? $productName : NULL, PDO::PARAM_STR);   

    $query->execute();      
}

For instance, if the user doesn't input anything on the productName field of the form, then $productName will be SET but EMPTY. So, you need check if it is empty(), and if it is, then insert NULL.

Tested on PHP 5.5.17

Good luck,

How to make python Requests work via socks proxy

In case someone has tried all of these older answers, and is still running into problems like:

requests.exceptions.ConnectionError: 
   SOCKSHTTPConnectionPool(host='myhost', port=80): 
   Max retries exceeded with url: /my/path 
   (Caused by NewConnectionError('<requests.packages.urllib3.contrib.socks.SOCKSConnection object at 0x106812bd0>: 
   Failed to establish a new connection: 
   [Errno 8] nodename nor servname provided, or not known',))

It may be because, by default, requests is configured to resolve DNS queries on the local side of the connection.

Try changing your proxy URL from socks5://proxyhost:1234 to socks5h://proxyhost:1234. Note the extra h (it stands for hostname resolution).

The PySocks package module default is to do remote resolution, and I'm not sure why requests made their integration this obscurely divergent, but here we are.

TCPDF output without saving file

I've been using the Output("doc.pdf", "I"); and it doesn't work, I'm always asked for saving the file.

I took a look in documentation and found that

I send the file inline to the browser (default). The plug-in is used if available. The name given by name is used when one selects the "Save as" option on the link generating the PDF. http://www.tcpdf.org/doc/classTCPDF.html#a3d6dcb62298ec9d42e9125ee2f5b23a1

Then I think you have to use a plugin to print it, otherwise it is going to be downloaded.

Updating Python on Mac

Easiest way is

 brew update && brew upgrade python

"relocation R_X86_64_32S against " linking Error

Relocation R_X86_64_PC32 against undefined symbol , usually happens when LDFLAGS are set with hardening and CFLAGS not .
Maybe just user error:
If you are using -specs=/usr/lib/rpm/redhat/redhat-hardened-ld at link time, you also need to use -specs=/usr/lib/rpm/redhat/redhat-hardened-cc1 at compile time, and as you are compiling and linking at the same time, you need either both, or drop the -specs=/usr/lib/rpm/redhat/redhat-hardened-ld . Common fixes :
https://bugzilla.redhat.com/show_bug.cgi?id=1304277#c3
https://github.com/rpmfusion/lxdream/blob/master/lxdream-0.9.1-implicit.patch

Angular JS update input field after change

I'm guessing that when you enter a value into the totals field that value expression somehow gets overwritten.

However, you can take an alternative approach: Create a field for the total value and when either one or two changes update that field.

<li>Total <input type="text" ng-model="total">{{total}}</li>

And change the javascript:

function TodoCtrl($scope) {
    $scope.$watch('one * two', function (value) {
        $scope.total = value;
    });
}

Example fiddle here.

How to get access to HTTP header information in Spring MVC REST controller?

You can use HttpEntity to read both Body and Headers.

   @RequestMapping(value = "/restURL")
   public String serveRest(HttpEntity<String> httpEntity){
                MultiValueMap<String, String> headers = 
                httpEntity.getHeaders();
                Iterator<Map.Entry<String, List<String>>> s = 
                headers.entrySet().iterator();
                while(s.hasNext()) {
                    Map.Entry<String, List<String>> obj = s.next();
                    String key = obj.getKey();
                    List<String> value = obj.getValue();
                }
                
                String body = httpEntity.getBody();

    }

Delete dynamically-generated table row using jQuery

A simple solution is encapsulate code of button event in a function, and call it when you add TRs too:

 var i = 1;
$("#addbutton").click(function() {
  $("table tr:first").clone().find("input").each(function() {
    $(this).val('').attr({
      'id': function(_, id) {return id + i },
      'name': function(_, name) { return name + i },
      'value': ''               
    });
  }).end().appendTo("table");
  i++;

  applyRemoveEvent();  
});


function applyRemoveEvent(){
    $('button.removebutton').on('click',function() {
        alert("aa");
      $(this).closest( 'tr').remove();
      return false;
    });
};

applyRemoveEvent();

http://jsfiddle.net/Z7fG7/2/

How to run a specific Android app using Terminal?

I keep this build-and-run script handy, whenever I am working from command line:

#!/usr/bin/env bash

PACKAGE=com.example.demo
ACTIVITY=.MainActivity
APK_LOCATION=app/build/outputs/apk/app-debug.apk
echo "Package: $PACKAGE"

echo "Building the project with tasks: $TASKS"
./gradlew $TASKS

echo "Uninstalling $PACKAGE"
adb uninstall $PACKAGE

echo "Installing $APK_LOCATION"
adb install $APK_LOCATION

echo "Starting $ACTIVITY"
adb shell am start -n $PACKAGE/$ACTIVITY

file_get_contents() Breaks Up UTF-8 Characters

I had similar problem with polish language

I tried:

$fileEndEnd = mb_convert_encoding($fileEndEnd, 'UTF-8', mb_detect_encoding($fileEndEnd, 'UTF-8', true));

I tried:

$fileEndEnd = utf8_encode ( $fileEndEnd );

I tried:

$fileEndEnd = iconv( "UTF-8", "UTF-8", $fileEndEnd );

And then -

$fileEndEnd = mb_convert_encoding($fileEndEnd, 'HTML-ENTITIES', "UTF-8");

This last worked perfectly !!!!!!

Left-pad printf with spaces

If you want the word "Hello" to print in a column that's 40 characters wide, with spaces padding the left, use the following.

char *ptr = "Hello";
printf("%40s\n", ptr);

That will give you 35 spaces, then the word "Hello". This is how you format stuff when you know how wide you want the column, but the data changes (well, it's one way you can do it).

If you know you want exactly 40 spaces then some text, just save the 40 spaces in a constant and print them. If you need to print multiple lines, either use multiple printf statements like the one above, or do it in a loop, changing the value of ptr each time.

Generate a Hash from string in Javascript

Slightly simplified version of @esmiralha's answer.

I don't override String in this version, since that could result in some undesired behaviour.

function hashCode(str) {
    var hash = 0;
    for (var i = 0; i < str.length; i++) {
        hash = ~~(((hash << 5) - hash) + str.charCodeAt(i));
    }
    return hash;
}

Simulate string split function in Excel formula

AFAIK the best you can do to emulate Split() is to use FILTERXML which is available from Excel 2013 onwards (not Excel Online or Mac).

The syntax more or less always is:

=FILTERXML("<t><s>"&SUBSTITUTE(A1,"|","</s><s>")&"</s></t>","//s")

This would return an array to be used in other functions and would even hold up if no delimiter is found. If you want to read more about it, maybe you are interested in this post.

document.getElementById vs jQuery $()

var contents = document.getElementById('contents');

var contents = $('#contents');

The code snippets are not the same. first one returns a Element object (source). The second one, jQuery equivalent will return a jQuery object containing a collection of either zero or one DOM element. (jQuery documentation). Internally jQuery uses document.getElementById() for efficiency.

In both the cases if more than one element found only the first element will be returned.


When checking the github project for jQuery I found following line snippets which seems to be using document.getElementById codes (https://github.com/jquery/jquery/blob/master/src/core/init.js line 68 onwards)

// HANDLE: $(#id)
} else {
    elem = document.getElementById( match[2] );

The server response was: 5.7.0 Must issue a STARTTLS command first. i16sm1806350pag.18 - gsmtp

I also got the same error using the code:

MailMessage mail = new MailMessage(); 
mail.To.Add(txtEmail.Text.Trim()); 
mail.To.Add("[email protected]");
mail.From = new MailAddress("[email protected]");
mail.Subject = "Confirmation of Registration on Job Junction.";
string Body = "Hi, this mail is to test sending mail using Gmail in ASP.NET";
mail.Body = Body;
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
// smtp.Host = "smtp.gmail.com"; //Or Your SMTP Server Address
smtp.Credentials = new System.Net.NetworkCredential("[email protected]", "password");
// smtp.Port = 587;
//Or your Smtp Email ID and Password
smtp.UseDefaultCredentials = false;
// smtp.EnableSsl = true;
smtp.Send(mail);

But moving 2 lines upward fixed the problem:

MailMessage mail = new MailMessage(); 
mail.To.Add(txtEmail.Text.Trim()); 
mail.To.Add("[email protected]");
mail.From = new MailAddress("[email protected]");
mail.Subject = "Confirmation of Registration on Job Junction.";
string Body = "Hi, this mail is to test sending mail using Gmail in ASP.NET";
mail.Body = Body;
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
// smtp.Host = "smtp.gmail.com"; //Or Your SMTP Server Address
smtp.UseDefaultCredentials = false;
smtp.EnableSsl = true;
smtp.Credentials = new System.Net.NetworkCredential("[email protected]", "password");
// smtp.Port = 587;
//Or your Smtp Email ID and Password
smtp.Send(mail);

Change select box option background color

If you really want to style the within a , consider switching to a Javascript/CSS based drop down such as http://getbootstrap.com/2.3.2/components.html#dropdowns or https://silviomoreto.github.io/bootstrap-select/examples/. This because browsers such as IE do not allow styling of options within elements. Chrome/OSX also has this problem - you cannot style options.

However a warning is attached to that approach. These types of menus work very differently on mobile platforms because native elements aren't used. They can have annoying quirks on desktop as well. My advice is 1) don't write your own and 2) find a library that's been really well tested.

'uint32_t' does not name a type

You need to include iostream

#include <iostream>
using namespace std;

Get current directory name (without full path) in a Bash script

Below grep with regex is also working,

>pwd | grep -o "\w*-*$"

NodeJS/express: Cache and 304 status code

I had the same problem in Safari and Chrome (the only ones I've tested) but I just did something that seems to work, at least I haven't been able to reproduce the problem since I added the solution. What I did was add a metatag to the header with a generated timstamp. Doesn't seem right but it's simple :)

<meta name="304workaround" content="2013-10-24 21:17:23">

Update P.S As far as I can tell, the problem disappears when I remove my node proxy (by proxy i mean both express.vhost and http-proxy module), which is weird...

What is Robocopy's "restartable" option?

Restartable mode (/Z) has to do with a partially-copied file. With this option, should the copy be interrupted while any particular file is partially copied, the next execution of robocopy can pick up where it left off rather than re-copying the entire file.

That option could be useful when copying very large files over a potentially unstable connection.

Backup mode (/B) has to do with how robocopy reads files from the source system. It allows the copying of files on which you might otherwise get an access denied error on either the file itself or while trying to copy the file's attributes/permissions. You do need to be running in an Administrator context or otherwise have backup rights to use this flag.

Git says remote ref does not exist when I delete remote branch

There's a shortcut to delete the branch in the origin:

git push origin :<branch_name>

Which is the same as doing git push origin --delete <branch_name>

Asp.net 4.0 has not been registered

Open:

Start Menu
-> Programs
-> Microsoft Visual Studio 2010
-> Visual Studio Tools
-> Visual Studio Command Prompt (2010)

Run in command prompt:

aspnet_regiis -i

Make sure it is run at administrator, check that the title starts with Administrator:

enter image description here

How should I copy Strings in Java?

Strings are immutable objects so you can copy them just coping the reference to them, because the object referenced can't change ...

So you can copy as in your first example without any problem :

String s = "hello";
String backup_of_s = s;
s = "bye";

Indirectly referenced from required .class file

Have you Googled for "weblogic ExpressionMap"? Do you know what it is and what it does?

Looks like you definitely need to be compiling alongside Weblogic and with Weblogic's jars included in your Eclipse classpath, if you're not already.

If you're not already working with Weblogic, then you need to find out what in the world is referencing it. You might need to do some heavy-duty grepping on your jars, classfiles, and/or source files looking for which ones include the string "weblogic".

If I had to include something that was relying on this Weblogic class, but couldn't use Weblogic, I'd be tempted to try to reverse-engineer a compatible class. Create your own weblogic.utils.expressions.ExpressionMap class; see if everything compiles; use any resultant errors or warnings at compile-time or runtime to give you clues as to what methods and other members need to be in this class. Make stub methods that do nothing or return null if possible.

Android SeekBar setOnSeekBarChangeListener

I hope this will help you:

final TextView t1=new TextView(this); 
t1.setText("Hello Android");        
final SeekBar sk=(SeekBar) findViewById(R.id.seekBar1);     
sk.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {       

    @Override       
    public void onStopTrackingTouch(SeekBar seekBar) {      
        // TODO Auto-generated method stub      
    }       

    @Override       
    public void onStartTrackingTouch(SeekBar seekBar) {     
        // TODO Auto-generated method stub      
    }       

    @Override       
    public void onProgressChanged(SeekBar seekBar, int progress,boolean fromUser) {     
        // TODO Auto-generated method stub      

        t1.setTextSize(progress);
        Toast.makeText(getApplicationContext(), String.valueOf(progress),Toast.LENGTH_LONG).show();

    }       
});             

Unable to add window -- token android.os.BinderProxy is not valid; is your activity running?

  • In my case the issue is occurred because of am trying to open/show dialog box in onPostExecute AsyncTask

  • However its an wrong method of showing dialog or Ui changes in onPostExecute.

  • For that, we need to check the activity is in active Eg : !isFinishing() , if the activity is not finished then only able to show our dialog box or ui change.

    @Override
    protected void onPostExecute(String response_str) {
    
       getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (!((Activity) mContext).isFinishing()) {
                            try {
                                ShowAgilDialog();
                            } catch (WindowManager.BadTokenException e) {
                                Log.e("WindowManagerBad ", e.toString());
                            }
                        }
                    }
                });
    }
    

Fatal error: Call to undefined function mb_strlen()

In case Google search for this error

Call to undefined function mb_ereg_match()

takes somebody to this thread. Installing php-mbstring resolves it too.

Ubuntu 18.04.1, PHP 7.2.10

sudo apt-get install php7.2-mbstring

Latex - Change margins of only a few pages

I had the same problem in a beamer presentation. For me worked using the columns environment:

\begin{frame}
  \begin{columns}
    \column{1.2\textwidth}
    \begin{figure}
      \subfigure{\includegraphics[width=.49\textwidth]{1.png}}
      \subfigure{\includegraphics[width=.49\textwidth]{2.png}}
    \end{figure}
   \end{columns}
\end{frame}

VBA - Run Time Error 1004 'Application Defined or Object Defined Error'

Your cells object is not fully qualified. You need to add a DOT before the cells object. For example

With Worksheets("Cable Cards")
    .Range(.Cells(RangeStartRow, RangeStartColumn), _
           .Cells(RangeEndRow, RangeEndColumn)).PasteSpecial xlValues

Similarly, fully qualify all your Cells object.

javascript regular expression to not match a word

function doesNotContainAbcOrDef(x) {
    return (x.match('abc') || x.match('def')) === null;
}

no target device found android studio 2.1.1

If you are using 32-bit ubuntu (my case) then it is most likely that Android Studio has downloaded 64-bit version of adb and fastboot inside your sdk/platform-tools folder. I think you already have installed adb (and fastboot). If you haven't then run these commands in terminal:

sudo add-apt-repository ppa:nilarimogard/webupd8
sudo apt-get update
sudo apt-get install android-tools-adb android-tools-fastboot

This will install 32-bit version of adb and fastboot. Now just replace the 64-bit adb and fastboot executable files in sdk/platform-tools with the installed 32-bit versions:

cp /usr/bin/adb <path-to-your-adt-sdk-package>/sdk/platform-tools/adb
cp /usr/bin/fastboot <path-to-your-adt-sdk-package>/sdk/platformtools/fastboot

Now your android studio should be able to run your App in your device.

"webxml attribute is required" error in Maven

If you change the default project path, you must specify the location of the web.xml file, for example:

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <version>2.5</version>
            <configuration>
                <webXml>src\main\web\WEB-INF\web.xml</webXml>
            </configuration>
        </plugin>

R: Comment out block of code

I use RStudio or Emacs and always use the editor shortcuts available to comment regions. If this is not a possibility then you could use Paul's answer but this only works if your code is syntactically correct.

Here is another dirty way I came up with, wrap it in scan() and remove the result. It does store the comment in memory for a short while so it will probably not work with very large comments. Best still is to just put # signs in front of every line (possibly with editor shortcuts).

foo <- scan(what="character")
These are comments
These are still comments
Can also be code:
x <- 1:10
One line must be blank

rm(foo)

How to flush output of print function?

Dan's idea doesn't quite work:

#!/usr/bin/env python
class flushfile(file):
    def __init__(self, f):
        self.f = f
    def write(self, x):
        self.f.write(x)
        self.f.flush()

import sys
sys.stdout = flushfile(sys.stdout)

print "foo"

The result:

Traceback (most recent call last):
  File "./passpersist.py", line 12, in <module>
    print "foo"
ValueError: I/O operation on closed file

I believe the problem is that it inherits from the file class, which actually isn't necessary. According to the docs for sys.stdout:

stdout and stderr needn’t be built-in file objects: any object is acceptable as long as it has a write() method that takes a string argument.

so changing

class flushfile(file):

to

class flushfile(object):

makes it work just fine.

error C2065: 'cout' : undeclared identifier

Try it, it will work. I checked it in Windows XP, Visual Studio 2010 Express.

#include "stdafx.h"
#include <iostream>
using namespace std;

void main( ) 
{
   int i = 0;
   cout << "Enter a number: ";
   cin >> i;
}

Best way to determine user's locale within browser

This article suggests the following properties of the browser's navigator object:

  • navigator.language (Netscape - Browser Localization)
  • navigator.browserLanguage (IE-Specific - Browser Localized Language)
  • navigator.systemLanguage (IE-Specific - Windows OS - Localized Language)
  • navigator.userLanguage

Roll these into a javascript function and you should be able to guess the right language, in most circumstances. Be sure to degrade gracefully, so have a div containing your language choice links, so that if there is no javascript or the method doesn't work, the user can still decide. If it does work, just hide the div.

The only problem with doing this on the client side is that either you serve up all the languages to the client, or you have to wait until the script has run and detected the language before requesting the right version. Perhaps serving up the most popular language version as a default would irritate the fewest people.

Edit: I'd second Ivan's cookie suggestion, but make sure the user can always change the language later; not everyone prefers the language their browser defaults to.

Listing contents of a bucket with boto3

It can also be done as follows:

csv_files = s3.list_objects_v2(s3_bucket_path)
    for obj in csv_files['Contents']:
        key = obj['Key']

curl: (6) Could not resolve host: google.com; Name or service not known

I have today similar problem. But weirder.

  • host - works host pl.archive.ubuntu.com
  • dig - works on default and on all other DNS's dig pl.archive.ubuntu.com, dig @127.0.1.1 pl.archive.ubuntu.com
  • curl - doesn't work! but for some addresses it does. WEIRD! Same in Ruby, APT and many more.
$ curl -v http://google.com/
*   Trying 172.217.18.78...
* Connected to google.com (172.217.18.78) port 80 (#0)
> GET / HTTP/1.1
> Host: google.com
> User-Agent: curl/7.47.0
> Accept: */*
>
< HTTP/1.1 302 Found
< Cache-Control: private
< Content-Type: text/html; charset=UTF-8
< Referrer-Policy: no-referrer
< Location: http://www.google.pl/?gfe_rd=cr&ei=pt9UWfqXL4uBX_W5n8gB
< Content-Length: 256
< Date: Thu, 29 Jun 2017 11:08:22 GMT
<
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>302 Moved</TITLE></HEAD><BODY>
<H1>302 Moved</H1>
The document has moved
<A HREF="http://www.google.pl/?gfe_rd=cr&ei=pt9UWfqXL4uBX_W5n8gB">here</A>.
</BODY></HTML>
* Connection #0 to host google.com left intact

$ curl -v http://pl.archive.ubuntu.com/
* Could not resolve host: pl.archive.ubuntu.com
* Closing connection 0
curl: (6) Could not resolve host: pl.archive.ubuntu.com

Revelation

Eventually I used strace on curl and found that it was connection to nscd deamon.

connect(4, {sa_family=AF_LOCAL, sun_path="/var/run/nscd/socket"}, 110) = 0

Solution

I've restarted the nscd service (Name Service Cache Daemon) and it helped to solve this issue!

systemctl restart nscd.service

How to disable manual input for JQuery UI Datepicker field?

When you make the input, set it to be readonly.

<input type="text" name="datepicker" id="datepicker" readonly="readonly" />

How do I get interactive plots again in Spyder/IPython/matplotlib?

This is actually pretty easy to fix and doesn't take any coding:

1.Click on the Plots tab above the console. 2.Then at the top right corner of the plots screen click on the options button. 3.Lastly uncheck the "Mute inline plotting" button

Now re-run your script and your graphs should show up in the console.

Cheers.

Add a custom attribute to a Laravel / Eloquent model on load?

Step 1: Define attributes in $appends
Step 2: Define accessor for that attributes.
Example:

<?php
...

class Movie extends Model{

    protected $appends = ['cover'];

    //define accessor
    public function getCoverAttribute()
    {
        return json_decode($this->InJson)->cover;
    }

How do I fix the npm UNMET PEER DEPENDENCY warning?

In my case all the dependencies were already there. Please update NPM in that case as it might have been crashed. It solved my problem.

npm install -g npm

Why would someone use WHERE 1=1 AND <conditions> in a SQL clause?

Making "where 1=1" the standard for all your queries also makes it trivially easy to validate the sql by replacing it with where 1 = 0, handy when you have batches of commands/files.

Also makes it trivially easy to find the end of the end of the from/join section of any query. Even queries with sub-queries if properly indented.

how to specify local modules as npm package dependencies

If it's acceptible to simply publish your modules preinstalled in node_modules alongside your other files, you can do it like this:

// ./node_modules/foo/package.json
{ 
  "name":"foo",
  "version":"0.0.1",
  "main":"index.js"
}

// ./package.json
...
"dependencies": {
  "foo":"0.0.1",
  "bar":"*"
}

// ./app.js
var foo = require('foo');

You may also want to store your module on git and tell your parent package.json to install the dependency from git: https://npmjs.org/doc/json.html#Git-URLs-as-Dependencies

How to change owner of PostgreSql database?

Frank Heikens answer will only update database ownership. Often, you also want to update ownership of contained objects (including tables). Starting with Postgres 8.2, REASSIGN OWNED is available to simplify this task.

IMPORTANT EDIT!

Never use REASSIGN OWNED when the original role is postgres, this could damage your entire DB instance. The command will update all objects with a new owner, including system resources (postgres0, postgres1, etc.)


First, connect to admin database and update DB ownership:

psql
postgres=# REASSIGN OWNED BY old_name TO new_name;

This is a global equivalent of ALTER DATABASE command provided in Frank's answer, but instead of updating a particular DB, it change ownership of all DBs owned by 'old_name'.

The next step is to update tables ownership for each database:

psql old_name_db
old_name_db=# REASSIGN OWNED BY old_name TO new_name;

This must be performed on each DB owned by 'old_name'. The command will update ownership of all tables in the DB.

Fixing slow initial load for IIS

See this article for tips on how to help performance issues. This includes both performance issues related to starting up, under the "cold start" section. Most of this will matter no matter what type of server you are using, locally or in production.

https://blogs.msdn.microsoft.com/b/mcsuksoldev/2011/01/19/common-performance-issues-on-asp-net-web-sites/

If the application deserializes anything from XML (and that includes web services…) make sure SGEN is run against all binaries involved in deseriaization and place the resulting DLLs in the Global Assembly Cache (GAC). This precompiles all the serialization objects used by the assemblies SGEN was run against and caches them in the resulting DLL. This can give huge time savings on the first deserialization (loading) of config files from disk and initial calls to web services. http://msdn.microsoft.com/en-us/library/bk3w6240(VS.80).aspx

If any IIS servers do not have outgoing access to the internet, turn off Certificate Revocation List (CRL) checking for Authenticode binaries by adding generatePublisherEvidence=”false” into machine.config. Otherwise every worker processes can hang for over 20 seconds during start-up while it times out trying to connect to the internet to obtain a CRL list. http://blogs.msdn.com/amolravande/archive/2008/07/20/startup-performance-disable-the-generatepublisherevidence-property.aspx

http://msdn.microsoft.com/en-us/library/bb629393.aspx

Consider using NGEN on all assemblies. However without careful use this doesn’t give much of a performance gain. This is because the base load addresses of all the binaries that are loaded by each process must be carefully set at build time to not overlap. If the binaries have to be rebased when they are loaded because of address clashes, almost all the performance gains of using NGEN will be lost. http://msdn.microsoft.com/en-us/magazine/cc163610.aspx

Java reflection: how to get field value from an object, not knowing its class

I strongly recommend using Java generics to specify what type of object is in that List, ie. List<Car>. If you have Cars and Trucks you can use a common superclass/interface like this List<Vehicle>.

However, you can use Spring's ReflectionUtils to make fields accessible, even if they are private like the below runnable example:

List<Object> list = new ArrayList<Object>();

list.add("some value");
list.add(3);

for(Object obj : list)
{
    Class<?> clazz = obj.getClass();

    Field field = org.springframework.util.ReflectionUtils.findField(clazz, "value");
    org.springframework.util.ReflectionUtils.makeAccessible(field);

    System.out.println("value=" + field.get(obj));
}

Running this has an output of:

value=[C@1b67f74
value=3

How to check if array is not empty?

len(self.table) checks for the length of the array, so you can use if-statements to find out if the length of the list is greater than 0 (not empty):

Python 2:

if len(self.table) > 0:
    #Do code here

Python 3:

if(len(self.table) > 0):
    #Do code here

It's also possible to use

if self.table:
    #Execute if self.table is not empty
else:
    #Execute if self.table is empty

to see if the list is not empty.

Understanding React-Redux and mapStateToProps()

It's a simple concept. Redux creates a ubiquitous state object (a store) from the actions in the reducers. Like a React component, this state doesn't have to be explicitly coded anywhere, but it helps developers to see a default state object in the reducer file to visualise what is happening. You import the reducer in the component to access the file. Then mapStateToProps selects only the key/value pairs in the store that its component needs. Think of it like Redux creating a global version of a React component's

this.state = ({ 
cats = [], 
dogs = []
})

It is impossible to change the structure of the state by using mapStateToProps(). What you are doing is choosing only the store's key/value pairs that the component needs and passing in the values (from a list of key/values in the store) to the props (local keys) in your component. You do this one value at a time in a list. No structure changes can occur in the process.

P.S. The store is local state. Reducers usually also pass state along to the database with Action Creators getting into the mix, but understand this simple concept first for this specific posting.

P.P.S. It is good practice to separate the reducers into separate files for each one and only import the reducer that the component needs.

c# razor url parameter from view

I've found the solution in this thread

@(ViewContext.RouteData.Values["parameterName"])

Open firewall port on CentOS 7

The answer by ganeshragav is correct, but it is also useful to know that you can use:

firewall-cmd --permanent --zone=public --add-port=2888/tcp 

but if is a known service, you can use:

firewall-cmd --permanent --zone=public --add-service=http 

and then reload the firewall

firewall-cmd --reload

[ Answer modified to reflect Martin Peter's comment, original answer had --permanent at end of command line ]

How do I truncate a .NET string?

I know there are a ton of answers already but my need was to keep the beginning and end of the string intact but shorten it to under the max length.

    public static string TruncateMiddle(string source)
    {
        if (String.IsNullOrWhiteSpace(source) || source.Length < 260) 
            return source;

        return string.Format("{0}...{1}", 
            source.Substring(0, 235),
            source.Substring(source.Length - 20));
    }

This is for creating SharePoint URLs that have a max length of 260 characters.

I didn't make length a parameter since it is a constant 260. I also didn't make the first substring length a parameter because I want it to break at a specific point. Finally, the second substring is the length of the source - 20 since I know the folder structure.

This could easily be adapted to your specific needs.

Failed binder transaction when putting an bitmap dynamically in a widget

You can compress the bitmap as an byte's array and then uncompress it in another activity, like this.

Compress!!

        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
        byte[] bytes = stream.toByteArray(); 
        setresult.putExtra("BMP",bytes);

Uncompress!!

        byte[] bytes = data.getByteArrayExtra("BMP");
        Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);

What are WSDL, SOAP and REST?

A WSDL is an XML document that describes a web service. It actually stands for Web Services Description Language.

SOAP is an XML-based protocol that lets you exchange info over a particular protocol (can be HTTP or SMTP, for example) between applications. It stands for Simple Object Access Protocol and uses XML for its messaging format to relay the information.

REST is an architectural style of networked systems and stands for Representational State Transfer. It's not a standard itself, but does use standards such as HTTP, URL, XML, etc.

Checking for the correct number of arguments

cat script.sh

    var1=$1
    var2=$2
    if [ "$#" -eq 2 ]
    then
            if [ -d $var1 ]
            then
            echo directory ${var1} exist
            else
            echo Directory ${var1} Does not exists
            fi
            if [ -d $var2 ]
            then
            echo directory ${var2} exist
            else
            echo Directory ${var2} Does not exists
            fi
    else
    echo "Arguments are not equals to 2"
    exit 1
    fi

execute it like below -

./script.sh directory1 directory2

Output will be like -

directory1 exit
directory2 Does not exists

What's the difference between utf8_general_ci and utf8_unicode_ci?

This post describes it very nicely.

In short: utf8_unicode_ci uses the Unicode Collation Algorithm as defined in the Unicode standards, whereas utf8_general_ci is a more simple sort order which results in "less accurate" sorting results.

jQuery ui datepicker with Angularjs

onSelect doesn't work well in ng-repeat, so I made another version using event bind

html

<tr ng-repeat="product in products">
<td>
    <input type="text" ng-model="product.startDate" class="form-control date-picker" data-date-format="yyyy-mm-dd" datepicker/>
</td>
</tr>

script

angular.module('app', []).directive('datepicker', function () {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, element, attrs, ngModelCtrl) {
            element.datepicker();
            element.bind('blur keyup change', function(){
                var model = attrs.ngModel;
                if (model.indexOf(".") > -1) scope[model.replace(/\.[^.]*/, "")][model.replace(/[^.]*\./, "")] = element.val();
                else scope[model] = element.val();
            });
        }
    };
});

How to force a component's re-rendering in Angular 2?

Rendering happens after change detection. To force change detection, so that component property values that have changed get propagated to the DOM (and then the browser will render those changes in the view), here are some options:

  • ApplicationRef.tick() - similar to Angular 1's $rootScope.$digest() -- i.e., check the full component tree
  • NgZone.run(callback) - similar to $rootScope.$apply(callback) -- i.e., evaluate the callback function inside the Angular 2 zone. I think, but I'm not sure, that this ends up checking the full component tree after executing the callback function.
  • ChangeDetectorRef.detectChanges() - similar to $scope.$digest() -- i.e., check only this component and its children

You will need to import and then inject ApplicationRef, NgZone, or ChangeDetectorRef into your component.

For your particular scenario, I would recommend the last option if only a single component has changed.

SQL Server : Columns to Rows

well If you have 150 columns then I think that UNPIVOT is not an option. So you could use xml trick

;with CTE1 as (
    select ID, EntityID, (select t.* for xml raw('row'), type) as Data
    from temp1 as t
), CTE2 as (
    select
         C.id, C.EntityID,
         F.C.value('local-name(.)', 'nvarchar(128)') as IndicatorName,
         F.C.value('.', 'nvarchar(max)') as IndicatorValue
    from CTE1 as c
        outer apply c.Data.nodes('row/@*') as F(C)
)
select * from CTE2 where IndicatorName like 'Indicator%'

sql fiddle demo

You could also write dynamic SQL, but I like xml more - for dynamic SQL you have to have permissions to select data directly from table and that's not always an option.

UPDATE
As there a big flame in comments, I think I'll add some pros and cons of xml/dynamic SQL. I'll try to be as objective as I could and not mention elegantness and uglyness. If you got any other pros and cons, edit the answer or write in comments

cons

  • it's not as fast as dynamic SQL, rough tests gave me that xml is about 2.5 times slower that dynamic (it was one query on ~250000 rows table, so this estimate is no way exact). You could compare it yourself if you want, here's sqlfiddle example, on 100000 rows it was 29s (xml) vs 14s (dynamic);
  • may be it could be harder to understand for people not familiar with xpath;

pros

  • it's the same scope as your other queries, and that could be very handy. A few examples come to mind
    • you could query inserted and deleted tables inside your trigger (not possible with dynamic at all);
    • user don't have to have permissions on direct select from table. What I mean is if you have stored procedures layer and user have permissions to run sp, but don't have permissions to query tables directly, you still could use this query inside stored procedure;
    • you could query table variable you have populated in your scope (to pass it inside the dynamic SQL you have to either make it temporary table instead or create type and pass it as a parameter into dynamic SQL;
  • you can do this query inside the function (scalar or table-valued). It's not possible to use dynamic SQL inside the functions;

How to get the Android Emulator's IP address?

If you need to refer to your host computer's localhost, such as when you want the emulator client to contact a server running on the same host, use the alias 10.0.2.2 to refer to the host computer's loopback interface. From the emulator's perspective, localhost (127.0.0.1) refers to its own loopback interface.More details: http://developer.android.com/guide/faq/commontasks.html#localhostalias

Why ModelState.IsValid always return false in mvc

Please post your Model Class.

To check the errors in your ModelState use the following code:

var errors = ModelState
    .Where(x => x.Value.Errors.Count > 0)
    .Select(x => new { x.Key, x.Value.Errors })
    .ToArray();

OR: You can also use

var errors = ModelState.Values.SelectMany(v => v.Errors);

Place a break point at the above line and see what are the errors in your ModelState.

Python Dictionary Comprehension

The main purpose of a list comprehension is to create a new list based on another one without changing or destroying the original list.

Instead of writing

l = []
for n in range(1, 11):
    l.append(n)

or

l = [n for n in range(1, 11)]

you should write only

l = range(1, 11)

In the two top code blocks you're creating a new list, iterating through it and just returning each element. It's just an expensive way of creating a list copy.

To get a new dictionary with all keys set to the same value based on another dict, do this:

old_dict = {'a': 1, 'c': 3, 'b': 2}
new_dict = { key:'your value here' for key in old_dict.keys()}

You're receiving a SyntaxError because when you write

d = {}
d[i for i in range(1, 11)] = True

you're basically saying: "Set my key 'i for i in range(1, 11)' to True" and "i for i in range(1, 11)" is not a valid key, it's just a syntax error. If dicts supported lists as keys, you would do something like

d[[i for i in range(1, 11)]] = True

and not

d[i for i in range(1, 11)] = True

but lists are not hashable, so you can't use them as dict keys.

Refused to execute script, strict MIME type checking is enabled?

I solved my problem by adding just ${pageContext.request.contextPath} to my jsp path . in stead of :

 <script    src="static/js/jquery-3.2.1.min.js"></script>

I set :

 <script    src="${pageContext.request.contextPath}/static/js/jquery-3.2.1.min.js"></script>

How to run sql script using SQL Server Management Studio?

Open SQL Server Management Studio > File > Open > File > Choose your .sql file (the one that contains your script) > Press Open > the file will be opened within SQL Server Management Studio, Now all what you need to do is to press Execute button.

How to set scope property with ng-init?

HTML:

<body ng-app="App">
    <div ng-controller="testController" >
        <input type="hidden" id="testInput" ng-model="testInput" ng-init="testInput=123" />
    </div>
    {{ testInput }}
</body>

JS:

angular.module('App', []);

testController = function ($scope) {
    console.log('test');
    $scope.$watch('testInput', testShow, true);
    function testShow() {
      console.log($scope.testInput);
    }
}

Fiddle

Link to reload current page

You can use a form to do a POST to the same URL.

 <form  method="POST" name="refresh" id="refresh">
 <input type="submit" value="Refresh" />
 </form>

This gives you a button that refreshes the current page. It is a bit annoying because if the user presses the browser refresh button, they will get a do you want to resubmit the form message.

Include another JSP file

What you're doing is a static include. A static include is resolved at compile time, and may thus not use a parameter value, which is only known at execution time.

What you need is a dynamic include:

<jsp:include page="..." />

Note that you should use the JSP EL rather than scriptlets. It also seems that you're implementing a central controller with index.jsp. You should use a servlet to do that instead, and dispatch to the appropriate JSP from this servlet. Or better, use an existing MVC framework like Stripes or Spring MVC.

Android Design Support Library expandable Floating Action Button(FAB) menu

When I tried to create something simillar to inbox floating action button i thought about creating own custom component.

It would be simple frame layout with fixed height (to contain expanded menu) containing FAB button and 3 more placed under the FAB. when you click on FAB you just simply animate other buttons to translate up from under the FAB.

There are some libraries which do that (for example https://github.com/futuresimple/android-floating-action-button), but it's always more fun if you create it by yourself :)

The type initializer for 'System.Data.Entity.Internal.AppConfig' threw an exception

The general issue is just any issue involving Machine/Web/App configs.

I had the same connection strings in Machine.Config as in my App.Config so I put before my first connection string in my App.Config

How do I do a not equal in Django queryset filtering?

What you are looking for are all objects that have either a=false or x=5. In Django, | serves as OR operator between querysets:

results = Model.objects.filter(a=false)|Model.objects.filter(x=5)

How to enable Auto Logon User Authentication for Google Chrome

If you add your site to "Local Intranet" in

Chrome > Options > Under the Hood > Change Proxy Settings > Security (tab) > Local Intranet/Sites > Advanced.

Add you site URL here and it will work.

Update for New Version of Chrome

Chrome > Settings > Advanced > System > Open Proxy Settings > Security (tab) > Local Intranet > Sites (button) > Advanced.

How to reload current page in ReactJS?

use this might help

window.location.reload();

MySQL user DB does not have password columns - Installing MySQL on OSX

Use the ALTER USER command rather than trying to update a USER row. Keep in mind that there may be more than one 'root' user, because user entities are qualified also by the machine from which they connect

https://dev.mysql.com/doc/refman/5.7/en/alter-user.html

For example.

ALTER USER 'root'@'localhost' IDENTIFIED BY 'new-password' 
ALTER USER 'root'@'*' IDENTIFIED BY 'new-password' 

Determine a string's encoding in C#

I found new library on GitHub: CharsetDetector/UTF-unknown

Charset detector build in C# - .NET Core 2-3, .NET standard 1-2 & .NET 4+

it's also a port of the Mozilla Universal Charset Detector based on other repositories.

CharsetDetector/UTF-unknown have a class named CharsetDetector.

CharsetDetector contains some static encoding detect methods:

  • CharsetDetector.DetectFromFile()
  • CharsetDetector.DetectFromStream()
  • CharsetDetector.DetectFromBytes()

detected result is in class DetectionResult has attribute Detected which is instance of class DetectionDetail with below attributes:

  • EncodingName
  • Encoding
  • Confidence

below is an example to show usage:

// Program.cs
using System;
using System.Text;
using UtfUnknown;

namespace ConsoleExample
{
    public class Program
    {
        public static void Main(string[] args)
        {
            string filename = @"E:\new-file.txt";
            DetectDemo(filename);
        }

        /// <summary>
        /// Command line example: detect the encoding of the given file.
        /// </summary>
        /// <param name="filename">a filename</param>
        public static void DetectDemo(string filename)
        {
            // Detect from File
            DetectionResult result = CharsetDetector.DetectFromFile(filename);
            // Get the best Detection
            DetectionDetail resultDetected = result.Detected;

            // detected result may be null.
            if (resultDetected != null)
            {
                // Get the alias of the found encoding
                string encodingName = resultDetected.EncodingName;
                // Get the System.Text.Encoding of the found encoding (can be null if not available)
                Encoding encoding = resultDetected.Encoding;
                // Get the confidence of the found encoding (between 0 and 1)
                float confidence = resultDetected.Confidence;

                if (encoding != null)
                {
                    Console.WriteLine($"Detection completed: {filename}");
                    Console.WriteLine($"EncodingWebName: {encoding.WebName}{Environment.NewLine}Confidence: {confidence}");
                }
                else
                {
                    Console.WriteLine($"Detection completed: {filename}");
                    Console.WriteLine($"(Encoding is null){Environment.NewLine}EncodingName: {encodingName}{Environment.NewLine}Confidence: {confidence}");
                }
            }
            else
            {
                Console.WriteLine($"Detection failed: {filename}");
            }
        }
    }
}

example result screenshot: enter image description here

How to manually include external aar package using new Gradle Android Build System

The standard way to import AAR file in an application is given in https://developer.android.com/studio/projects/android-library.html#AddDependency

Click File > New > New Module. Click Import .JAR/.AAR Package then click Next. Enter the location of the compiled AAR or JAR file then click Finish.

Please refer the link above for next steps.

Checking for a null int value from a Java ResultSet

Another solution:

public class DaoTools {
    static public Integer getInteger(ResultSet rs, String strColName) throws SQLException {
        int nValue = rs.getInt(strColName);
        return rs.wasNull() ? null : nValue;
    }
}

Get the date of next monday, tuesday, etc

PHP 7.1:

$next_date = new DateTime('next Thursday');
$stamp = $next_date->getTimestamp();

PHP manual getTimestamp()

Count the Number of Tables in a SQL Server Database

You can use INFORMATION_SCHEMA.TABLES to retrieve information about your database tables.

As mentioned in the Microsoft Tables Documentation:

INFORMATION_SCHEMA.TABLES returns one row for each table in the current database for which the current user has permissions.

The following query, therefore, will return the number of tables in the specified database:

USE MyDatabase
SELECT COUNT(*)
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'

As of SQL Server 2008, you can also use sys.tables to count the the number of tables.

From the Microsoft sys.tables Documentation:

sys.tables returns a row for each user table in SQL Server.

The following query will also return the number of table in your database:

SELECT COUNT(*)
FROM sys.tables

IE 8: background-size fix

Also i have found another useful link. It is a background hack used like this

.selector { background-size: cover; -ms-behavior: url(/backgroundsize.min.htc); }

https://github.com/louisremi/background-size-polyfill

What are the options for storing hierarchical data in a relational database?

Adjacency Model + Nested Sets Model

I went for it because I could insert new items to the tree easily (you just need a branch's id to insert a new item to it) and also query it quite fast.

+-------------+----------------------+--------+-----+-----+
| category_id | name                 | parent | lft | rgt |
+-------------+----------------------+--------+-----+-----+
|           1 | ELECTRONICS          |   NULL |   1 |  20 |
|           2 | TELEVISIONS          |      1 |   2 |   9 |
|           3 | TUBE                 |      2 |   3 |   4 |
|           4 | LCD                  |      2 |   5 |   6 |
|           5 | PLASMA               |      2 |   7 |   8 |
|           6 | PORTABLE ELECTRONICS |      1 |  10 |  19 |
|           7 | MP3 PLAYERS          |      6 |  11 |  14 |
|           8 | FLASH                |      7 |  12 |  13 |
|           9 | CD PLAYERS           |      6 |  15 |  16 |
|          10 | 2 WAY RADIOS         |      6 |  17 |  18 |
+-------------+----------------------+--------+-----+-----+
  • Every time you need all children of any parent you just query the parent column.
  • If you needed all descendants of any parent you query for items which have their lft between lft and rgt of parent.
  • If you needed all parents of any node up to the root of the tree, you query for items having lft lower than the node's lft and rgt bigger than the node's rgt and sort the by parent.

I needed to make accessing and querying the tree faster than inserts, that's why I chose this

The only problem is to fix the left and right columns when inserting new items. well I created a stored procedure for it and called it every time I inserted a new item which was rare in my case but it is really fast. I got the idea from the Joe Celko's book, and the stored procedure and how I came up with it is explained here in DBA SE https://dba.stackexchange.com/q/89051/41481

Change the Arrow buttons in Slick slider

if your using react-slick you can try this on custom next and prev divs

https://react-slick.neostack.com/docs/example/previous-next-methods

Breadth First Vs Depth First

These two terms differentiate between two different ways of walking a tree.

It is probably easiest just to exhibit the difference. Consider the tree:

    A
   / \
  B   C
 /   / \
D   E   F

A depth first traversal would visit the nodes in this order

A, B, D, C, E, F

Notice that you go all the way down one leg before moving on.

A breadth first traversal would visit the node in this order

A, B, C, D, E, F

Here we work all the way across each level before going down.

(Note that there is some ambiguity in the traversal orders, and I've cheated to maintain the "reading" order at each level of the tree. In either case I could get to B before or after C, and likewise I could get to E before or after F. This may or may not matter, depends on you application...)


Both kinds of traversal can be achieved with the pseudocode:

Store the root node in Container
While (there are nodes in Container)
   N = Get the "next" node from Container
   Store all the children of N in Container
   Do some work on N

The difference between the two traversal orders lies in the choice of Container.

  • For depth first use a stack. (The recursive implementation uses the call-stack...)
  • For breadth-first use a queue.

The recursive implementation looks like

ProcessNode(Node)
   Work on the payload Node
   Foreach child of Node
      ProcessNode(child)
   /* Alternate time to work on the payload Node (see below) */

The recursion ends when you reach a node that has no children, so it is guaranteed to end for finite, acyclic graphs.


At this point, I've still cheated a little. With a little cleverness you can also work-on the nodes in this order:

D, B, E, F, C, A

which is a variation of depth-first, where I don't do the work at each node until I'm walking back up the tree. I have however visited the higher nodes on the way down to find their children.

This traversal is fairly natural in the recursive implementation (use the "Alternate time" line above instead of the first "Work" line), and not too hard if you use a explicit stack, but I'll leave it as an exercise.

AND/OR in Python?

or is not exclusive (e.g. xor) so or is the same thing as and/or.

Ping all addresses in network, windows

An expansion and useful addition to egmackenzie's "arp -a" solution for Windows -

Windows Example searching for my iPhone on the WiFi network

(pre: iPhone WiFi disabled)

  • Open Command Prompt in Admin mode (R.C. Start & look in menu)
  • arp -d <- clear the arp listing!
  • ping 10.1.10.255 <- take your subnet, and ping '255', everyone
  • arp -a
  • iPhone WiFi on
  • ping 10.1.10.255
  • arp -a

See below for example:

enter image description here

Here is a nice writeup on the use of 'arp -d' here if interested -

vertical-align: middle doesn't work

You must wrap your element in a table-cell, within a table using display.

Like this:

<div>
  <span class='twoline'>Two line text</span>
  <span class='float'>Float right</span>
</div>

and

.float {
    display: table-cell;
    vertical-align: middle;
    text-align: right;
}
.twoline {
    width: 50px;
    display: table-cell;
}
div {
    display: table;
    border: solid 1px blue;
    width: 500px;
    height: 100px;
}

Shown here: http://jsfiddle.net/e8ESb/7/

T-SQL: Export to new Excel file

Use PowerShell:

$Server = "TestServer"
$Database = "TestDatabase"
$Query = "select * from TestTable"
$FilePath = "C:\OutputFile.csv"

# This will overwrite the file if it already exists.
Invoke-Sqlcmd -Query $Query -Database $Database -ServerInstance $Server | Export-Csv $FilePath

In my usual cases, all I really need is a CSV file that can be read by Excel. However, if you need an actual Excel file, then tack on some code to convert the CSV file to an Excel file. This answer gives a solution for this, but I've not tested it.

How do I determine file encoding in OS X?

Classic 8-bit LaTeX is very restricted in which UTF8 characters it can use; it's highly dependent on the encoding of the font you're using and which glyphs that font has available.

Since you don't give a specific example, it's hard to know exactly where the problem is — whether you're attempting to use a glyph that your font doesn't have or whether you're not using the correct font encoding in the first place.

Here's a minimal example showing how a few UTF8 characters can be used in a LaTeX document:

\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage{lmodern}
\usepackage[utf8]{inputenc}
\begin{document}
‘Héllø—thêrè.’
\end{document}

You may have more luck with the [utf8x] encoding, but be slightly warned that it's no longer supported and has some idiosyncrasies compared with [utf8] (as far as I recall; it's been a while since I've looked at it). But if it does the trick, that's all that matters for you.

{"<user xmlns=''> was not expected.} Deserializing Twitter XML

Even easier is just to add the following annotations to the top of your class:

[Serializable, XmlRoot("user")]
public partial class User
{
}

Python and pip, list all versions of a package that's available?

I didn't have any luck with yolk, yolk3k or pip install -v but so I ended up using this (adapted to Python 3 from eric chiang's answer):

import json
import requests
from distutils.version import StrictVersion

def versions(package_name):
    url = "https://pypi.python.org/pypi/{}/json".format(package_name)
    data = requests.get(url).json()
    return sorted(list(data["releases"].keys()), key=StrictVersion, reverse=True)

>>> print("\n".join(versions("gunicorn")))
19.1.1
19.1.0
19.0.0
18.0
17.5
0.17.4
0.17.3
...

Why can't I define a static method in a Java interface?

Interfaces just provide a list of things a class will provide, not an actual implementation of those things, which is what your static item is.

If you want statics, use an abstract class and inherit it, otherwise, remove the static.

Hope that helps!

Deployment error:Starting of Tomcat failed, the server port 8080 is already in use

If you are behind a proxy server this issue could happen i had the same issue and was solved by: Preferences -> General -> Proxy Settings -> No Proxy.

"Maybe the tomcat ready-message was sent to the proxy - and never reached the IDE."

found @: https://netbeans.org/bugzilla/show_bug.cgi?id=231220

Keep a line of text as a single line - wrap the whole line or none at all

You can use white-space: nowrap; to define this behaviour:

// HTML:

_x000D_
_x000D_
.nowrap {_x000D_
  white-space: nowrap ;_x000D_
}
_x000D_
<p>_x000D_
      <span class="nowrap">How do I wrap this line of text</span>_x000D_
      <span class="nowrap">- asked by Peter 2 days ago</span>_x000D_
    </p>
_x000D_
_x000D_
_x000D_

// CSS:
.nowrap {
  white-space: nowrap ;
}

Custom CSS Scrollbar for Firefox

Firefox 64 adds support for the spec draft CSS Scrollbars Module Level 1, which adds two new properties of scrollbar-width and scrollbar-color which give some control over how scrollbars are displayed.

You can set scrollbar-color to one of the following values (descriptions from MDN):

  • auto Default platform rendering for the track portion of the scrollbar, in the absence of any other related scrollbar color properties.
  • dark Show a dark scrollbar, which can be either a dark variant of scrollbar provided by the platform, or a custom scrollbar with dark colors.
  • light Show a light scrollbar, which can be either a light variant of scrollbar provided by the platform, or a custom scrollbar with light colors.
  • <color> <color> Applies the first color to the scrollbar thumb, the second to the scrollbar track.

Note that dark and light values are not currently implemented in Firefox.

macOS notes:

The auto-hiding semi-transparent scrollbars that are the macOS default cannot be colored with this rule (they still choose their own contrasting color based on the background). Only the permanently showing scrollbars (System Preferences > Show Scroll Bars > Always) are colored.

Visual Demo:

_x000D_
_x000D_
.scroll {_x000D_
  width: 20%;_x000D_
  height: 100px;_x000D_
  border: 1px solid grey;_x000D_
  overflow: scroll;_x000D_
  display: inline-block;_x000D_
}_x000D_
.scroll-color-auto {_x000D_
  scrollbar-color: auto;_x000D_
}_x000D_
.scroll-color-dark {_x000D_
  scrollbar-color: dark;_x000D_
}_x000D_
.scroll-color-light {_x000D_
  scrollbar-color: light;_x000D_
}_x000D_
.scroll-color-colors {_x000D_
  scrollbar-color: orange lightyellow;_x000D_
}
_x000D_
<div class="scroll scroll-color-auto">_x000D_
<p>auto</p><p>auto</p><p>auto</p><p>auto</p><p>auto</p><p>auto</p>_x000D_
</div>_x000D_
_x000D_
<div class="scroll scroll-color-dark">_x000D_
<p>dark</p><p>dark</p><p>dark</p><p>dark</p><p>dark</p><p>dark</p>_x000D_
</div>_x000D_
_x000D_
<div class="scroll scroll-color-light">_x000D_
<p>light</p><p>light</p><p>light</p><p>light</p><p>light</p><p>light</p>_x000D_
</div>_x000D_
_x000D_
<div class="scroll scroll-color-colors">_x000D_
<p>colors</p><p>colors</p><p>colors</p><p>colors</p><p>colors</p><p>colors</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

You can set scrollbar-width to one of the following values (descriptions from MDN):

  • auto The default scrollbar width for the platform.
  • thin A thin scrollbar width variant on platforms that provide that option, or a thinner scrollbar than the default platform scrollbar width.
  • none No scrollbar shown, however the element will still be scrollable.

You can also set a specific length value, according to the spec. Both thin and a specific length may not do anything on all platforms, and what exactly it does is platform-specific. In particular, Firefox doesn't appear to be currently support a specific length value (this comment on their bug tracker seems to confirm this). The thin keywork does appear to be well-supported however, with macOS and Windows support at-least.

It's probably worth noting that the length value option and the entire scrollbar-width property are being considered for removal in a future draft, and if that happens this particular property may be removed from Firefox in a future version.

Visual Demo:

_x000D_
_x000D_
.scroll {_x000D_
  width: 30%;_x000D_
  height: 100px;_x000D_
  border: 1px solid grey;_x000D_
  overflow: scroll;_x000D_
  display: inline-block;_x000D_
}_x000D_
.scroll-width-auto {_x000D_
  scrollbar-width: auto;_x000D_
}_x000D_
.scroll-width-thin {_x000D_
  scrollbar-width: thin;_x000D_
}_x000D_
.scroll-width-none {_x000D_
  scrollbar-width: none;_x000D_
}
_x000D_
<div class="scroll scroll-width-auto">_x000D_
<p>auto</p><p>auto</p><p>auto</p><p>auto</p><p>auto</p><p>auto</p>_x000D_
</div>_x000D_
_x000D_
<div class="scroll scroll-width-thin">_x000D_
<p>thin</p><p>thin</p><p>thin</p><p>thin</p><p>thin</p><p>thin</p>_x000D_
</div>_x000D_
_x000D_
<div class="scroll scroll-width-none">_x000D_
<p>none</p><p>none</p><p>none</p><p>none</p><p>none</p><p>none</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

javax.websocket client simple example

Have a look at this Java EE 7 examples from Arun Gupta.

I forked it on github.

Main

/**
 * @author Arun Gupta
 */
public class Client {

    final static CountDownLatch messageLatch = new CountDownLatch(1);

    public static void main(String[] args) {
        try {
            WebSocketContainer container = ContainerProvider.getWebSocketContainer();
            String uri = "ws://echo.websocket.org:80/";
            System.out.println("Connecting to " + uri);
            container.connectToServer(MyClientEndpoint.class, URI.create(uri));
            messageLatch.await(100, TimeUnit.SECONDS);
        } catch (DeploymentException | InterruptedException | IOException ex) {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

ClientEndpoint

/**
 * @author Arun Gupta
 */
@ClientEndpoint
public class MyClientEndpoint {
    @OnOpen
    public void onOpen(Session session) {
        System.out.println("Connected to endpoint: " + session.getBasicRemote());
        try {
            String name = "Duke";
            System.out.println("Sending message to endpoint: " + name);
            session.getBasicRemote().sendText(name);
        } catch (IOException ex) {
            Logger.getLogger(MyClientEndpoint.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @OnMessage
    public void processMessage(String message) {
        System.out.println("Received message in client: " + message);
        Client.messageLatch.countDown();
    }

    @OnError
    public void processError(Throwable t) {
        t.printStackTrace();
    }
}

Does java have a int.tryparse that doesn't throw an exception for bad data?

No. You have to make your own like this:

boolean tryParseInt(String value) {  
     try {  
         Integer.parseInt(value);  
         return true;  
      } catch (NumberFormatException e) {  
         return false;  
      }  
}

...and you can use it like this:

if (tryParseInt(input)) {  
   Integer.parseInt(input);  // We now know that it's safe to parse
}

EDIT (Based on the comment by @Erk)

Something like follows should be better

public int tryParse(String value, int defaultVal) {
    try {
        return Integer.parseInt(value);
    } catch (NumberFormatException e) {
        return defaultVal;
    }
}

When you overload this with a single string parameter method, it would be even better, which will enable using with the default value being optional.

public int tryParse(String value) {
    return tryParse(value, 0)
}

PLS-00103: Encountered the symbol "CREATE"

For me / had to be in a new line.

For example

create type emp_t;/

didn't work

but

create type emp_t;

/

worked.

Recommended way to save uploaded files in a servlet application

Store it anywhere in an accessible location except of the IDE's project folder aka the server's deploy folder, for reasons mentioned in the answer to Uploaded image only available after refreshing the page:

  1. Changes in the IDE's project folder does not immediately get reflected in the server's work folder. There's kind of a background job in the IDE which takes care that the server's work folder get synced with last updates (this is in IDE terms called "publishing"). This is the main cause of the problem you're seeing.

  2. In real world code there are circumstances where storing uploaded files in the webapp's deploy folder will not work at all. Some servers do (either by default or by configuration) not expand the deployed WAR file into the local disk file system, but instead fully in the memory. You can't create new files in the memory without basically editing the deployed WAR file and redeploying it.

  3. Even when the server expands the deployed WAR file into the local disk file system, all newly created files will get lost on a redeploy or even a simple restart, simply because those new files are not part of the original WAR file.

It really doesn't matter to me or anyone else where exactly on the local disk file system it will be saved, as long as you do not ever use getRealPath() method. Using that method is in any case alarming.

The path to the storage location can in turn be definied in many ways. You have to do it all by yourself. Perhaps this is where your confusion is caused because you somehow expected that the server does that all automagically. Please note that @MultipartConfig(location) does not specify the final upload destination, but the temporary storage location for the case file size exceeds memory storage threshold.

So, the path to the final storage location can be definied in either of the following ways:

  • Hardcoded:

      File uploads = new File("/path/to/uploads");
    
  • Environment variable via SET UPLOAD_LOCATION=/path/to/uploads:

      File uploads = new File(System.getenv("UPLOAD_LOCATION"));
    
  • VM argument during server startup via -Dupload.location="/path/to/uploads":

      File uploads = new File(System.getProperty("upload.location"));
    
  • *.properties file entry as upload.location=/path/to/uploads:

      File uploads = new File(properties.getProperty("upload.location"));
    
  • web.xml <context-param> with name upload.location and value /path/to/uploads:

      File uploads = new File(getServletContext().getInitParameter("upload.location"));
    
  • If any, use the server-provided location, e.g. in JBoss AS/WildFly:

      File uploads = new File(System.getProperty("jboss.server.data.dir"), "uploads");
    

Either way, you can easily reference and save the file as follows:

File file = new File(uploads, "somefilename.ext");

try (InputStream input = part.getInputStream()) {
    Files.copy(input, file.toPath());
}

Or, when you want to autogenerate an unique file name to prevent users from overwriting existing files with coincidentally the same name:

File file = File.createTempFile("somefilename-", ".ext", uploads);

try (InputStream input = part.getInputStream()) {
    Files.copy(input, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
}

How to obtain part in JSP/Servlet is answered in How to upload files to server using JSP/Servlet? and how to obtain part in JSF is answered in How to upload file using JSF 2.2 <h:inputFile>? Where is the saved File?

Note: do not use Part#write() as it interprets the path relative to the temporary storage location defined in @MultipartConfig(location).

See also: