Programs & Examples On #Keyword search

How can I use grep to find a word inside a folder?

Why not do a recursive search to find all instances in sub directories:

grep -r 'text' *

This works like a charm.

How can I uninstall Ruby on ubuntu?

Here is what sudo apt-get purge ruby* removed relating to GRUB for me:

grub-pc 
grub-gfxpayload-lists
grub2-common
grub-pc-bin 
grub-common 

Response.Redirect to new window

Because Response.Redirect is initiated on the server you can't do it using that.

If you can write directly to the Response stream you could try something like:

response.write("<script>");
response.write("window.open('page.html','_blank')");
response.write("</script>");

JavaScript closure inside loops – simple practical example

Bit late to the party, but I was exploring this issue today and noticed that many of the answers don't completely address how Javascript treats scopes, which is essentially what this boils down to.

So as many others mentioned, the problem is that the inner function is referencing the same i variable. So why don't we just create a new local variable each iteration, and have the inner function reference that instead?

_x000D_
_x000D_
//overwrite console.log() so you can see the console output
console.log = function(msg) {document.body.innerHTML += '<p>' + msg + '</p>';};

var funcs = {};
for (var i = 0; i < 3; i++) {
    var ilocal = i; //create a new local variable
    funcs[i] = function() {
        console.log("My value: " + ilocal); //each should reference its own local variable
    };
}
for (var j = 0; j < 3; j++) {
    funcs[j]();
}
_x000D_
_x000D_
_x000D_

Just like before, where each inner function outputted the last value assigned to i, now each inner function just outputs the last value assigned to ilocal. But shouldn't each iteration have it's own ilocal?

Turns out, that's the issue. Each iteration is sharing the same scope, so every iteration after the first is just overwriting ilocal. From MDN:

Important: JavaScript does not have block scope. Variables introduced with a block are scoped to the containing function or script, and the effects of setting them persist beyond the block itself. In other words, block statements do not introduce a scope. Although "standalone" blocks are valid syntax, you do not want to use standalone blocks in JavaScript, because they don't do what you think they do, if you think they do anything like such blocks in C or Java.

Reiterated for emphasis:

JavaScript does not have block scope. Variables introduced with a block are scoped to the containing function or script

We can see this by checking ilocal before we declare it in each iteration:

_x000D_
_x000D_
//overwrite console.log() so you can see the console output
console.log = function(msg) {document.body.innerHTML += '<p>' + msg + '</p>';};

var funcs = {};
for (var i = 0; i < 3; i++) {
  console.log(ilocal);
  var ilocal = i;
}
_x000D_
_x000D_
_x000D_

This is exactly why this bug is so tricky. Even though you are redeclaring a variable, Javascript won't throw an error, and JSLint won't even throw a warning. This is also why the best way to solve this is to take advantage of closures, which is essentially the idea that in Javascript, inner functions have access to outer variables because inner scopes "enclose" outer scopes.

Closures

This also means that inner functions "hold onto" outer variables and keep them alive, even if the outer function returns. To utilize this, we create and call a wrapper function purely to make a new scope, declare ilocal in the new scope, and return an inner function that uses ilocal (more explanation below):

_x000D_
_x000D_
//overwrite console.log() so you can see the console output
console.log = function(msg) {document.body.innerHTML += '<p>' + msg + '</p>';};

var funcs = {};
for (var i = 0; i < 3; i++) {
    funcs[i] = (function() { //create a new scope using a wrapper function
        var ilocal = i; //capture i into a local var
        return function() { //return the inner function
            console.log("My value: " + ilocal);
        };
    })(); //remember to run the wrapper function
}
for (var j = 0; j < 3; j++) {
    funcs[j]();
}
_x000D_
_x000D_
_x000D_

Creating the inner function inside a wrapper function gives the inner function a private environment that only it can access, a "closure". Thus, every time we call the wrapper function we create a new inner function with it's own separate environment, ensuring that the ilocal variables don't collide and overwrite each other. A few minor optimizations gives the final answer that many other SO users gave:

_x000D_
_x000D_
//overwrite console.log() so you can see the console output
console.log = function(msg) {document.body.innerHTML += '<p>' + msg + '</p>';};

var funcs = {};
for (var i = 0; i < 3; i++) {
    funcs[i] = wrapper(i);
}
for (var j = 0; j < 3; j++) {
    funcs[j]();
}
//creates a separate environment for the inner function
function wrapper(ilocal) {
    return function() { //return the inner function
        console.log("My value: " + ilocal);
    };
}
_x000D_
_x000D_
_x000D_

Update

With ES6 now mainstream, we can now use the new let keyword to create block-scoped variables:

_x000D_
_x000D_
//overwrite console.log() so you can see the console output
console.log = function(msg) {document.body.innerHTML += '<p>' + msg + '</p>';};

var funcs = {};
for (let i = 0; i < 3; i++) { // use "let" to declare "i"
    funcs[i] = function() {
        console.log("My value: " + i); //each should reference its own local variable
    };
}
for (var j = 0; j < 3; j++) { // we can use "var" here without issue
    funcs[j]();
}
_x000D_
_x000D_
_x000D_

Look how easy it is now! For more information see this answer, which my info is based off of.

Appending to an object

You can do this with Object.assign(). Sometimes you need an array, but when working with functions that expect a single JSON object -- such as an OData call -- I've found this method simpler than creating an array only to unpack it.

var alerts = { 
    1: {app:'helloworld',message:'message'},
    2: {app:'helloagain',message:'another message'}
}

alerts = Object.assign({3: {app:'helloagain_again',message:'yet another message'}}, alerts)

//Result:
console.log(alerts)
{ 
    1: {app:'helloworld',message:'message'},
    2: {app:'helloagain',message:'another message'}
    3: {app: "helloagain_again",message: "yet another message"}
} 

EDIT: To address the comment regarding getting the next key, you can get an array of the keys with the Object.keys() function -- see Vadi's answer for an example of incrementing the key. Similarly, you can get all the values with Object.values() and key-values pairs with Object.entries().

var alerts = { 
    1: {app:'helloworld',message:'message'},
    2: {app:'helloagain',message:'another message'}
}
console.log(Object.keys(alerts))
// Output
Array [ "1", "2" ]

Best practice for localization and globalization of strings and labels

When you’re faced with a problem to solve (and frankly, who isn’t these days?), the basic strategy usually taken by we computer people is called “divide and conquer.” It goes like this:

  • Conceptualize the specific problem as a set of smaller sub-problems.
  • Solve each smaller problem.
  • Combine the results into a solution of the specific problem.

But “divide and conquer” is not the only possible strategy. We can also take a more generalist approach:

  • Conceptualize the specific problem as a special case of a more general problem.
  • Somehow solve the general problem.
  • Adapt the solution of the general problem to the specific problem.

- Eric Lippert

I believe many solutions already exist for this problem in server-side languages such as ASP.Net/C#.

I've outlined some of the major aspects of the problem

  • Issue: We need to load data only for the desired language

    Solution: For this purpose we save data to a separate files for each language

ex. res.de.js, res.fr.js, res.en.js, res.js(for default language)

  • Issue: Resource files for each page should be separated so we only get the data we need

    Solution: We can use some tools that already exist like https://github.com/rgrove/lazyload

  • Issue: We need a key/value pair structure to save our data

    Solution: I suggest a javascript object instead of string/string air. We can benefit from the intellisense from an IDE

  • Issue: General members should be stored in a public file and all pages should access them

    Solution: For this purpose I make a folder in the root of web application called Global_Resources and a folder to store global file for each sub folders we named it 'Local_Resources'

  • Issue: Each subsystems/subfolders/modules member should override the Global_Resources members on their scope

    Solution: I considered a file for each

Application Structure

root/
    Global_Resources/
        default.js
        default.fr.js
    UserManagementSystem/
        Local_Resources/
            default.js
            default.fr.js
            createUser.js
        Login.htm
        CreateUser.htm

The corresponding code for the files:

Global_Resources/default.js

var res = {
    Create : "Create",
    Update : "Save Changes",
    Delete : "Delete"
};

Global_Resources/default.fr.js

var res = {
    Create : "créer",
    Update : "Enregistrer les modifications",
    Delete : "effacer"
};

The resource file for the desired language should be loaded on the page selected from Global_Resource - This should be the first file that is loaded on all the pages.

UserManagementSystem/Local_Resources/default.js

res.Name = "Name";
res.UserName = "UserName";
res.Password = "Password";

UserManagementSystem/Local_Resources/default.fr.js

res.Name = "nom";
res.UserName = "Nom d'utilisateur";
res.Password = "Mot de passe";

UserManagementSystem/Local_Resources/createUser.js

// Override res.Create on Global_Resources/default.js
res.Create = "Create User"; 

UserManagementSystem/Local_Resources/createUser.fr.js

// Override Global_Resources/default.fr.js
res.Create = "Créer un utilisateur";

manager.js file (this file should be load last)

res.lang = "fr";

var globalResourcePath = "Global_Resources";
var resourceFiles = [];

var currentFile = globalResourcePath + "\\default" + res.lang + ".js" ;

if(!IsFileExist(currentFile))
    currentFile = globalResourcePath + "\\default.js" ;
if(!IsFileExist(currentFile)) throw new Exception("File Not Found");

resourceFiles.push(currentFile);

// Push parent folder on folder into folder
foreach(var folder in parent folder of current page)
{
    currentFile = folder + "\\Local_Resource\\default." + res.lang + ".js";

    if(!IsExist(currentFile))
        currentFile = folder + "\\Local_Resource\\default.js";
    if(!IsExist(currentFile)) throw new Exception("File Not Found");

    resourceFiles.push(currentFile);
}

for(int i = 0; i < resourceFiles.length; i++) { Load.js(resourceFiles[i]); }

// Get current page name
var pageNameWithoutExtension = "SomePage";

currentFile = currentPageFolderPath + pageNameWithoutExtension + res.lang + ".js" ;

if(!IsExist(currentFile))
    currentFile = currentPageFolderPath + pageNameWithoutExtension + ".js" ;
if(!IsExist(currentFile)) throw new Exception("File Not Found");

Hope it helps :)

Tomcat is not deploying my web project from Eclipse

I tried everything and nothing worked so here is another solution that finally worked (for me).

I had to check Enable Java EE configuration under Preferences -> Maven -> Jave EE configuration

After that you can check that more entries were added in Deployment assemblies of the project settings.

Viewing unpushed Git commits

If you have git submodules...

Whether you do git cherry -v or git logs @{u}.. -p, don't forget to include your submodules via git submodule foreach --recursive 'git logs @{u}..'.

I am using the following bash script to check all of that:

    unpushedCommitsCmd="git log @{u}.."; # Source: https://stackoverflow.com/a/8182309

    # check if there are unpushed changes
    if [ -n "$($getGitUnpushedCommits)" ]; then # Check Source: https://stackoverflow.com/a/12137501
        echo "You have unpushed changes.  Push them first!"
        $getGitUnpushedCommits;
        exit 2
    fi

    unpushedInSubmodules="git submodule foreach --recursive --quiet ${unpushedCommitsCmd}"; # Source: https://stackoverflow.com/a/24548122
    # check if there are unpushed changes in submodules
    if [ -n "$($unpushedInSubmodules)" ]; then
        echo "You have unpushed changes in submodules.  Push them first!"
        git submodule foreach --recursive ${unpushedCommitsCmd} # not "--quiet" this time, to display details
        exit 2
    fi

jQuery get the location of an element relative to window

function getWindowRelativeOffset(parentWindow, elem) {
        var offset = {
            left : 0,
            top : 0
        };
        // relative to the target field's document
        offset.left = elem.getBoundingClientRect().left;
        offset.top = elem.getBoundingClientRect().top;
        // now we will calculate according to the current document, this current
        // document might be same as the document of target field or it may be
        // parent of the document of the target field
        var childWindow = elem.document.frames.window;
        while (childWindow != parentWindow) {
            offset.left = offset.left + childWindow.frameElement.getBoundingClientRect().left;
            offset.top = offset.top + childWindow.frameElement.getBoundingClientRect().top;
            childWindow = childWindow.parent;
        }
        return offset;
    };

you can call it like this

getWindowRelativeOffset(top, inputElement);

I focus for IE only as per my requirement but similar can be done for other browsers

How do I pass parameters to a jar file at the time of execution?

The JAVA Documentation says:

java [ options ] -jar file.jar [ argument ... ]

and

... Non-option arguments after the class name or JAR file name are passed to the main function...

Maybe you have to put the arguments in single quotes.

How do I create a datetime in Python from milliseconds?

import pandas as pd

Date_Time = pd.to_datetime(df.NameOfColumn, unit='ms')

Making a button invisible by clicking another button in HTML

Use the id of the element to do the same.

document.getElementById(id).style.visibility = 'hidden';

How do I pass a method as a parameter in Python

Here is your example re-written to show a stand-alone working example:

class Test:
    def method1(self):
        return 'hello world'

    def method2(self, methodToRun):
        result = methodToRun()
        return result

    def method3(self):
        return self.method2(self.method1)

test = Test()

print test.method3()

Loop through childNodes

Here is a functional ES6 way of iterating over a NodeList. This method uses the Array's forEach like so:

Array.prototype.forEach.call(element.childNodes, f)

Where f is the iterator function that receives a child nodes as it's first parameter and the index as the second.

If you need to iterate over NodeLists more than once you could create a small functional utility method out of this:

const forEach = f => x => Array.prototype.forEach.call(x, f);

// For example, to log all child nodes
forEach((item) => { console.log(item); })(element.childNodes)

// The functional forEach is handy as you can easily created curried functions
const logChildren = forEach((childNode) => { console.log(childNode); })
logChildren(elementA.childNodes)
logChildren(elementB.childNodes)

(You can do the same trick for map() and other Array functions.)

"commence before first target. Stop." error

if you have added a new line, Make sure you have added next line syntax in previous line. typically if "\" is missing in your previous line of changes, you will get this error.

Right align text in android TextView

In my case, I was using Relative Layout for a emptyString

After struggling on this for an hour. Only this worked for me:

android:layout_toRightOf="@id/welcome"
android:layout_toEndOf="@id/welcome"
android:layout_alignBaseline="@id/welcome"

layout_toRightOf or layout_toEndOf both works, but to support it better, I used both.

To make it more clear:

This was what I was trying to do:

enter image description here

And this was the emulator's output

enter image description here

Layout:

<TextView
    android:id="@+id/welcome"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="16dp"
    android:layout_marginTop="16dp"
    android:text="Welcome "
    android:textSize="16sp" />
<TextView
    android:id="@+id/username"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@id/welcome"
    android:layout_toRightOf="@id/welcome"
    android:text="@string/emptyString"
    android:textSize="16sp" />

Notice that:

  1. android:layout_width="wrap_content" works
  2. Gravity is not used

Get random sample from list while maintaining ordering of items?

Simple-to-code O(N + K*log(K)) way

Take a random sample without replacement of the indices, sort the indices, and take them from the original.

indices = random.sample(range(len(myList)), K)
[myList[i] for i in sorted(indices)]

Or more concisely:

[x[1] for x in sorted(random.sample(enumerate(myList),K))]

Optimized O(N)-time, O(1)-auxiliary-space way

You can alternatively use a math trick and iteratively go through myList from left to right, picking numbers with dynamically-changing probability (N-numbersPicked)/(total-numbersVisited). The advantage of this approach is that it's an O(N) algorithm since it doesn't involve sorting!

from __future__ import division

def orderedSampleWithoutReplacement(seq, k):
    if not 0<=k<=len(seq):
        raise ValueError('Required that 0 <= sample_size <= population_size')

    numbersPicked = 0
    for i,number in enumerate(seq):
        prob = (k-numbersPicked)/(len(seq)-i)
        if random.random() < prob:
            yield number
            numbersPicked += 1

Proof of concept and test that probabilities are correct:

Simulated with 1 trillion pseudorandom samples over the course of 5 hours:

>>> Counter(
        tuple(orderedSampleWithoutReplacement([0,1,2,3], 2))
        for _ in range(10**9)
    )
Counter({
    (0, 3): 166680161, 
    (1, 2): 166672608, 
    (0, 2): 166669915, 
    (2, 3): 166667390, 
    (1, 3): 166660630, 
    (0, 1): 166649296
})

Probabilities diverge from true probabilities by less a factor of 1.0001. Running this test again resulted in a different order meaning it isn't biased towards one ordering. Running the test with fewer samples for [0,1,2,3,4], k=3 and [0,1,2,3,4,5], k=4 had similar results.

edit: Not sure why people are voting up wrong comments or afraid to upvote... NO, there is nothing wrong with this method. =)

(Also a useful note from user tegan in the comments: If this is python2, you will want to use xrange, as usual, if you really care about extra space.)

edit: Proof: Considering the uniform distribution (without replacement) of picking a subset of k out of a population seq of size len(seq), we can consider a partition at an arbitrary point i into 'left' (0,1,...,i-1) and 'right' (i,i+1,...,len(seq)). Given that we picked numbersPicked from the left known subset, the remaining must come from the same uniform distribution on the right unknown subset, though the parameters are now different. In particular, the probability that seq[i] contains a chosen element is #remainingToChoose/#remainingToChooseFrom, or (k-numbersPicked)/(len(seq)-i), so we simulate that and recurse on the result. (This must terminate since if #remainingToChoose == #remainingToChooseFrom, then all remaining probabilities are 1.) This is similar to a probability tree that happens to be dynamically generated. Basically you can simulate a uniform probability distribution by conditioning on prior choices (as you grow the probability tree, you pick the probability of the current branch such that it is aposteriori the same as prior leaves, i.e. conditioned on prior choices; this will work because this probability is uniformly exactly N/k).

edit: Timothy Shields mentions Reservoir Sampling, which is the generalization of this method when len(seq) is unknown (such as with a generator expression). Specifically the one noted as "algorithm R" is O(N) and O(1) space if done in-place; it involves taking the first N element and slowly replacing them (a hint at an inductive proof is also given). There are also useful distributed variants and miscellaneous variants of reservoir sampling to be found on the wikipedia page.

edit: Here's another way to code it below in a more semantically obvious manner.

from __future__ import division
import random

def orderedSampleWithoutReplacement(seq, sampleSize):
    totalElems = len(seq)
    if not 0<=sampleSize<=totalElems:
        raise ValueError('Required that 0 <= sample_size <= population_size')

    picksRemaining = sampleSize
    for elemsSeen,element in enumerate(seq):
        elemsRemaining = totalElems - elemsSeen
        prob = picksRemaining/elemsRemaining
        if random.random() < prob:
            yield element
            picksRemaining -= 1

from collections import Counter         
Counter(
    tuple(orderedSampleWithoutReplacement([0,1,2,3], 2))
    for _ in range(10**5)

)

Display help message with python argparse when script is called without any arguments

If your command is something where a user needs to choose some action, then use a mutually exclusive group with required=True.

This is kind of an extension to the answer given by pd321.

import argparse

parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument("--batch", action='store', type=int,  metavar='pay_id')
group.add_argument("--list", action='store_true')
group.add_argument("--all", action='store_true', help='check all payments')

args=parser.parse_args()

if args.batch:
    print('batch {}'.format(args.batch))

if args.list:
    print('list')

if args.all:
    print('all')

Output:

$ python3 a_test.py
usage: a_test.py [-h] (--batch pay_id | --list | --all)
a_test.py: error: one of the arguments --batch --list --all is required

This only give the basic help. And some of the other answers will give you the full help. But at least your users know they can do -h

Android Spinner: Get the selected item change event

One trick I found was putting your setOnItemSelectedListeners in onWindowFocusChanged instead of onCreate. I haven't found any bad side-effects to doing it this way, yet. Basically, set up the listeners after the window gets drawn. I'm not sure how often onWindowFocusChanged runs, but it's easy enough to create yourself a lock variable if you are finding it running too often.

I think Android might be using a message-based processing system, and if you put it all in onCreate, you may run into situations where the spinner gets populated after it gets drawn. So, your listener will fire off after you set the item location. This is an educated guess, of course, but feel free to correct me on this.

XPath selecting a node with some attribute value equals to some other node's attribute value

This XPath is specific to the code snippet you've provided. To select <child> with id as #grand you can write //child[@id='#grand'].

To get age //child[@id='#grand']/@age

Hope this helps

How can I do string interpolation in JavaScript?

Supplant more for ES6 version of @Chris Nielsen's post.

String.prototype.supplant = function (o) {
  return this.replace(/\${([^\${}]*)}/g,
    (a, b) => {
      var r = o[b];
      return typeof r === 'string' || typeof r === 'number' ? r : a;
    }
  );
};

string = "How now ${color} cow? {${greeting}}, ${greeting}, moo says the ${color} cow.";

string.supplant({color: "brown", greeting: "moo"});
=> "How now brown cow? {moo}, moo, moo says the brown cow."

Pressed <button> selector

You can do this if you use an <a> tag instead of a button. I know it's not exactly what you asked for, but it might give you some other options if you cannot find a solution to this:

Borrowing from a demo from another answer here I produced this:

_x000D_
_x000D_
a {_x000D_
  display: block;_x000D_
  font-size: 18px;_x000D_
  border: 2px solid gray;_x000D_
  border-radius: 100px;_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  text-align: center;_x000D_
  line-height: 100px;_x000D_
}_x000D_
_x000D_
a:active {_x000D_
  font-size: 18px;_x000D_
  border: 2px solid green;_x000D_
  border-radius: 100px;_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
}_x000D_
_x000D_
a:target {_x000D_
  font-size: 18px;_x000D_
  border: 2px solid red;_x000D_
  border-radius: 100px;_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
}
_x000D_
<a id="btn" href="#btn">Demo</a>
_x000D_
_x000D_
_x000D_

Notice the use of :target; this will be the style applied when the element is targeted via the hash. Which also means your HTML will need to be this: <a id="btn" href="#btn">Demo</a> a link targeting itself. and the demo http://jsfiddle.net/rlemon/Awdq5/4/

Thanks to @BenjaminGruenbaum here is a better demo: http://jsfiddle.net/agzVt/

Also, as a footnote: this should really be done with JavaScript and applying / removing CSS classes from the element. It would be much less convoluted.

Design Documents (High Level and Low Level Design Documents)

High-Level Design (HLD) involves decomposing a system into modules, and representing the interfaces & invocation relationships among modules. An HLD is referred to as software architecture.

LLD, also known as a detailed design, is used to design internals of the individual modules identified during HLD i.e. data structures and algorithms of the modules are designed and documented.

Now, HLD and LLD are actually used in traditional Approach (Function-Oriented Software Design) whereas, in OOAD, the system is seen as a set of objects interacting with each other.

As per the above definitions, a high-level design document will usually include a high-level architecture diagram depicting the components, interfaces, and networks that need to be further specified or developed. The document may also depict or otherwise refer to work flows and/or data flows between component systems.

Class diagrams with all the methods and relations between classes come under LLD. Program specs are covered under LLD. LLD describes each and every module in an elaborate manner so that the programmer can directly code the program based on it. There will be at least 1 document for each module. The LLD will contain - a detailed functional logic of the module in pseudo code - database tables with all elements including their type and size - all interface details with complete API references(both requests and responses) - all dependency issues - error message listings - complete inputs and outputs for a module.

Which is the best Linux C/C++ debugger (or front-end to gdb) to help teaching programming?

Perhaps it is indirect to gdb (because it's an IDE), but my recommendations would be KDevelop. Being quite spoiled with Visual Studio's debugger (professionally at work for many years), I've so far felt the most comfortable debugging in KDevelop (as hobby at home, because I could not afford Visual Studio for personal use - until Express Edition came out). It does "look something similar to" Visual Studio compared to other IDE's I've experimented with (including Eclipse CDT) when it comes to debugging step-through, step-in, etc (placing break points is a bit awkward because I don't like to use mouse too much when coding, but it's not difficult).

Permanently hide Navigation Bar in an activity

From Google documentation:

You can hide the navigation bar on Android 4.0 and higher using the SYSTEM_UI_FLAG_HIDE_NAVIGATION flag. This snippet hides both the navigation bar and the status bar:

View decorView = getWindow().getDecorView();
// Hide both the navigation bar and the status bar.
// SYSTEM_UI_FLAG_FULLSCREEN is only available on Android 4.1 and higher, but as
// a general rule, you should design your app to hide the status bar whenever you
// hide the navigation bar.
int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
              | View.SYSTEM_UI_FLAG_FULLSCREEN;
decorView.setSystemUiVisibility(uiOptions);

http://developer.android.com/training/system-ui/navigation.html

jQuery Uncaught TypeError: Property '$' of object [object Window] is not a function

My favorite no-conflict-friendly construct:

jQuery(function($) {
  // ...
});

Calling jQuery with a function pointer is a shortcut for $(document).ready(...)

Or as we say in coffeescript:

jQuery ($) ->
  # code here

Using JsonConvert.DeserializeObject to deserialize Json to a C# POCO class

You could create a JsonConverter. See here for an example thats similar to your question.

How to extract text from a string using sed?

The pattern \d might not be supported by your sed. Try [0-9] or [[:digit:]] instead.

To only print the actual match (not the entire matching line), use a substitution.

sed -n 's/.*\([0-9][0-9]*G[0-9][0-9]*\).*/\1/p'

How to copy data from one HDFS to another HDFS?

DistCp (distributed copy) is a tool used for copying data between clusters. It uses MapReduce to effect its distribution, error handling and recovery, and reporting. It expands a list of files and directories into input to map tasks, each of which will copy a partition of the files specified in the source list.

Usage: $ hadoop distcp <src> <dst>

example: $ hadoop distcp hdfs://nn1:8020/file1 hdfs://nn2:8020/file2

file1 from nn1 is copied to nn2 with filename file2

Distcp is the best tool as of now. Sqoop is used to copy data from relational database to HDFS and vice versa, but not between HDFS to HDFS.

More info:

There are two versions available - runtime performance in distcp2 is more compared to distcp

Replacing NULL and empty string within Select statement

Try this

COALESCE(NULLIF(Address.COUNTRY,''), 'United States')

How to change current working directory using a batch file

A simpler syntax might be

pushd %root%

How to identify unused CSS definitions from multiple CSS files in a project

Chrome Developer Tools has an Audits tab which can show unused CSS selectors.

Run an audit, then, under Web Page Performance see Remove unused CSS rules

enter image description here

relative path in BAT script

either bin\Iris.exe (no leading slash - because that means start right from the root)
or \Program\bin\Iris.exe (full path)

Click a button with XPath containing partial id and title in Selenium IDE

Now that you have provided your HTML sample, we're able to see that your XPath is slightly wrong. While it's valid XPath, it's logically wrong.

You've got:

//*[contains(@id, 'ctl00_btnAircraftMapCell')]//*[contains(@title, 'Select Seat')]

Which translates into:

Get me all the elements that have an ID that contains ctl00_btnAircraftMapCell. Out of these elements, get any child elements that have a title that contains Select Seat.

What you actually want is:

//a[contains(@id, 'ctl00_btnAircraftMapCell') and contains(@title, 'Select Seat')]

Which translates into:

Get me all the anchor elements that have both: an id that contains ctl00_btnAircraftMapCell and a title that contains Select Seat.

HTML email in outlook table width issue - content is wider than the specified table width

I guess problem is in width attributes in table and td remove 'px' for example

<table border="0" cellpadding="0" cellspacing="0" width="580px" style="background-color: #0290ba;">

Should be

<table border="0" cellpadding="0" cellspacing="0" width="580" style="background-color: #0290ba;">

Bash script plugin for Eclipse?

I will reproduce a good tutorial here, because I lost this article and take some time to find it again!

Adding syntax highlighting for new languages to Eclipse with the Colorer library

Say you have an HRC file containing the syntax and lexical structure of some programming language Eclipse does not support (for example D / Iptables or any other script language).

Using the EclipseColorer plugin, you can easily add support for it.

Go to Help -> Install New Software and click Add.. In the Name field write Colorer and in the Location field write http://colorer.sf.net/eclipsecolorer/

Select the entry you’ve just added in the work with: combo box, wait for the component list to populate and click Select All

Click Next and follow the instructions

Once the plugin is installed, close Eclipse.

Copy your HRC file to [EclipseFolder]\plugins\net.sf.colorer_0.9.9\colorer\hrc\auto\types

[EclipseFolder] = /home/myusername/.eclipse

Use your favorite text editor to open

[EclipseFolder]\plugins\net.sf.colorer_0.9.9\colorer\hrc\auto\empty.hrc

Add the appropriate prototype element. For example, if your HRC file is d.hrc, empty.hrc will look like this:

<?xml version="1.0" encoding='Windows-1251'?>
 <!DOCTYPE hrc PUBLIC
 "-//Cail Lomecb//DTD Colorer HRC take5//EN"
 "http://colorer.sf.net/2003/hrc.dtd"
 >
 <hrc version="take5" xmlns="http://colorer.sf.net/2003/hrc"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://colorer.sf.net/2003/hrc http://colorer.sf.net/2003/hrc.xsd"
 ><annotation><documentation>
 'auto' is a place for include
 to colorer your own HRCs
</documentation></annotation>
    <prototype name="d" group="main" description="D">
         <location link="types/d.hrc"/>
        <filename>/\.(d)$/i</filename>
 </prototype>
</hrc>

Save the changes and close the text editor

Open Eclipse and go to Window -> Preferences -> General -> Editors -> File Associations

In the file types section, click Add.. and fill in the appropriate filetype (for example .d)

Click OK and click your newly added entry in the list

In the associated editors section, click Add.., select Colorer Editor and press OK

ok, the hard part is you must learn about HCR syntax.

You can look in

[EclipseFolder]/net.sf.colorer_0.9.9/colorer/hrc/common.jar

to learn how do it and explore many other hcr's files. At this moment I didn't find any documentation.

My gift is a basic and incomplete iptables syntax highlight. If you improve please share with me.

<?xml version="1.0" encoding="Windows-1251"?>
<!DOCTYPE hrc PUBLIC "-//Cail Lomecb//DTD Colorer HRC take5//EN" "http://colorer.sf.net/2003/hrc.dtd">
<hrc version="take5" xmlns="http://colorer.sf.net/2003/hrc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://colorer.sf.net/2003/hrc http://colorer.sf.net/2003/hrc.xsd">
    <type name="iptables">
        <annotation>
            <develby> Mario Moura - moura.mario  gmail.com</develby>
            <documentation>Support iptables EQL language</documentation>
            <appinfo>
                  <prototype name="iptables" group="database" description="iptables">
                       <location link="iptables.hrc"/>
                       <filename>/\.epl$/i</filename>
                  </prototype>  
            </appinfo>
        </annotation>

        <region name="iptablesTable" parent="def:Keyword"/>
        <region name="iptablesChainFilter" parent="def:Symbol"/>
        <region name="iptablesChainNatMangle" parent="def:NumberDec"/>
        <region name="iptablesCustomDefaultChains" parent="def:Keyword"/>
        <region name="iptablesOptions" parent="def:String"/>
        <region name="iptablesParameters" parent="def:Operator"/>
        <region name="iptablesOtherOptions" parent="def:Comment"/>
        <region name="iptablesMatchExtensions" parent="def:ParameterStrong"/>
        <region name="iptablesTargetExtensions" parent="def:FunctionKeyword"/>
        <region name="pyComment" parent="def:Comment"/>
          <region name="pyOperator" parent="def:Operator"/>
          <region name="pyDelimiter" parent="def:Symbol"/>


        <scheme name="iptablesTable">
            <keywords ignorecase="no" region="iptablesTable">
                <word name="mangle"/>
                <word name="filter"/>
                <word name="nat"/>
                <word name="as"/>
                <word name="at"/>
                <word name="asc"/>
                <word name="avedev"/>
                <word name="avg"/>
                <word name="between"/>
                <word name="by"/>
            </keywords>
        </scheme>

        <scheme name="iptablesChainFilter">
            <keywords ignorecase="no" region="iptablesChainFilter">
                <word name="FORWARD"/>
                <word name="INPUT"/>
                <word name="OUTPUT"/>
            </keywords>
        </scheme>

        <scheme name="iptablesChainNatMangle">
            <keywords ignorecase="no" region="iptablesChainNatMangle">
                <word name="PREROUTING"/>
                <word name="POSTROUTING"/>
                <word name="OUTPUT"/>
            </keywords>
        </scheme>

        <scheme name="iptablesCustomDefaultChains">
            <keywords ignorecase="no" region="iptablesCustomDefaultChains">
                <word name="CHTTP"/>
                <word name="CHTTPS"/>
                <word name="CSSH"/>
                <word name="CDNS"/>
                <word name="CFTP"/>
                <word name="CGERAL"/>
                <word name="CICMP"/>
            </keywords>
        </scheme>


        <scheme name="iptablesOptions">
            <keywords ignorecase="no" region="iptablesOptions">
                <word name="-A"/>
                <word name="--append"/>
                <word name="-D"/>
                <word name="--delete"/>
                <word name="-I"/>
                <word name="--insert"/>
                <word name="-R"/>
                <word name="--replace"/>
                <word name="-L"/>
                <word name="--list"/>
                <word name="-F"/>
                <word name="--flush"/>
                <word name="-Z"/>
                <word name="--zero"/>
                <word name="-N"/>
                <word name="--new-chain"/>
                <word name="-X"/>
                <word name="--delete-chain"/>
                <word name="-P"/>
                <word name="--policy"/>
                <word name="-E"/>
                <word name="--rename-chain"/>
            </keywords>
        </scheme>

        <scheme name="iptablesParameters">
            <keywords ignorecase="no" region="iptablesParameters">
                <word name="-p"/>
                <word name="--protocol"/>
                <word name="-s"/>
                <word name="--source"/>
                <word name="-d"/>
                <word name="--destination"/>
                <word name="-j"/>
                <word name="--jump"/>
                <word name="-g"/>
                <word name="--goto"/>
                <word name="-i"/>
                <word name="--in-interface"/>
                <word name="-o"/>
                <word name="--out-interface"/>
                <word name="-f"/>
                <word name="--fragment"/>
                <word name="-c"/>
                <word name="--set-counters"/>
            </keywords>
        </scheme>

        <scheme name="iptablesOtherOptions">
            <keywords ignorecase="no" region="iptablesOtherOptions">
                <word name="-v"/>
                <word name="--verbose"/>
                <word name="-n"/>
                <word name="--numeric"/>
                <word name="-x"/>
                <word name="--exact"/>

                <word name="--line-numbers"/>
                <word name="--modprobe"/>
            </keywords>
        </scheme>

        <scheme name="iptablesMatchExtensions">
            <keywords ignorecase="no" region="iptablesMatchExtensions">
                <word name="account"/>
                <word name="addrtype"/>
                <word name="childlevel"/>
                <word name="comment"/>
                <word name="connbytes"/>
                <word name="connlimit"/>
                <word name="connmark"/>
                <word name="connrate"/>
                <word name="conntrack"/>
                <word name="dccp"/>
                <word name="dscp"/>
                <word name="dstlimit"/>
                <word name="ecn"/>
                <word name="esp"/>
                <word name="hashlimit"/>
                <word name="helper"/>
                <word name="icmp"/>
                <word name="ipv4options"/>
                <word name="length"/>
                <word name="limit"/>
                <word name="mac"/>
                <word name="mark"/>
                <word name="mport"/>
                <word name="multiport"/>
                <word name="nth"/>
                <word name="osf"/>
                <word name="owner"/>
                <word name="physdev"/>
                <word name="pkttype"/>
                <word name="policy"/>
                <word name="psd"/>
                <word name="quota"/>
                <word name="realm"/>
                <word name="recent"/>
                <word name="sctp"/>
                <word name="set"/>
                <word name="state"/>
                <word name="string"/>
                <word name="tcp"/>
                <word name="tcpmss"/>
                <word name="tos"/>
                <word name="u32"/>
                <word name="udp"/>                                                                              
            </keywords>
        </scheme>


    <scheme name="iptablesTargetExtensions">
            <keywords ignorecase="no" region="iptablesTargetExtensions">
                <word name="BALANCE"/>
                <word name="CLASSIFY"/>
                <word name="CLUSTERIP"/>
                <word name="CONNMARK"/>
                <word name="DNAT"/>
                <word name="DSCP"/>
                <word name="ECN"/>
                <word name="IPMARK"/>
                <word name="IPV4OPTSSTRIP"/>
                <word name="LOG"/>
                <word name="MARK"/>
                <word name="MASQUERADE"/>
                <word name="MIRROR"/>
                <word name="NETMAP"/>
                <word name="NFQUEUE"/>
                <word name="NOTRACK"/>
                <word name="REDIRECT"/>
                <word name="REJECT"/>
                <word name="SAME"/>
                <word name="SET"/>
                <word name="SNAT"/>
                <word name="TARPIT"/>
                <word name="TCPMSS"/>
                <word name="TOS"/>
                <word name="TRACE"/>
                <word name="TTL"/>
                <word name="ULOG"/>
                <word name="XOR"/>                                                                          
            </keywords>
        </scheme>



        <scheme name="iptables">
              <inherit scheme="iptablesTable"/>
              <inherit scheme="iptablesChainFilter"/>
              <inherit scheme="iptablesChainNatMangle"/>
              <inherit scheme="iptablesCustomDefaultChains"/>                                     
              <inherit scheme="iptablesOptions"/>
              <inherit scheme="iptablesParameters"/>
              <inherit scheme="iptablesOtherOptions"/>
              <inherit scheme="iptablesMatchExtensions"/>
              <inherit scheme="iptablesTargetExtensions"/>

   <!-- python operators : http://docs.python.org/ref/keywords.html -->
   <keywords region="pyOperator">
    <symb name="+"/>
    <symb name="-"/>
    <symb name="*"/>
    <symb name="**"/>
    <symb name="/"/>
    <symb name="//"/>
    <symb name="%"/>
    <symb name="&lt;&lt;"/>
    <symb name=">>"/>
    <symb name="&amp;"/>
    <symb name="|"/>
    <symb name="^"/>
    <symb name="~"/>
    <symb name="&lt;"/>
    <symb name=">"/>
    <symb name="&lt;="/>
    <symb name=">="/>
    <symb name="=="/>
    <symb name="!="/>
    <symb name="&lt;>"/>
   </keywords>


   <!-- basic python comment - consider it everything after # till the end of line -->
   <block start="/#/" end="/$/" region="pyComment" scheme="def:Comment"/>

   <block start="/(u|U)?(r|R)?(&quot;{3}|&apos;{3})/" end="/\y3/"
      region00="def:PairStart" region10="def:PairEnd"
      scheme="def:Comment" region="pyComment" />
      <!-- TODO: better scheme for multiline comments/docstrings -->
      <!-- scheme="StringCommon" region="pyString" /> -->


   <!-- python delimiters : http://docs.python.org/ref/delimiters.html -->
   <keywords region="pyDelimiter">
    <symb name="+"/>
    <symb name="("/>
    <symb name=")"/>
    <symb name="["/>
    <symb name="]"/>
    <symb name="{"/>
    <symb name="}"/>
    <symb name="@"/>
    <symb name=","/>
    <symb name=":"/>
    <symb name="."/>
    <symb name="`"/>
    <symb name="="/>
    <symb name=";"/>
    <symb name="+="/>
    <symb name="-="/>
    <symb name="*="/>
    <symb name="/="/>
    <symb name="//="/>
    <symb name="%="/>
    <symb name="&amp;="/>
    <symb name="|="/>
    <symb name="^="/>
    <symb name=">>="/>
    <symb name="&lt;&lt;="/>
    <symb name="**="/>
   </keywords>



        </scheme>
    </type>

After this you must save the file as iptables.hcr and add inside the jar:

[EclipseFolder]/net.sf.colorer_0.9.9/colorer/hrc/common.jar

Based in: https://ohadsc.wordpress.com/2012/05/26/adding-syntax-highlighting-for-new-languages-to-eclipse-with-the-colorer-library/

How to use sed to extract substring

You should not parse XML using tools like sed, or awk. It's error-prone.

If input changes, and before name parameter you will get new-line character instead of space it will fail some day producing unexpected results.

If you are really sure, that your input will be always formated this way, you can use cut. It's faster than sed and awk:

cut -d'"' -f2 < input.txt

It will be better to first parse it, and extract only parameter name attribute:

xpath -q -e //@name input.txt | cut -d'"' -f2

To learn more about xpath, see this tutorial: http://www.w3schools.com/xpath/

error C4996: 'scanf': This function or variable may be unsafe in c programming

Another way to suppress the error: Add this line at the top in C/C++ file:

#define _CRT_SECURE_NO_WARNINGS

php: loop through json array

Use json_decode to convert the JSON string to a PHP array, then use normal PHP array functions on it.

$json = '[{"var1":"9","var2":"16","var3":"16"},{"var1":"8","var2":"15","var3":"15"}]';
$data = json_decode($json);

var_dump($data[0]['var1']); // outputs '9'

font size in html code

font-size:35px;

So like this:

<html>
  <tr>
  <td style="padding-left:5px;padding-bottom:3px;"> 
    <strong style="font-size:35px;">Datum:</strong>
    <br/>
    November 2010 
  </td>
  </tr>
</html>

Although inline styles are a bad practice and you should class things. Also you should use a <strong></strong> tag instead of <b></b>

Public free web services for testing soap client

There is a bunch on here:

http://www.webservicex.net/WS/wscatlist.aspx

Just google for "Free WebService" or "Open WebService" and you'll find tons of open SOAP endpoints.

Remember, you can get a WSDL from any ASMX endpoint by adding ?WSDL to the url.

How do I cancel an HTTP fetch() request?

As for now there is no proper solution, as @spro says.

However, if you have an in-flight response and are using ReadableStream, you can close the stream to cancel the request.

fetch('http://example.com').then((res) => {
  const reader = res.body.getReader();

  /*
   * Your code for reading streams goes here
   */

  // To abort/cancel HTTP request...
  reader.cancel();
});

How to tell if UIViewController's view is visible

There are a couple of issues with the above solutions. If you are using, for example, a UISplitViewController, the master view will always return true for

if(viewController.isViewLoaded && viewController.view.window) {
    //Always true for master view in split view controller
}

Instead, take this simple approach which seems to work well in most, if not all cases:

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];

    //We are now invisible
    self.visible = false;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

    //We are now visible
    self.visible = true;
}

Changing an AIX password via script?

You can try:

echo "USERNAME:NEWPASSWORD" | chpasswd

mysql select from n last rows

because it is autoincrement, here's my take:

Select * from tbl 
where certainconditionshere 
and autoincfield >= (select max(autoincfield) from tbl) - $n

A CORS POST request works from plain JavaScript, but why not with jQuery?

You are sending "params" in js: request.send(params);

but "data" in jquery". Is data defined?: data:data,

Also, you have an error in the URL:

$.ajax( {url:url,
         type:"POST",
         dataType:"json",
         data:data, 
         success:function(data, textStatus, jqXHR) {alert("success");},
         error: function(jqXHR, textStatus, errorThrown) {alert("failure");}
});

You are mixing the syntax with the one for $.post


Update: I was googling around based on monsur answer, and I found that you need to add Access-Control-Allow-Headers: Content-Type (below is the full paragraph)

http://metajack.im/2010/01/19/crossdomain-ajax-for-xmpp-http-binding-made-easy/

How CORS Works

CORS works very similarly to Flash's crossdomain.xml file. Basically, the browser will send a cross-domain request to a service, setting the HTTP header Origin to the requesting server. The service includes a few headers like Access-Control-Allow-Origin to indicate whether such a request is allowed.

For the BOSH connection managers, it is enough to specify that all origins are allowed, by setting the value of Access-Control-Allow-Origin to *. The Content-Type header must also be white-listed in the Access-Control-Allow-Headers header.

Finally, for certain types of requests, including BOSH connection manager requests, the permissions check will be pre-flighted. The browser will do an OPTIONS request and expect to get back some HTTP headers that indicate which origins are allowed, which methods are allowed, and how long this authorization will last. For example, here is what the Punjab and ejabberd patches I did return for OPTIONS:

Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Headers: Content-Type 
Access-Control-Max-Age: 86400

Using Caps Lock as Esc in Mac OS X

You can also use DoubleCommand to remap this, and other keys.

IIRC, it will map Caps Lock to Esc.

How to use sessions in an ASP.NET MVC 4 application?

Due to the stateless nature of the web, sessions are also an extremely useful way of persisting objects across requests by serialising them and storing them in a session.

A perfect use case of this could be if you need to access regular information across your application, to save additional database calls on each request, this data can be stored in an object and unserialised on each request, like so:

Our reusable, serializable object:

[Serializable]
public class UserProfileSessionData
{
    public int UserId { get; set; }

    public string EmailAddress { get; set; }

    public string FullName { get; set; }
}

Use case:

public class LoginController : Controller {

    [HttpPost]
    public ActionResult Login(LoginModel model)
    {
        if (ModelState.IsValid)
        {
            var profileData = new UserProfileSessionData {
                UserId = model.UserId,
                EmailAddress = model.EmailAddress,
                FullName = model.FullName
            }

            this.Session["UserProfile"] = profileData;
        }
    }

    public ActionResult LoggedInStatusMessage()
    {
        var profileData = this.Session["UserProfile"] as UserProfileSessionData;

        /* From here you could output profileData.FullName to a view and
        save yourself unnecessary database calls */
    }

}

Once this object has been serialised, we can use it across all controllers without needing to create it or query the database for the data contained within it again.

Inject your session object using Dependency Injection

In a ideal world you would 'program to an interface, not implementation' and inject your serializable session object into your controller using your Inversion of Control container of choice, like so (this example uses StructureMap as it's the one I'm most familiar with).

public class WebsiteRegistry : Registry
{
    public WebsiteRegistry()
    {
        this.For<IUserProfileSessionData>().HybridHttpOrThreadLocalScoped().Use(() => GetUserProfileFromSession());   
    }

    public static IUserProfileSessionData GetUserProfileFromSession()
    {
        var session = HttpContext.Current.Session;
        if (session["UserProfile"] != null)
        {
            return session["UserProfile"] as IUserProfileSessionData;
        }

        /* Create new empty session object */
        session["UserProfile"] = new UserProfileSessionData();

        return session["UserProfile"] as IUserProfileSessionData;
    }
}

You would then register this in your Global.asax.cs file.

For those that aren't familiar with injecting session objects, you can find a more in-depth blog post about the subject here.

A word of warning:

It's worth noting that sessions should be kept to a minimum, large sessions can start to cause performance issues.

It's also recommended to not store any sensitive data in them (passwords, etc).

Checking session if empty or not

Use this if the session variable emp_num will store a string:

 if (!string.IsNullOrEmpty(Session["emp_num"] as string))
 {
                //The code
 }

If it doesn't store a string, but some other type, you should just check for null before accessing the value, as in your second example.

How to remove the default arrow icon from a dropdown list (select element)?

select{
padding: 11px 50px 11px 10px;
background: rgba(255,255,255,1);
border-radius: 7px;
-webkit-border-radius: 7px;
-moz-border-radius: 7px;
border: 0;
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
color: #8ba2d4;

}

Divide a number by 3 without using *, /, +, -, % operators

Here's my solution:

public static int div_by_3(long a) {
    a <<= 30;
    for(int i = 2; i <= 32 ; i <<= 1) {
        a = add(a, a >> i);
    }
    return (int) (a >> 32);
}

public static long add(long a, long b) {
    long carry = (a & b) << 1;
    long sum = (a ^ b);
    return carry == 0 ? sum : add(carry, sum);
}

First, note that

1/3 = 1/4 + 1/16 + 1/64 + ...

Now, the rest is simple!

a/3 = a * 1/3  
a/3 = a * (1/4 + 1/16 + 1/64 + ...)
a/3 = a/4 + a/16 + 1/64 + ...
a/3 = a >> 2 + a >> 4 + a >> 6 + ...

Now all we have to do is add together these bit shifted values of a! Oops! We can't add though, so instead, we'll have to write an add function using bit-wise operators! If you're familiar with bit-wise operators, my solution should look fairly simple... but just in-case you aren't, I'll walk through an example at the end.

Another thing to note is that first I shift left by 30! This is to make sure that the fractions don't get rounded off.

11 + 6

1011 + 0110  
sum = 1011 ^ 0110 = 1101  
carry = (1011 & 0110) << 1 = 0010 << 1 = 0100  
Now you recurse!

1101 + 0100  
sum = 1101 ^ 0100 = 1001  
carry = (1101 & 0100) << 1 = 0100 << 1 = 1000  
Again!

1001 + 1000  
sum = 1001 ^ 1000 = 0001  
carry = (1001 & 1000) << 1 = 1000 << 1 = 10000  
One last time!

0001 + 10000
sum = 0001 ^ 10000 = 10001 = 17  
carry = (0001 & 10000) << 1 = 0

Done!

It's simply carry addition that you learned as a child!

111
 1011
+0110
-----
10001

This implementation failed because we can not add all terms of the equation:

a / 3 = a/4 + a/4^2 + a/4^3 + ... + a/4^i + ... = f(a, i) + a * 1/3 * 1/4^i
f(a, i) = a/4 + a/4^2 + ... + a/4^i

Suppose the reslut of div_by_3(a) = x, then x <= floor(f(a, i)) < a / 3. When a = 3k, we get wrong answer.

How can I add a hint or tooltip to a label in C# Winforms?

Just to share my idea...

I created a custom class to inherit the Label class. I added a private variable assigned as a Tooltip class and a public property, TooltipText. Then, gave it a MouseEnter delegate method. This is an easy way to work with multiple Label controls and not have to worry about assigning your Tooltip control for each Label control.

    public partial class ucLabel : Label
    {
        private ToolTip _tt = new ToolTip();

        public string TooltipText { get; set; }

        public ucLabel() : base() {
            _tt.AutoPopDelay = 1500;
            _tt.InitialDelay = 400;
//            _tt.IsBalloon = true;
            _tt.UseAnimation = true;
            _tt.UseFading = true;
            _tt.Active = true;
            this.MouseEnter += new EventHandler(this.ucLabel_MouseEnter);
        }

        private void ucLabel_MouseEnter(object sender, EventArgs ea)
        {
            if (!string.IsNullOrEmpty(this.TooltipText))
            {
                _tt.SetToolTip(this, this.TooltipText);
                _tt.Show(this.TooltipText, this.Parent);
            }
        }
    }

In the form or user control's InitializeComponent method (the Designer code), reassign your Label control to the custom class:

this.lblMyLabel = new ucLabel();

Also, change the private variable reference in the Designer code:

private ucLabel lblMyLabel;

How to show grep result with complete path or file name

It is similar to BVB Media's answer.

grep -rnw 'blablabla' `pwd`

It works fine on my ubuntu bash.

Subset a dataframe by multiple factor levels

You can use %in%

  data[data$Code %in% selected,]
  Code Value
1    A     1
2    B     2
7    A     3
8    A     4

Typescript: How to define type for a function callback (as any function type, not universal any) used in a method parameter

Here's an example of a function that accepts a callback

const sqk = (x: number, callback: ((_: number) => number)): number => {
  // callback will receive a number and expected to return a number
  return callback (x * x);
}

// here our callback will receive a number
sqk(5, function(x) {
  console.log(x); // 25
  return x;       // we must return a number here
});

If you don't care about the return values of callbacks (most people don't know how to utilize them in any effective way), you can use void

const sqk = (x: number, callback: ((_: number) => void)): void => {
  // callback will receive a number, we don't care what it returns
  callback (x * x);
}

// here our callback will receive a number
sqk(5, function(x) {
  console.log(x); // 25
  // void
});

Note, the signature I used for the callback parameter ...

const sqk = (x: number, callback: ((_: number) => number)): number

I would say this is a TypeScript deficiency because we are expected to provide a name for the callback parameters. In this case I used _ because it's not usable inside the sqk function.

However, if you do this

// danger!! don't do this
const sqk = (x: number, callback: ((number) => number)): number

It's valid TypeScript, but it will interpreted as ...

// watch out! typescript will think it means ...
const sqk = (x: number, callback: ((number: any) => number)): number

Ie, TypeScript will think the parameter name is number and the implied type is any. This is obviously not what we intended, but alas, that is how TypeScript works.

So don't forget to provide the parameter names when typing your function parameters... stupid as it might seem.

How to create a fixed-size array of objects

If what you want is a fixed size array, and initialize it with nil values, you can use an UnsafeMutableBufferPointer, allocate memory for 64 nodes with it, and then read/write from/to the memory by subscripting the pointer type instance. This also has the benefit of avoiding checking if the memory must be reallocated, which Array does. I would however be surprised if the compiler doesn't optimize that away for arrays that don't have any more calls to methods that may require resizing, other than at the creation site.

let count = 64
let sprites = UnsafeMutableBufferPointer<SKSpriteNode>.allocate(capacity: count)

for i in 0..<count {
    sprites[i] = ...
}

for sprite in sprites {
    print(sprite!)
}

sprites.deallocate()

This is however not very user friendly. So, let's make a wrapper!

class ConstantSizeArray<T>: ExpressibleByArrayLiteral {
    
    typealias ArrayLiteralElement = T
    
    private let memory: UnsafeMutableBufferPointer<T>
    
    public var count: Int {
        get {
            return memory.count
        }
    }
    
    private init(_ count: Int) {
        memory = UnsafeMutableBufferPointer.allocate(capacity: count)
    }
    
    public convenience init(count: Int, repeating value: T) {
        self.init(count)
        
        memory.initialize(repeating: value)
    }
    
    public required convenience init(arrayLiteral: ArrayLiteralElement...) {
        self.init(arrayLiteral.count)
        
        memory.initialize(from: arrayLiteral)
    }
    
    deinit {
        memory.deallocate()
    }
    
    public subscript(index: Int) -> T {
        set(value) {
            precondition((0...endIndex).contains(index))
            
            memory[index] = value;
        }
        get {
            precondition((0...endIndex).contains(index))
            
            return memory[index]
        }
    }
}

extension ConstantSizeArray: MutableCollection {
    public var startIndex: Int {
        return 0
    }
    
    public var endIndex: Int {
        return count - 1
    }
    
    func index(after i: Int) -> Int {
        return i + 1;
    }
}

Now, this is a class, and not a structure, so there's some reference counting overhead incurred here. You can change it to a struct instead, but because Swift doesn't provide you with an ability to use copy initializers and deinit on structures, you'll need a deallocation method (func release() { memory.deallocate() }), and all copied instances of the structure will reference the same memory.

Now, this class may just be good enough. Its use is simple:

let sprites = ConstantSizeArray<SKSpriteNode?>(count: 64, repeating: nil)

for i in 0..<sprites.count {
    sprite[i] = ...
}

for sprite in sprites {
    print(sprite!)
}

For more protocols to implement conformance to, see the Array documentation (scroll to Relationships).

How to find list intersection?

You can also use a counter! It doesn't preserve the order, but it'll consider the duplicates:

>>> from collections import Counter
>>> a = [1,2,3,4,5]
>>> b = [1,3,5,6]
>>> d1, d2 = Counter(a), Counter(b)
>>> c = [n for n in d1.keys() & d2.keys() for _ in range(min(d1[n], d2[n]))]
>>> print(c)
[1,3,5]

Where to find the complete definition of off_t type?

Since this answer still gets voted up, I want to point out that you should almost never need to look in the header files. If you want to write reliable code, you're much better served by looking in the standard. A better question than "how is off_t defined on my machine" is "how is off_t defined by the standard?". Following the standard means that your code will work today and tomorrow, on any machine.

In this case, off_t isn't defined by the C standard. It's part of the POSIX standard, which you can browse here.

Unfortunately, off_t isn't very rigorously defined. All I could find to define it is on the page on sys/types.h:

blkcnt_t and off_t shall be signed integer types.

This means that you can't be sure how big it is. If you're using GNU C, you can use the instructions in the answer below to ensure that it's 64 bits. Or better, you can convert to a standards defined size before putting it on the wire. This is how projects like Google's Protocol Buffers work (although that is a C++ project).


So, I think "where do I find the definition in my header files" isn't the best question. But, for completeness here's the answer:

On my machine (and most machines using glibc) you'll find the definition in bits/types.h (as a comment says at the top, never directly include this file), but it's obscured a bit in a bunch of macros. An alternative to trying to unravel them is to look at the preprocessor output:

#include <stdio.h>
#include <sys/types.h>

int main(void) {
  off_t blah;

  return 0;
}

And then:

$ gcc -E sizes.c  | grep __off_t
typedef long int __off_t;
....

However, if you want to know the size of something, you can always use the sizeof() operator.

Edit: Just saw the part of your question about the __. This answer has a good discussion. The key point is that names starting with __ are reserved for the implementation (so you shouldn't start your own definitions with __).

how to show only even or odd rows in sql server 2008?

FASTER: Bitwise instead of modulus.

select * from MEN where (id&1)=0;

Random question: Do you actually use uppercase table names? Usually uppercase is reserved for keywords. (By convention)

Maven build Compilation error : Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project Maven

for it was comming because of java version mismatch ,so I have corrected it and i am able to build the war file.hope it will help someone

    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>

SET NAMES utf8 in MySQL?

Getting encoding right is really tricky - there are too many layers:

  • Browser
  • Page
  • PHP
  • MySQL

The SQL command "SET CHARSET utf8" from PHP will ensure that the client side (PHP) will get the data in utf8, no matter how they are stored in the database. Of course, they need to be stored correctly first.

DDL definition vs. real data

Encoding defined for a table/column doesn't really mean that the data are in that encoding. If you happened to have a table defined as utf8 but stored as differtent encoding, then MySQL will treat them as utf8 and you're in trouble. Which means you have to fix this first.

What to check

You need to check in what encoding the data flow at each layer.

  • Check HTTP headers, headers.
  • Check what's really sent in body of the request.
  • Don't forget that MySQL has encoding almost everywhere:
    • Database
    • Tables
    • Columns
    • Server as a whole
    • Client
      Make sure that there's the right one everywhere.

Conversion

If you receive data in e.g. windows-1250, and want to store in utf-8, then use this SQL before storing:

SET NAMES 'cp1250';

If you have data in DB as windows-1250 and want to retreive utf8, use:

SET CHARSET 'utf8';

Few more notes:

  • Don't rely on too "smart" tools to show the data. E.g. phpMyAdmin does (was doing when I was using it) encoding really bad. And it goes through all the layers so it's hard to find out.
  • Also, Internet Explorer had really stupid behavior of "guessing" the encoding based on weird rules.
  • Use simple editors where you can switch encoding. I recommend MySQL Workbench.

CSS to set A4 paper size

CSS

body {
  background: rgb(204,204,204); 
}
page[size="A4"] {
  background: white;
  width: 21cm;
  height: 29.7cm;
  display: block;
  margin: 0 auto;
  margin-bottom: 0.5cm;
  box-shadow: 0 0 0.5cm rgba(0,0,0,0.5);
}
@media print {
  body, page[size="A4"] {
    margin: 0;
    box-shadow: 0;
  }
}

HTML

<page size="A4"></page>
<page size="A4"></page>
<page size="A4"></page>

DEMO

Setting PHP tmp dir - PHP upload not working

I struggled with this issue for a long time... My solution was to modify the php.ini file, in the folder that contained the php script. This was important, as modifying the php.ini at the root did not resolve the problem (I have a php.ini in each folder for granular control). The relevant entries in my php.ini looked like this.... (the output_buffering is not likely needed for this issue)

output_buffering = On 
upload_max_filesize = 20M 
post_max_size = 21M

SQL Server: Extract Table Meta-Data (description, fields and their data types)

To get the description data, you unfortunately have to use sysobjects/syscolumns to get the ids:

SELECT      u.name + '.' + t.name AS [table],
            td.value AS [table_desc],
            c.name AS [column],
            cd.value AS [column_desc]
FROM        sysobjects t
INNER JOIN  sysusers u
    ON      u.uid = t.uid
LEFT OUTER JOIN sys.extended_properties td
    ON      td.major_id = t.id
    AND     td.minor_id = 0
    AND     td.name = 'MS_Description'
INNER JOIN  syscolumns c
    ON      c.id = t.id
LEFT OUTER JOIN sys.extended_properties cd
    ON      cd.major_id = c.id
    AND     cd.minor_id = c.colid
    AND     cd.name = 'MS_Description'
WHERE t.type = 'u'
ORDER BY    t.name, c.colorder

You can do it with info-schema, but you'd have to concatenate etc to call OBJECT_ID() - so what would be the point?

How to insert a line break <br> in markdown

I know this post is about adding a single line break but I thought I would mention that you can create multiple line breaks with the backslash (\) character:

Hello
\
\
\
World!

This would result in 3 new lines after "Hello". To clarify, that would mean 2 empty lines between "Hello" and "World!". It would display like this:


Hello



World!



Personally I find this cleaner for a large number of line breaks compared to using <br>.

Note that backslashes are not recommended for compatibility reasons. So this may not be supported by your Markdown parser but it's handy when it is.

Make the current Git branch a master branch

The problem with the other two answers is that the new master doesn't have the old master as an ancestor, so when you push it, everyone else will get messed up. This is what you want to do:

git checkout better_branch
git merge --strategy=ours master    # keep the content of this branch, but record a merge
git checkout master
git merge better_branch             # fast-forward master up to the merge

If you want your history to be a little clearer, I'd recommend adding some information to the merge commit message to make it clear what you've done. Change the second line to:

git merge --strategy=ours --no-commit master
git commit          # add information to the template merge message

How to attach a file using mail command on Linux?

With mailx you can do:

mailx -s "My Subject"  -a ./mail_att.csv -S [email protected]  [email protected] < ./mail_body.txt

This worked great on our GNU Linux servers, but unfortunately my dev environment is Mac OsX which only has a crummy old BSD version of mailx. Normally I use Coreutils to get better versions of unix commands than the Mac BSD ones, but mailx is not in Coreutils.

I found a solution from notpeter in an unrelated thread (https://serverfault.com/questions/196001/using-unix-mail-mailx-with-a-modern-mail-server-imap-instead-of-mbox-files) which was to download the Heirloom mailx OSX binary package from http://www.tramm.li/iWiki/HeirloomNotes.html. It has a more featured mailx which can handle the above command syntax.

(Apologies for poor cross linking linking or attribution, I'm new to the site.)

Compiler error: memset was not declared in this scope

You should include <string.h> (or its C++ equivalent, <cstring>).

How to override !important?

This can help too

td[style] {height: 50px !important;}

This will override any inline style

A project with an Output Type of Class Library cannot be started directly

Suppose you have multiple project in the solution. Select the project that you want to view in browser and select 'Set as StartUp Project'. In your multiple project soln which was the main, the visual studio was unable to identify. this was the main problem.

Logging POST data from $request_body

Try echo_read_request_body.

"echo_read_request_body ... Explicitly reads request body so that the $request_body variable will always have non-empty values (unless the body is so big that it has been saved by Nginx to a local temporary file)."

location /log {
  log_format postdata $request_body;
  access_log /mnt/logs/nginx/my_tracking.access.log postdata;
  echo_read_request_body;
}

How to prevent null values inside a Map and null fields inside a bean from getting serialized through Jackson

my solution, hope help
custom ObjectMapper and config to spring xml(register message conveters)

public class PyResponseConfigObjectMapper extends ObjectMapper {
public PyResponseConfigObjectMapper() {
    disable(SerializationFeature.WRITE_NULL_MAP_VALUES); //map no_null
    setSerializationInclusion(JsonInclude.Include.NON_NULL); // bean no_null
}

}

Python Requests library redirect new url

For python3.5, you can use the following code:

import urllib.request
res = urllib.request.urlopen(starturl)
finalurl = res.geturl()
print(finalurl)

jQuery set radio button

Try this:

$("#" + newcol).attr("checked", "checked");

I've had issues with attr("checked", true), so I tend to use the above instead.

Also, if you have the ID then you don't need that other stuff for selection. An ID is unique.

Prevent Bootstrap Modal from disappearing when clicking outside or pressing escape?

Just add data-backdrop="static" and data-keyboard="false" attributes to that modal.

Eg.

<a data-controls-modal="your_div_id" data-backdrop="static" data-keyboard="false" href="#">

how to loop through rows columns in excel VBA Macro

This one is similar to @Wilhelm's solution. The loop automates based on a range created by evaluating the populated date column. This was slapped together based strictly on the conversation here and screenshots.

Please note: This assumes that the headers will always be on the same row (row 8). Changing the first row of data (moving the header up/down) will cause the range automation to break unless you edit the range block to take in the header row dynamically. Other assumptions include that VOL and CAPACITY formula column headers are named "Vol" and "Cap" respectively.

Sub Loop3()

Dim dtCnt As Long
Dim rng As Range
Dim frmlas() As String

Application.ScreenUpdating = False

'The following code block sets up the formula output range
dtCnt = Sheets("Loop").Range("A1048576").End(xlUp).Row              'lowest date column populated
endHead = Sheets("Loop").Range("XFD8").End(xlToLeft).Column         'right most header populated
Set rng = Sheets("Loop").Range(Cells(9, 2), Cells(dtCnt, endHead))  'assigns range for automation

ReDim frmlas(1)      'array assigned to formula strings
    'VOL column formula
frmlas(0) = "VOL FORMULA"
    'CAPACITY column formula
frmlas(1) = "CAP FORMULA"

For i = 1 To rng.Columns.count
If rng(0, i).Value = "Vol" Then         'checks for volume formula column
    For j = 1 To rng.Rows.count
        rng(j, i).Formula= frmlas(0)    'inserts volume formula
    Next j
ElseIf rng(0, i).Value = "Cap" Then     'checks for capacity formula column
    For j = 1 To rng.Rows.count
        rng(j, i).Formula = frmlas(1)   'inserts capacity formula
    Next j
End If
Next i

Application.ScreenUpdating = True

End Sub

Return date as ddmmyyyy in SQL Server

Just for the record, since SQL 2012 you can use FORMAT, as simple as:

SELECT FORMAT(GETDATE(), 'ddMMyyyy')

(op question is specific about SQL 2008)

How do I get Fiddler to stop ignoring traffic to localhost?

Fiddler's website addresses this question directly.

There are several suggested workarounds, but the most straightforward is simply to use the machine name rather than "localhost" or "127.0.0.1":

http://machinename/mytestpage.aspx

How to do a for loop in windows command line?

This may help you find what you're looking for... Batch script loop

My answer is as follows:

@echo off
:start
set /a var+=1
if %var% EQU 100 goto end
:: Code you want to run goes here
goto start

:end
echo var has reached %var%.
pause
exit

The first set of commands under the start label loops until a variable, %var% reaches 100. Once this happens it will notify you and allow you to exit. This code can be adapted to your needs by changing the 100 to 17 and putting your code or using a call command followed by the batch file's path (Shift+Right Click on file and select "Copy as Path") where the comment is placed.

Sort matrix according to first column in R

The accepted answer works like a charm unless you're applying it to a vector. Since a vector is non-recursive, you'll get an error like this

$ operator is invalid for atomic vectors

You can use [ in that case

foo[order(foo["V1"]),]

Visual Studio 2010 always thinks project is out of date, but nothing has changed

I'm on Visual Studio 2013 and just updated to the Windows 10 May 2019 update and compiling suddenly had to be redone every time, regardless of changes. Tried renaming the pch to ProjectName instead of TargetName, looked for missing files with the detailed log and that Python script, but in the end it was my time was not synced with MS's servers (by like milliseconds).

What resolved this for me was

  • "Adjust date and time" in the control panel
  • "Sync Now"

Now my projects don't need to be recompiled for no reason.

Rename a table in MySQL

ALTER TABLE `group` RENAME `member`

group is keyword so you must have to enclose into group

Right way to write JSON deserializer in Spring or extend it

With Spring MVC 4.2.1.RELEASE, you need to use the new Jackson2 dependencies as below for the Deserializer to work.

Dont use this

<dependency>  
            <groupId>org.codehaus.jackson</groupId>  
            <artifactId>jackson-mapper-asl</artifactId>  
            <version>1.9.12</version>  
        </dependency>  

Use this instead.

<dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.2.2</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.2.2</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.2.2</version>
        </dependency>  

Also use com.fasterxml.jackson.databind.JsonDeserializer and com.fasterxml.jackson.databind.annotation.JsonDeserialize for the deserialization and not the classes from org.codehaus.jackson

Java: using switch statement with enum under subclass

Change it to this:

switch (enumExample) {
    case VALUE_A: {
        //..
        break;
    }
}

The clue is in the error. You don't need to qualify case labels with the enum type, just its value.

How to disable Home and other system buttons in Android?

First of, please think long and hard if you really want to disable the Home button or any other button for that matter (e.g. the Back button), this is not something that should be done (at least most of the times, this is a bad design). I can speak only for myself, but if I downloaded an app that doesn't let me do something like clicking an OS button, the next thing I do is uninstall that app and leave a very bad review. I also believe that your app will not be featured on the App Store.

Now...

Notice that MX Player is asking permission to draw on top of other applications:MX Player permissions
Since you cannot override the Home button on Android device (at least no in the latest OS versions). MX Player draws itself on top of your launcher when you "lock" the app and clicks on the Home button.
To see an example of that is a bit more simple and straight forward to understand, you can see the Facebook Messenger App.

As I was asked to provide some more info about MX Player Status Bar and Navigation Bar "overriding", I'm editing my answer to include these topics too.

First thing first, MX Player is using Immersive Full-Screen Mode (DevBytes Video) on KitKat.
Android 4.4 (API Level 19) introduces a new SYSTEM_UI_FLAG_IMMERSIVE flag for setSystemUiVisibility() that lets your app go truly "full screen." This flag, when combined with the SYSTEM_UI_FLAG_HIDE_NAVIGATION and SYSTEM_UI_FLAG_FULLSCREEN flags, hides the navigation and status bars and lets your app capture all touch events on the screen.

When immersive full-screen mode is enabled, your activity continues to receive all touch events. The user can reveal the system bars with an inward swipe along the region where the system bars normally appear. This clears the SYSTEM_UI_FLAG_HIDE_NAVIGATION flag (and the SYSTEM_UI_FLAG_FULLSCREEN flag, if applied) so the system bars become visible. This also triggers your View.OnSystemUiVisibilityChangeListener, if set. However, if you'd like the system bars to automatically hide again after a few moments, you can instead use the SYSTEM_UI_FLAG_IMMERSIVE_STICKY flag. Note that the "sticky" version of the flag doesn't trigger any listeners, as system bars temporarily shown in this mode are in a transient state.

Second: Hiding the Status Bar
Third: Hiding the Navigation Bar
Please note that although using immersive full screen is only for KitKat, hiding the Status Bar and Navigation Bar is not only for KitKat.

I don't have much to say about the 2nd and 3rd, You get the idea I believe, it's a fast read in any case. Just make sure you pay close attention to View.OnSystemUiVisibilityChangeListener.

I added a Gist that explains what I meant, it's not complete and needs some fixing but you'll get the idea. https://gist.github.com/Epsiloni/8303531

Good luck implementing this, and have fun!

Process.start: how to get the output?

The standard .NET way of doing this is to read from the Process' StandardOutput stream. There is an example in the linked MSDN docs. Similar, you can read from StandardError, and write to StandardInput.

Invert "if" statement to reduce nesting

It's a matter of opinion.

My normal approach would be to avoid single line ifs, and returns in the middle of a method.

You wouldn't want lines like it suggests everywhere in your method but there is something to be said for checking a bunch of assumptions at the top of your method, and only doing your actual work if they all pass.

Get the last inserted row ID (with SQL statement)

Assuming a simple table:

CREATE TABLE dbo.foo(ID INT IDENTITY(1,1), name SYSNAME);

We can capture IDENTITY values in a table variable for further consumption.

DECLARE @IDs TABLE(ID INT);

-- minor change to INSERT statement; add an OUTPUT clause:
INSERT dbo.foo(name) 
  OUTPUT inserted.ID INTO @IDs(ID)
SELECT N'Fred'
UNION ALL
SELECT N'Bob';

SELECT ID FROM @IDs;

The nice thing about this method is (a) it handles multi-row inserts (SCOPE_IDENTITY() only returns the last value) and (b) it avoids this parallelism bug, which can lead to wrong results, but so far is only fixed in SQL Server 2008 R2 SP1 CU5.

VLook-Up Match first 3 characters of one column with another column

Try using a wildcard like this

=VLOOKUP(LEFT(A1,3)&"*",B$2:B$22,1,FALSE)

so if A1 is "barry" that formula will return the first value in B2:B22 that starts with "bar"

Multiple commands on a single line in a Windows batch file

Use:

echo %time% & dir & echo %time%

This is, from memory, equivalent to the semi-colon separator in bash and other UNIXy shells.

There's also && (or ||) which only executes the second command if the first succeeded (or failed), but the single ampersand & is what you're looking for here.


That's likely to give you the same time however since environment variables tend to be evaluated on read rather than execute.

You can get round this by turning on delayed expansion:

pax> cmd /v:on /c "echo !time! & ping 127.0.0.1 >nul: & echo !time!"
15:23:36.77
15:23:39.85

That's needed from the command line. If you're doing this inside a script, you can just use setlocal:

@setlocal enableextensions enabledelayedexpansion
@echo off
echo !time! & ping 127.0.0.1 >nul: & echo !time!
endlocal

jQuery function to open link in new window

Try adding return false; in your click callback like this -

$(document).ready(function() {
  $('.popup').click(function(event) {
      window.open($(this).attr("href"), "popupWindow", "width=600,height=600,scrollbars=yes");
      return false;
  });
});

How to Clear Console in Java?

Try this code

import java.io.IOException;

public class CLS {
    public static void main(String... arg) throws IOException, InterruptedException {
        new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
    }
}

Now when the Java process is connected to a console, it will clear the console.

Deleting an object in java?

If you want help an object go away, set its reference to null.

String x = "sadfasdfasd";
// do stuff
x = null;

Setting reference to null will make it more likely that the object will be garbage collected, as long as there are no other references to the object.

Regular expression for floating point numbers

for javascript

const test = new RegExp('^[+]?([0-9]{0,})*[.]?([0-9]{0,2})?$','g');

Which would work for 1.23 1234.22 0 0.12 12

You can change the parts in the {} to get different results in decimal length and front of the decimal as well. This is used in inputs for entering in number and checking every input as you type only allowing what passes.

How to check if the docker engine and a docker container are running?

I have a more fleshed out example of using some of the work above in the context of a Gitea container, but it could easily be converted to another container based on the name. Also, you could probably use the docker ps --filter capability to set $GITEA_CONTAINER in a newer system or one without docker-compose in use.

# Set to name or ID of the container to be watched.
GITEA_CONTAINER=$(./bin/docker-compose ps |grep git|cut -f1 -d' ')

# Set timeout to the number of seconds you are willing to wait.
timeout=500; counter=0
# This first echo is important for keeping the output clean and not overwriting the previous line of output.
echo "Waiting for $GITEA_CONTAINER to be ready (${counter}/${timeout})"
#This says that until docker inspect reports the container is in a running state, keep looping.
until [[ $(docker inspect --format '{{json .State.Running}}' $GITEA_CONTAINER) == true ]]; do

  # If we've reached the timeout period, report that and exit to prevent running an infinite loop.
  if [[ $timeout -lt $counter ]]; then
    echo "ERROR: Timed out waiting for $GITEA_CONTAINER to come up."
    exit 1
  fi

  # Every 5 seconds update the status
  if (( $counter % 5 == 0 )); then
    echo -e "\e[1A\e[KWaiting for $GITEA_CONTAINER to be ready (${counter}/${timeout})"
  fi

  # Wait a second and increment the counter
  sleep 1s
  ((counter++))

done

How to check whether a select box is empty using JQuery/Javascript

To check whether select box has any values:

if( $('#fruit_name').has('option').length > 0 ) {

To check whether selected value is empty:

if( !$('#fruit_name').val() ) { 

How to set OnClickListener on a RadioButton in Android?

 radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
    {
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            // checkedId is the RadioButton selected
            RadioButton rb=(RadioButton)findViewById(checkedId);
            textViewChoice.setText("You Selected " + rb.getText());
            //Toast.makeText(getApplicationContext(), rb.getText(), Toast.LENGTH_SHORT).show();
        }
    });

How do I set the default page of my application in IIS7?

Just go to web.config file and add following

<system.webServer>
    <defaultDocument>
      <files>
        <clear />
        <add value="Path of your Page" />
      </files>
    </defaultDocument>
</system.webServer>

Multi-Line Comments in Ruby?

Using either:

=begin
This
is
a
comment
block
=end

or

# This
# is
# a
# comment
# block

are the only two currently supported by rdoc, which is a good reason to use only these I think.

Xcode "Build and Archive" from command line

After updating to Xcode 8, I found that enterprise ipa generate by

/usr/bin/xcrun -sdk iphoneos PackageApplication -v "${RELEASE_BUILDDIR}/${APPLICATION_NAME}.app" -o "${BUILD_HISTORY_DIR}/${APPLICATION_NAME}.ipa" --sign "${DEVELOPER_NAME}" --embed "${PROVISONING_PROFILE}" 

Command cannot be launched because of some signature issue. The log indicates that "warning: PackageApplication is deprecated, use xcodebuild -exportArchive instead.

So I switch to xcodebuild -exportArchive and everything went back normal.

How to declare an array inside MS SQL Server Stored Procedure?

T-SQL doesn't support arrays that I'm aware of.

What's your table structure? You could probably design a query that does this instead:

select
month,
sum(sales)
from sales_table
group by month
order by month

How to write specific CSS for mozilla, chrome and IE

use agent detector and then with your web language create program to create css

for example in python

csscreator()
    useragent = detector()
    if useragent == "Firefox":
         css = "your css"
    ...
    return css

Change arrow colors in Bootstraps carousel

In bootstrap 4 if you are just changing the colour of the controls you can use the sass variables, typically in custom.scss:

$carousel-control-color: #7b277d;

As highlighted in this github issue note: https://github.com/twbs/bootstrap/issues/21985#issuecomment-281402443

How to change the author and committer name and e-mail of multiple commits in Git?

Try this out. It will do the same as above mentioned, but interactively.

bash <(curl -s  https://raw.githubusercontent.com/majdarbash/git-author-change-script/master/run.sh)

Reference: https://github.com/majdarbash/git-author-change-script

What's the opposite of 'make install', i.e. how do you uninstall a library in Linux?

If sudo make uninstall is unavailable:

In a Debian based system, instead of (or after*) doing make install you can run sudo checkinstall to make a .deb file that gets automatically installed. You can then remove it using the system package manager (e.g. apt/synaptic/aptitude/dpkg). Checkinstall also supports creating other types of package, e.g. RPM.

See also http://community.linuxmint.com/tutorial/view/162 and some basic checkinstall usage and debian checkinstall package.


*: If you're reading this after having installed with make install you can still follow the above instructions and do a dpkg -r $PACKAGE_NAME_YOU_CHOSEN afterwards.

How to create a temporary directory and get the path / file name in Python

If I get your question correctly, you want to also know the names of the files generated inside the temporary directory? If so, try this:

import os
import tempfile

with tempfile.TemporaryDirectory() as tmp_dir:
    # generate some random files in it
     files_in_dir = os.listdir(tmp_dir)

Should I use PATCH or PUT in my REST API?

The PATCH method is the correct choice here as you're updating an existing resource - the group ID. PUT should only be used if you're replacing a resource in its entirety.

Further information on partial resource modification is available in RFC 5789. Specifically, the PUT method is described as follows:

Several applications extending the Hypertext Transfer Protocol (HTTP) require a feature to do partial resource modification. The existing HTTP PUT method only allows a complete replacement of a document. This proposal adds a new HTTP method, PATCH, to modify an existing HTTP resource.

Pinging an IP address using PHP and echoing the result

This also did not work for me in Wordpress. I also tried -t and -n and other ways, but did not work. I used,

function pingAddress($ip) {
    $pingresult = exec("/bin/ping -c2 -w2 $ip", $outcome, $status);  
    if ($status==0) {
    $status = "alive";
    } else {
    $status = "dead";
    }
    $message .= '<div id="dialog-block-left">';
    $message .= '<div id="ip-status">The IP address, '.$ip.', is  '.$status.'</div><div style="clear:both"></div>';    
    return $message;
}
// Some IP Address
pingAddress("192.168.1.1"); 

This worked perfectly for me, finally. I referred this from http://www.phpscriptsdaily.com/php/php-ping/ Hope this will help

Well I want to modify this as it is working fine on my localhost but not on my live server For live server, I got another thing which now works for both local as well as live.

$fp = fSockOpen($ip,80,$errno,$errstr,1);
if($fp) { $status=0; fclose($fp); } else { $status=1; }

Then I show the Server is up for 0 and down for 1.

This works perfectly for me. I got this from Ping site and return result in PHP Thanks @karim79

Meaning of "n:m" and "1:n" in database design

In a relational database all types of relationships are represented in the same way: as relations. The candidate key(s) of each relation (and possibly other constraints as well) determine what kind of relationship is being represented. 1:n and m:n are two kinds of binary relationship:

C {Employee*,Company}
B {Book*,Author*}

In each case * designates the key attribute(s). {Book,Author} is a compound key.

C is a relation where each employee works for only one company but each company may have many employees (1:n): B is a relation where a book can have many authors and an author may write many books (m:n):

Notice that the key constraints ensure that each employee can only be associated with one company whereas any combination of books and authors is permitted.

Other kinds of relationship are possible as well: n-ary (having more than two components); fixed cardinality (m:n where m and n are fixed constants or ranges); directional; and so on. William Kent in his book "Data and Reality" identifies at least 432 kinds - and that's just for binary relationships. In practice, the binary relationships 1:n and m:n are very common and are usually singled out as specially important in designing and understanding data models.

Collectors.toMap() keyMapper -- more succinct expression?

List<Person> roster = ...;

Map<String, Person> map = 
    roster
        .stream()
        .collect(
            Collectors.toMap(p -> p.getLast(), p -> p)
        );

that would be the translation, but i havent run this or used the API. most likely you can substitute p -> p, for Function.identity(). and statically import toMap(...)

How to start a background process in Python?

You probably want to start investigating the os module for forking different threads (by opening an interactive session and issuing help(os)). The relevant functions are fork and any of the exec ones. To give you an idea on how to start, put something like this in a function that performs the fork (the function needs to take a list or tuple 'args' as an argument that contains the program's name and its parameters; you may also want to define stdin, out and err for the new thread):

try:
    pid = os.fork()
except OSError, e:
    ## some debug output
    sys.exit(1)
if pid == 0:
    ## eventually use os.putenv(..) to set environment variables
    ## os.execv strips of args[0] for the arguments
    os.execv(args[0], args)

Is there an XSLT name-of element?

<xsl:value-of select="name(.)" /> : <xsl:value-of select="."/>

MSBUILD : error MSB1008: Only one project can be specified

If you use default workspace in Jenkins, this might occur. Use custom workspace location without any spaces.

enter image description here

Create a unique number with javascript time

I use

Math.floor(new Date().valueOf() * Math.random())

So if by any chance the code is fired at the same time there is also a teeny chance that the random numbers will be the same.

Get element of JS object with an index

I know it's a late answer, but I think this is what OP asked for.

myobj[Object.keys(myobj)[0]];

C# Reflection: How to get class reference from string?

A simple use:

Type typeYouWant = Type.GetType("NamespaceOfType.TypeName, AssemblyName");

Sample:

Type dogClass = Type.GetType("Animals.Dog, Animals");

C compile : collect2: error: ld returned 1 exit status

sometimes this error came beacause failed to compile in middlest of any build. The best way to try is by doing make clean and again make the whole code .

Modulo operator with negative values

From ISO14882:2011(e) 5.6-4:

The binary / operator yields the quotient, and the binary % operator yields the remainder from the division of the first expression by the second. If the second operand of / or % is zero the behavior is undefined. For integral operands the / operator yields the algebraic quotient with any fractional part discarded; if the quotient a/b is representable in the type of the result, (a/b)*b + a%b is equal to a.

The rest is basic math:

(-7/3) => -2
-2 * 3 => -6
so a%b => -1

(7/-3) => -2
-2 * -3 => 6
so a%b => 1

Note that

If both operands are nonnegative then the remainder is nonnegative; if not, the sign of the remainder is implementation-defined.

from ISO14882:2003(e) is no longer present in ISO14882:2011(e)

PostgreSQL - SQL state: 42601 syntax error

Your function would work like this:

CREATE OR REPLACE FUNCTION prc_tst_bulk(sql text)
RETURNS TABLE (name text, rowcount integer) AS 
$$
BEGIN

RETURN QUERY EXECUTE '
WITH v_tb_person AS (' || sql || $x$)
SELECT name, count(*)::int FROM v_tb_person WHERE nome LIKE '%a%' GROUP BY name
UNION
SELECT name, count(*)::int FROM v_tb_person WHERE gender = 1 GROUP BY name$x$;

END     
$$ LANGUAGE plpgsql;

Call:

SELECT * FROM prc_tst_bulk($$SELECT a AS name, b AS nome, c AS gender FROM tbl$$)
  • You cannot mix plain and dynamic SQL the way you tried to do it. The whole statement is either all dynamic or all plain SQL. So I am building one dynamic statement to make this work. You may be interested in the chapter about executing dynamic commands in the manual.

  • The aggregate function count() returns bigint, but you had rowcount defined as integer, so you need an explicit cast ::int to make this work

  • I use dollar quoting to avoid quoting hell.

However, is this supposed to be a honeypot for SQL injection attacks or are you seriously going to use it? For your very private and secure use, it might be ok-ish - though I wouldn't even trust myself with a function like that. If there is any possible access for untrusted users, such a function is a loaded footgun. It's impossible to make this secure.

Craig (a sworn enemy of SQL injection!) might get a light stroke, when he sees what you forged from his piece of code in the answer to your preceding question. :)

The query itself seems rather odd, btw. But that's beside the point here.

C++ String Concatenation operator<<

nametext is an std::string but these do not have the stream insertion operator (<<) like output streams do.

To concatenate strings you can use the append member function (or its equivalent, +=, which works in the exact same way) or the + operator, which creates a new string as a result of concatenating the previous two.

How to modify a CSS display property from JavaScript?

I found the solution.

As said in the EDIT of my answer, a <div> is misfunctioning in a <table>. So I wrote this code instead :

<tr id="hidden" style="display:none;">
    <td class="depot_table_left">
        <label for="sexe">Sexe</label>
    </td>
    <td>
        <select type="text" name="sexe">
            <option value="1">Sexe</option>
            <option value="2">Joueur</option>
            <option value="3">Joueuse</option>
        </select>
    </td>
</tr>

And this is working fine.

Thanks everybody ;)

JavaScript function in href vs. onclick

In terms of javascript, one difference is that the this keyword in the onclick handler will refer to the DOM element whose onclick attribute it is (in this case the <a> element), whereas this in the href attribute will refer to the window object.

In terms of presentation, if an href attribute is absent from a link (i.e. <a onclick="[...]">) then, by default, browsers will display the text cursor (and not the often-desired pointer cursor) since it is treating the <a> as an anchor, and not a link.

In terms of behavior, when specifying an action by navigation via href, the browser will typically support opening that href in a separate window using either a shortcut or context menu. This is not possible when specifying an action only via onclick.


However, if you're asking what is the best way to get dynamic action from the click of a DOM object, then attaching an event using javascript separate from the content of the document is the best way to go. You could do this in a number of ways. A common way is to use a javascript library like jQuery to bind an event:

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<a id="link" href="http://example.com/action">link text</a>
<script type="text/javascript">
    $('a#link').click(function(){ /* ... action ... */ })
</script>

Git: force user and password prompt

This is most likely because you have multiple accounts, like one private, one for work with GitHub.

SOLUTION On Windows, go to Start > Credential Manager > Windows Credentials and remove GitHub creds, then try pulling or pushing again and you will be prompted to relogin into GitHub

SOLUTION OnMac, issue following on terminal:

git remote set-url origin https://[email protected]/username/repo-name.git

by replacing 'username' with your GitHub username in both places and providing your GitHub repo name.

Convert Java string to Time, NOT Date

You might want to take a look at this example:

public static void main(String[] args) {

    String myTime = "10:30:54";
    SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");
    Date date = null;
    try {
        date = sdf.parse(myTime);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    String formattedTime = sdf.format(date);

    System.out.println(formattedTime);

}

Angular - Set headers for every request

Better late than never... =)

You may take the concept of extended BaseRequestOptions(from here https://angular.io/docs/ts/latest/guide/server-communication.html#!#override-default-request-options) and refresh the headers "on the fly" (not only in constructor). You may use getter/setter "headers" property override like this:

import { Injectable } from '@angular/core';
import { BaseRequestOptions, RequestOptions, Headers } from '@angular/http';

@Injectable()
export class DefaultRequestOptions extends BaseRequestOptions {

    private superHeaders: Headers;

    get headers() {
        // Set the default 'Content-Type' header
        this.superHeaders.set('Content-Type', 'application/json');

        const token = localStorage.getItem('authToken');
        if(token) {
            this.superHeaders.set('Authorization', `Bearer ${token}`);
        } else {
            this.superHeaders.delete('Authorization');
        }
        return this.superHeaders;
    }

    set headers(headers: Headers) {
        this.superHeaders = headers;
    }

    constructor() {
        super();
    }
}

export const requestOptionsProvider = { provide: RequestOptions, useClass: DefaultRequestOptions };

Using FolderBrowserDialog in WPF application

If I'm not mistaken you're looking for the FolderBrowserDialog (hence the naming):

var dialog = new System.Windows.Forms.FolderBrowserDialog();
System.Windows.Forms.DialogResult result = dialog.ShowDialog();

Also see this SO thread: Open directory dialog

Install specific branch from github using Npm

I'm using SSH to authenticate my GitHub account and have a couple dependencies in my project installed as follows:

"dependencies": {
  "<dependency name>": "git+ssh://[email protected]/<github username>/<repository name>.git#<release version | branch>"
}

Dynamic variable names in Bash

Even though it's an old question, I still had some hard time with fetching dynamic variables names, while avoiding the eval (evil) command.

Solved it with declare -n which creates a reference to a dynamic value, this is especially useful in CI/CD processes, where the required secret names of the CI/CD service are not known until runtime. Here's how:

# Bash v4.3+
# -----------------------------------------------------------
# Secerts in CI/CD service, injected as environment variables
# AWS_ACCESS_KEY_ID_DEV, AWS_SECRET_ACCESS_KEY_DEV
# AWS_ACCESS_KEY_ID_STG, AWS_SECRET_ACCESS_KEY_STG
# -----------------------------------------------------------
# Environment variables injected by CI/CD service
# BRANCH_NAME="DEV"
# -----------------------------------------------------------
declare -n _AWS_ACCESS_KEY_ID_REF=AWS_ACCESS_KEY_ID_${BRANCH_NAME}
declare -n _AWS_SECRET_ACCESS_KEY_REF=AWS_SECRET_ACCESS_KEY_${BRANCH_NAME}

export AWS_ACCESS_KEY_ID=${_AWS_ACCESS_KEY_ID_REF}
export AWS_SECRET_ACCESS_KEY=${_AWS_SECRET_ACCESS_KEY_REF}

echo $AWS_ACCESS_KEY_ID $AWS_SECRET_ACCESS_KEY
aws s3 ls

Routing with Multiple Parameters using ASP.NET MVC

You can pass arbitrary parameters through the query string, but you can also set up custom routes to handle it in a RESTful way:

http://ws.audioscrobbler.com/2.0/?method=artist.getimages&artist=cher&
                                  api_key=b25b959554ed76058ac220b7b2e0a026

That could be:

routes.MapRoute(
    "ArtistsImages",
    "{ws}/artists/{artist}/{action}/{*apikey}",
    new { ws = "2.0", controller="artists" artist = "", action="", apikey="" }
    );

So if someone used the following route:

ws.audioscrobbler.com/2.0/artists/cher/images/b25b959554ed76058ac220b7b2e0a026/

It would take them to the same place your example querystring did.

The above is just an example, and doesn't apply the business rules and constraints you'd have to set up to make sure people didn't 'hack' the URL.

Get an array of list element contents in jQuery

var optionTexts = [];
$("ul li").each(function() { optionTexts.push($(this).text()) });

...should do the trick. To get the final output you're looking for, join() plus some concatenation will do nicely:

var quotedCSV = '"' + optionTexts.join('", "') + '"';

How to read XML response from a URL in java?

For xml parsing of an inputstream you can do:

// the SAX way:
XMLReader myReader = XMLReaderFactory.createXMLReader();
myReader.setContentHandler(handler);
myReader.parse(new InputSource(new URL(url).openStream()));

// or if you prefer DOM:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new URL(url).openStream());

But to communicate over http from server to client I prefer using hessian library or springs http invoker lib

Creating a BLOB from a Base64 string in JavaScript

See this example: https://jsfiddle.net/pqhdce2L/

_x000D_
_x000D_
function b64toBlob(b64Data, contentType, sliceSize) {_x000D_
  contentType = contentType || '';_x000D_
  sliceSize = sliceSize || 512;_x000D_
_x000D_
  var byteCharacters = atob(b64Data);_x000D_
  var byteArrays = [];_x000D_
_x000D_
  for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {_x000D_
    var slice = byteCharacters.slice(offset, offset + sliceSize);_x000D_
_x000D_
    var byteNumbers = new Array(slice.length);_x000D_
    for (var i = 0; i < slice.length; i++) {_x000D_
      byteNumbers[i] = slice.charCodeAt(i);_x000D_
    }_x000D_
_x000D_
    var byteArray = new Uint8Array(byteNumbers);_x000D_
_x000D_
    byteArrays.push(byteArray);_x000D_
  }_x000D_
    _x000D_
  var blob = new Blob(byteArrays, {type: contentType});_x000D_
  return blob;_x000D_
}_x000D_
_x000D_
_x000D_
var contentType = 'image/png';_x000D_
var b64Data = Your Base64 encode;_x000D_
_x000D_
var blob = b64toBlob(b64Data, contentType);_x000D_
var blobUrl = URL.createObjectURL(blob);_x000D_
_x000D_
var img = document.createElement('img');_x000D_
img.src = blobUrl;_x000D_
document.body.appendChild(img);
_x000D_
_x000D_
_x000D_

How to convert ActiveRecord results into an array of hashes

as_json

You should use as_json method which converts ActiveRecord objects to Ruby Hashes despite its name

tasks_records = TaskStoreStatus.all
tasks_records = tasks_records.as_json

# You can now add new records and return the result as json by calling `to_json`

tasks_records << TaskStoreStatus.last.as_json
tasks_records << { :task_id => 10, :store_name => "Koramanagala", :store_region => "India" }
tasks_records.to_json

serializable_hash

You can also convert any ActiveRecord objects to a Hash with serializable_hash and you can convert any ActiveRecord results to an Array with to_a, so for your example :

tasks_records = TaskStoreStatus.all
tasks_records.to_a.map(&:serializable_hash)

And if you want an ugly solution for Rails prior to v2.3

JSON.parse(tasks_records.to_json) # please don't do it

How to start and stop/pause setInterval?

You can't stop a timer function mid-execution. You can only catch it after it completes and prevent it from triggering again.

Visual Studio Code - is there a Compare feature like that plugin for Notepad ++?

I found a flow which is fastest for me, by first associating a keyboard shortcut Alt+k to "Compare Active File With..." (#a). (Similar to wisbucky's answer but further improved and more step-wise.)

Then, to compare two files:

  1. Open or focus file B (will be editable in compare view by default). E.g. by drag-drop from File Explorer to VS Code's center.
  2. Open or focus file A.
  3. Press Alt+k, a quick open menu will be shown with file B focused.
  4. Press Enter.

Result: file A on left and file B on right. (Tested on VS Code 1.27.1)

Remarks

#a - to do so, press Ctrl-k Ctrl-s to show Keyboard Shortcuts, type compare on the top search box, and double click the "Keybinding" column for "Compare Active File With...", press Alt+k then Enter to assign it.

Git merge error "commit is not possible because you have unmerged files"

Since git 2.23 (August 2019) you now have a shortcut to do that: git restore --staged [filepath]. With this command, you could ignore a conflicted file without needing to add and remove that.

Example:

> git status

  ...
  Unmerged paths:
    (use "git add <file>..." to mark resolution)
      both modified:   file.ex

> git restore --staged file.ex

> git status

  ...
  Changes not staged for commit:
    (use "git add <file>..." to update what will be committed)
    (use "git restore <file>..." to discard changes in working directory)
      modified:   file.ex

Google Chrome redirecting localhost to https

I experienced the same problem in Chrome and I tried unsuccessfully to use BigJump's solution.

I fixed my problem by forcing a hard refresh, as shown in this blog (originally from this SuperUser answer).

Ensure your address bar is using the http scheme and then go through these steps, possibly a couple of times:

  1. Open the Developer Tools panel (CTRL+SHIFT+I)
  2. Click and hold the reload icon / Right click the reload icon.
  3. A menu will open.
  4. Choose the 3rd option from this menu ("Empty Cache and Hard Reload")

HTTP Basic Authentication - what's the expected web browser experience?

Have you tried ?

curl somesite.com --user username:password

Passing parameters from jsp to Spring Controller method

Use the @RequestParam to pass a parameter to the controller handler method. In the jsp your form should have an input field with name = "id" like the following:

<input type="text" name="id" />
<input type="submit" />

Then in your controller, your handler method should be like the following:

@RequestMapping("listNotes")
public String listNotes(@RequestParam("id") int id) {
    Person person = personService.getCurrentlyAuthenticatedUser();
    model.addAttribute("person", new Person());
    model.addAttribute("listPersons", this.personService.listPersons());
    model.addAttribute("listNotes", this.notesService.listNotesBySectionId(id, person));
    return "note";
}

Please also refer to these answers and tutorial:

How to generate random float number in C

If you want to generate a random float in a range, try a next solution.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>


float
random_float(const float min, const float max)
{
    if (max == min) return min;
    else if (min < max) return (max - min) * ((float)rand() / RAND_MAX) + min;

    // return 0 if min > max
    return 0;
}


int
main (const int argc, const char *argv[])
{
    srand(time(NULL));

    char line[] = "-------------------------------------------";

    float data[10][2] = {
        {-10, 10},
        {-5., 5},
        {-1, 1},
        {-0.25, -0.15},
        {1.5, 1.52},
        {-1700, 8000},
        {-0.1, 0.1},
        {-1, 0},
        {-1, -2},
        {1.2, 1.1}
    };

    puts(line);
    puts("     From    |    Result    |      To");
    puts(line);


    int i;
    for (i = 0; i < 10; ++i) {
        printf("%12f | %12f | %12f\n", data[i][0], random_float(data[i][0], data[i][1]), data[i][1]);
    }

    puts(line);

    return 0;
}

A result (values is fickle)

-------------------------------------------
     From    |    Result    |      To
-------------------------------------------
  -10.000000 |     2.330828 |    10.000000
   -5.000000 |    -4.945523 |     5.000000
   -1.000000 |     0.004242 |     1.000000
   -0.250000 |    -0.203197 |    -0.150000
    1.500000 |     1.513431 |     1.520000
-1700.000000 |  3292.941895 |  8000.000000
   -0.100000 |    -0.021541 |     0.100000
   -1.000000 |    -0.148299 |     0.000000
   -1.000000 |     0.000000 |    -2.000000
    1.200000 |     0.000000 |     1.100000
-------------------------------------------

Uninstalling an MSI file from the command line without using msiexec

wmic product get name

Just gets the cmd stuck... still flashing _ after a couple minutes

in HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall, if you can find the folder with the software name you are trying to install (not the one named with ProductCode), the UninstallString points to the application's own uninstaller C:\Program Files\Zune\ZuneSetup.exe /x

Does .NET provide an easy way convert bytes to KB, MB, GB, etc.?

public static class MyExtension
{
    public static string ToPrettySize(this float Size)
    {
        return ConvertToPrettySize(Size, 0);
    }
    public static string ToPrettySize(this int Size)
    {
        return ConvertToPrettySize(Size, 0);
    }
    private static string ConvertToPrettySize(float Size, int R)
    {
        float F = Size / 1024f;
        if (F < 1)
        {
            switch (R)
            {
                case 0:
                    return string.Format("{0:0.00} byte", Size);
                case 1:
                    return string.Format("{0:0.00} kb", Size);
                case 2:
                    return string.Format("{0:0.00} mb", Size);
                case 3:
                    return string.Format("{0:0.00} gb", Size);
            }
        }
        return ConvertToPrettySize(F, ++R);
    }
}

Appending the same string to a list of strings in Python

my_list = ['foo', 'fob', 'faz', 'funk']
string = 'bar'
my_new_list = [x + string for x in my_list]
print my_new_list

This will print:

['foobar', 'fobbar', 'fazbar', 'funkbar']

how does multiplication differ for NumPy Matrix vs Array classes?

Function matmul (since numpy 1.10.1) works fine for both types and return result as a numpy matrix class:

import numpy as np

A = np.mat('1 2 3; 4 5 6; 7 8 9; 10 11 12')
B = np.array(np.mat('1 1 1 1; 1 1 1 1; 1 1 1 1'))
print (A, type(A))
print (B, type(B))

C = np.matmul(A, B)
print (C, type(C))

Output:

(matrix([[ 1,  2,  3],
        [ 4,  5,  6],
        [ 7,  8,  9],
        [10, 11, 12]]), <class 'numpy.matrixlib.defmatrix.matrix'>)
(array([[1, 1, 1, 1],
       [1, 1, 1, 1],
       [1, 1, 1, 1]]), <type 'numpy.ndarray'>)
(matrix([[ 6,  6,  6,  6],
        [15, 15, 15, 15],
        [24, 24, 24, 24],
        [33, 33, 33, 33]]), <class 'numpy.matrixlib.defmatrix.matrix'>)

Since python 3.5 as mentioned early you also can use a new matrix multiplication operator @ like

C = A @ B

and get the same result as above.

How do I copy to the clipboard in JavaScript?

This solution was found here. The document.execCommand("copy"); is not supported on Internet Explorer 8 and earlier.

_x000D_
_x000D_
const copyBtn =  document.getElementById("copyBtn");
const input = document.getElementById("input");

function copyText() {
  const value = input.value;
  
  input.select(); // selects the input variable as the text to be copied
  input.setSelectionRange(0, 99999); // this is used to set the selection range for mobile devices
  
  document.execCommand("copy"); // copies the selected text
  
  alert("Copied the text " + value); // displays the copied text in a prompt
}

copyBtn.onmousedown = function () {
  copyText();
}
_x000D_
<input type="text" id="input" placeholder="Type text to copy... "/>
<button id="copyBtn">
  Copy
</button>
_x000D_
_x000D_
_x000D_

how to add a day to a date using jquery datepicker

Try this:

 $('.pickupDate').change(function() {
  var date2 = $('.pickupDate').datepicker('getDate', '+1d'); 
  date2.setDate(date2.getDate()+1); 
  $('.dropoffDate').datepicker('setDate', date2);
});

Using print statements only to debug

A better way to debug the code is, by using module clrprint

It prints a color full output only when pass parameter debug=True

from clrprint import *
clrprint('ERROR:', information,clr=['r','y'], debug=True)

Disabling browser caching for all browsers from ASP.NET

For what it's worth, I just had to handle this in my ASP.NET MVC 3 application. Here is the code block I used in the Global.asax file to handle this for all requests.

    protected void Application_BeginRequest()
    {
        //NOTE: Stopping IE from being a caching whore
        HttpContext.Current.Response.Cache.SetAllowResponseInBrowserHistory(false);
        HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        HttpContext.Current.Response.Cache.SetNoStore();
        Response.Cache.SetExpires(DateTime.Now);
        Response.Cache.SetValidUntilExpires(true);
    }

How do I add target="_blank" to a link within a specified div?

I use this for every external link:

window.onload = function(){
  var anchors = document.getElementsByTagName('a');
  for (var i=0; i<anchors.length; i++){
    if (anchors[i].hostname != window.location.hostname) {
        anchors[i].setAttribute('target', '_blank');
    }
  }
}

Java decimal formatting using String.format?

NumberFormat and DecimalFormat are definitely what you want. Also, note the NumberFormat.setRoundingMode() method. You can use it to control how rounding or truncation is applied during formatting.

How to add images in select list?

For those wanting to display an icon, and accepting a "black and white" solution, one possibility is using character entities:

   <select>
      <option>100 &euro;</option>
      <option>89 &pound;</option>
    </select>

By extension, your icons can be stored in a custom font. Here's an example using the font FontAwesome: https://jsfiddle.net/14606fv9/2/ https://jsfiddle.net/14606fv9/2/

One benefit is that it doesn't require any Javascript. However, pay attention that loading the full font doesn't slow down the loading of your page.

Nota bene: The solution of using a background image doesn't seem working anymore in Firefox (at least in version 57 "Quantum"):

<select>
  <option style="background-image:url(euro.png);">100</option>
  <option style="background-image:url(pound.png);">89</option>
</select>

PHPExcel set border and format for all sheets in spreadsheet

To answer your extra question:

You can set which rows should be repeated on every page using:

$objPHPExcel->getActiveSheet()->getPageSetup()->setRowsToRepeatAtTopByStartAndEnd(1, 5);

Now, row 1, 2, 3, 4 and 5 will be repeated.

What does an exclamation mark before a cell reference mean?

When entered as the reference of a Named range, it refers to range on the sheet the named range is used on.

For example, create a named range MyName refering to =SUM(!B1:!K1)

Place a formula on Sheet1 =MyName. This will sum Sheet1!B1:K1

Now place the same formula (=MyName) on Sheet2. That formula will sum Sheet2!B1:K1

Note: (as pnuts commented) this and the regular SheetName!B1:K1 format are relative, so reference different cells as the =MyName formula is entered into different cells.

JavaScript associative array to JSON

I posted a fix for this here

You can use this function to modify JSON.stringify to encode arrays, just post it near the beginning of your script (check the link above for more detail):

// Upgrade for JSON.stringify, updated to allow arrays
(function(){
    // Convert array to object
    var convArrToObj = function(array){
        var thisEleObj = new Object();
        if(typeof array == "object"){
            for(var i in array){
                var thisEle = convArrToObj(array[i]);
                thisEleObj[i] = thisEle;
            }
        }else {
            thisEleObj = array;
        }
        return thisEleObj;
    };
    var oldJSONStringify = JSON.stringify;
    JSON.stringify = function(input){
        if(oldJSONStringify(input) == '[]')
            return oldJSONStringify(convArrToObj(input));
        else
            return oldJSONStringify(input);
    };
})();

php create object without class

you can always use new stdClass(). Example code:

   $object = new stdClass();
   $object->property = 'Here we go';

   var_dump($object);
   /*
   outputs:

   object(stdClass)#2 (1) {
      ["property"]=>
      string(10) "Here we go"
    }
   */

Also as of PHP 5.4 you can get same output with:

$object = (object) ['property' => 'Here we go'];

how to check for datatype in node js- specifically for integer

_x000D_
_x000D_
var val = ... //the value you want to check_x000D_
if(Number.isNaN(Number(val))){_x000D_
  console.log("This is NOT a number!");_x000D_
}else{_x000D_
  console.log("This IS a number!");_x000D_
}
_x000D_
_x000D_
_x000D_

How to Make A Chevron Arrow Using CSS?

I needed to change an input to an arrow in my project. Below is final work.

_x000D_
_x000D_
#in_submit {_x000D_
  background-color: white;_x000D_
  border-left: #B4C8E9;_x000D_
  border-top: #B4C8E9;_x000D_
  border-right: 3px solid black;_x000D_
  border-bottom: 3px solid black;_x000D_
  width: 15px;_x000D_
  height: 15px;_x000D_
  transform: rotate(-45deg);_x000D_
  margin-top: 4px;_x000D_
  margin-left: 4px;_x000D_
  position: absolute;_x000D_
  cursor: pointer;_x000D_
}
_x000D_
<input id="in_submit" type="button" class="convert_btn">
_x000D_
_x000D_
_x000D_

Here Fiddle

Linux command to translate DomainName to IP

Use this

$ dig +short stackoverflow.com

69.59.196.211

or this

$ host stackoverflow.com

stackoverflow.com has address 69.59.196.211
stackoverflow.com mail is handled by 30 alt2.aspmx.l.google.com.
stackoverflow.com mail is handled by 40 aspmx2.googlemail.com.
stackoverflow.com mail is handled by 50 aspmx3.googlemail.com.
stackoverflow.com mail is handled by 10 aspmx.l.google.com.
stackoverflow.com mail is handled by 20 alt1.aspmx.l.google.com.

T-SQL and the WHERE LIKE %Parameter% clause

The correct answer is, that, because the '%'-sign is part of your search expression, it should be part of your VALUE, so whereever you SET @LastName (be it from a programming language or from TSQL) you should set it to '%' + [userinput] + '%'

or, in your example:

DECLARE @LastName varchar(max)
SET @LastName = 'ning'
SELECT Employee WHERE LastName LIKE '%' + @LastName + '%'

Using wget to recursively fetch a directory with arbitrary files in it

Recursive wget ignoring robots (for websites)

wget -e robots=off -r -np --page-requisites --convert-links 'http://example.com/folder/'

-e robots=off causes it to ignore robots.txt for that domain

-r makes it recursive

-np = no parents, so it doesn't follow links up to the parent folder

Import CSV to SQLite

I had exactly same problem (on OS X Maverics 10.9.1 with SQLite3 3.7.13, but I don't think SQLite is related to the cause). I tried to import csv data saved from MS Excel 2011, which btw. uses ';' as columns separator. I found out that csv file from Excel still uses newline character from Mac OS 9 times, changing it to unix newline solved the problem. AFAIR BBEdit has a command for this, as well as Sublime Text 2.

How to set HTTP header to UTF-8 using PHP which is valid in W3C validator?

PHP sends headers automatically if set up to use internal encoding:

ini_set('default_charset', 'utf-8');

fastest MD5 Implementation in JavaScript

Currently the fastest implementation of md5 (based on Joseph Myers' code):

https://github.com/iReal/FastMD5

jsPerf comparaison: http://jsperf.com/md5-shootout/63

Swift: Sort array of objects alphabetically

With Swift 3, you can choose one of the following ways to solve your problem.


1. Using sorted(by:?) with a Movie class that does not conform to Comparable protocol

If your Movie class does not conform to Comparable protocol, you must specify in your closure the property on which you wish to use Array's sorted(by:?) method.

Movie class declaration:

import Foundation

class Movie: CustomStringConvertible {

    let name: String
    var date: Date
    var description: String { return name }

    init(name: String, date: Date = Date()) {
        self.name = name
        self.date = date
    }

}

Usage:

let avatarMovie = Movie(name: "Avatar")
let titanicMovie = Movie(name: "Titanic")
let piranhaMovie = Movie(name: "Piranha II: The Spawning")

let movies = [avatarMovie, titanicMovie, piranhaMovie]
let sortedMovies = movies.sorted(by: { $0.name < $1.name })
// let sortedMovies = movies.sorted { $0.name < $1.name } // also works

print(sortedMovies)

/*
prints: [Avatar, Piranha II: The Spawning, Titanic]
*/

2. Using sorted(by:?) with a Movie class that conforms to Comparable protocol

However, by making your Movie class conform to Comparable protocol, you can have a much concise code when you want to use Array's sorted(by:?) method.

Movie class declaration:

import Foundation

class Movie: CustomStringConvertible, Comparable {

    let name: String
    var date: Date
    var description: String { return name }

    init(name: String, date: Date = Date()) {
        self.name = name
        self.date = date
    }

    static func ==(lhs: Movie, rhs: Movie) -> Bool {
        return lhs.name == rhs.name
    }

    static func <(lhs: Movie, rhs: Movie) -> Bool {
        return lhs.name < rhs.name
    }

}

Usage:

let avatarMovie = Movie(name: "Avatar")
let titanicMovie = Movie(name: "Titanic")
let piranhaMovie = Movie(name: "Piranha II: The Spawning")

let movies = [avatarMovie, titanicMovie, piranhaMovie]
let sortedMovies = movies.sorted(by: { $0 < $1 })
// let sortedMovies = movies.sorted { $0 < $1 } // also works
// let sortedMovies = movies.sorted(by: <) // also works

print(sortedMovies)

/*
 prints: [Avatar, Piranha II: The Spawning, Titanic]
 */

3. Using sorted() with a Movie class that conforms to Comparable protocol

By making your Movie class conform to Comparable protocol, you can use Array's sorted() method as an alternative to sorted(by:?).

Movie class declaration:

import Foundation

class Movie: CustomStringConvertible, Comparable {

    let name: String
    var date: Date
    var description: String { return name }

    init(name: String, date: Date = Date()) {
        self.name = name
        self.date = date
    }

    static func ==(lhs: Movie, rhs: Movie) -> Bool {
        return lhs.name == rhs.name
    }

    static func <(lhs: Movie, rhs: Movie) -> Bool {
        return lhs.name < rhs.name
    }

}

Usage:

let avatarMovie = Movie(name: "Avatar")
let titanicMovie = Movie(name: "Titanic")
let piranhaMovie = Movie(name: "Piranha II: The Spawning")

let movies = [avatarMovie, titanicMovie, piranhaMovie]
let sortedMovies = movies.sorted()

print(sortedMovies)

/*
 prints: [Avatar, Piranha II: The Spawning, Titanic]
 */

Annotation-specified bean name conflicts with existing, non-compatible bean def

Explanation internal working on this error

You are getting this error because after instantiation the container is trying to assign same object to both classes as class name is same irrespective of different packages......thats why error says non compatible bean definition of same name ..

Actually how it works internally is--->>>>.

pkg test1; …. @RestController class Test{}

pkg test2; …. @RestController class Test{}

First container will get class Test and @RestController indicates it to instantiate as…test = new Test(); and it won’t instantiate twice After instantiating container will provide a reference variable test(same as class name) to both the classes and while it provide test reference To second class it gets non compatible bean definition of same name ……

Solution—>>>>

Assign a refrence name to both rest controller so that container won’t instantiate with default name and instantiate saperately for both classes irrespective Of same name

For example——>>>

pkg test1; …. @RestController(“test1”) class Test{}

pkg test2; …. @RestController(“test2”) class Test{}

Note:The same will work with @Controller,@Service,@Repository etc..

Note: if you are creating reference variable at class level then you can also annotate it with @Qualifier("specific refrence name") for example @Autowired @Qualifier("test1") Test test;

@import vs #import - iOS 7

There is a few benefits of using modules. You can use it only with Apple's framework unless module map is created. @import is a bit similar to pre-compiling headers files when added to .pch file which is a way to tune app the compilation process. Additionally you do not have to add libraries in the old way, using @import is much faster and efficient in fact. If you still look for a nice reference I will highly recommend you reading this article.

jQuery Mobile: document ready vs. page events

jQuery Mobile 1.4 Update:

My original article was intended for old way of page handling, basically everything before jQuery Mobile 1.4. Old way of handling is now deprecated and it will stay active until (including) jQuery Mobile 1.5, so you can still use everything mentioned below, at least until next year and jQuery Mobile 1.6.

Old events, including pageinit don't exist any more, they are replaced with pagecontainer widget. Pageinit is erased completely and you can use pagecreate instead, that event stayed the same and its not going to be changed.

If you are interested in new way of page event handling take a look here, in any other case feel free to continue with this article. You should read this answer even if you are using jQuery Mobile 1.4 +, it goes beyond page events so you will probably find a lot of useful information.

Older content:

This article can also be found as a part of my blog HERE.

$(document).on('pageinit') vs $(document).ready()

The first thing you learn in jQuery is to call code inside the $(document).ready() function so everything will execute as soon as the DOM is loaded. However, in jQuery Mobile, Ajax is used to load the contents of each page into the DOM as you navigate. Because of this $(document).ready() will trigger before your first page is loaded and every code intended for page manipulation will be executed after a page refresh. This can be a very subtle bug. On some systems it may appear that it works fine, but on others it may cause erratic, difficult to repeat weirdness to occur.

Classic jQuery syntax:

$(document).ready(function() {

});

To solve this problem (and trust me this is a problem) jQuery Mobile developers created page events. In a nutshell page events are events triggered in a particular point of page execution. One of those page events is a pageinit event and we can use it like this:

$(document).on('pageinit', function() {

});

We can go even further and use a page id instead of document selector. Let's say we have jQuery Mobile page with an id index:

<div data-role="page" id="index">
    <div data-theme="a" data-role="header">
        <h3>
            First Page
        </h3>
        <a href="#second" class="ui-btn-right">Next</a>
    </div>

    <div data-role="content">
        <a href="#" data-role="button" id="test-button">Test button</a>
    </div>

    <div data-theme="a" data-role="footer" data-position="fixed">

    </div>
</div>

To execute code that will only available to the index page we could use this syntax:

$('#index').on('pageinit', function() {

});

Pageinit event will be executed every time page is about be be loaded and shown for the first time. It will not trigger again unless page is manually refreshed or Ajax page loading is turned off. In case you want code to execute every time you visit a page it is better to use pagebeforeshow event.

Here's a working example: http://jsfiddle.net/Gajotres/Q3Usv/ to demonstrate this problem.

Few more notes on this question. No matter if you are using 1 html multiple pages or multiple HTML files paradigm it is advised to separate all of your custom JavaScript page handling into a single separate JavaScript file. This will note make your code any better but you will have much better code overview, especially while creating a jQuery Mobile application.

There's also another special jQuery Mobile event and it is called mobileinit. When jQuery Mobile starts, it triggers a mobileinit event on the document object. To override default settings, bind them to mobileinit. One of a good examples of mobileinit usage is turning off Ajax page loading, or changing default Ajax loader behavior.

$(document).on("mobileinit", function(){
  //apply overrides here
});

Page events transition order

First all events can be found here: http://api.jquerymobile.com/category/events/

Lets say we have a page A and a page B, this is a unload/load order:

  1. page B - event pagebeforecreate

  2. page B - event pagecreate

  3. page B - event pageinit

  4. page A - event pagebeforehide

  5. page A - event pageremove

  6. page A - event pagehide

  7. page B - event pagebeforeshow

  8. page B - event pageshow

For better page events understanding read this:

  • pagebeforeload, pageload and pageloadfailed are fired when an external page is loaded
  • pagebeforechange, pagechange and pagechangefailed are page change events. These events are fired when a user is navigating between pages in the applications.
  • pagebeforeshow, pagebeforehide, pageshow and pagehide are page transition events. These events are fired before, during and after a transition and are named.
  • pagebeforecreate, pagecreate and pageinit are for page initialization.
  • pageremove can be fired and then handled when a page is removed from the DOM

Page loading jsFiddle example: http://jsfiddle.net/Gajotres/QGnft/

If AJAX is not enabled, some events may not fire.

Prevent page transition

If for some reason page transition needs to be prevented on some condition it can be done with this code:

$(document).on('pagebeforechange', function(e, data){
    var to = data.toPage,
        from = data.options.fromPage;

    if (typeof to  === 'string') {
        var u = $.mobile.path.parseUrl(to);
        to = u.hash || '#' + u.pathname.substring(1);
        if (from) from = '#' + from.attr('id');

        if (from === '#index' && to === '#second') {
            alert('Can not transition from #index to #second!');
            e.preventDefault();
            e.stopPropagation();

            // remove active status on a button, if transition was triggered with a button
            $.mobile.activePage.find('.ui-btn-active').removeClass('ui-btn-active ui-focus ui-btn');;
        }
    }
});

This example will work in any case because it will trigger at a begging of every page transition and what is most important it will prevent page change before page transition can occur.

Here's a working example:

Prevent multiple event binding/triggering

jQuery Mobile works in a different way than classic web applications. Depending on how you managed to bind your events each time you visit some page it will bind events over and over. This is not an error, it is simply how jQuery Mobile handles its pages. For example, take a look at this code snippet:

$(document).on('pagebeforeshow','#index' ,function(e,data){
    $(document).on('click', '#test-button',function(e) {
        alert('Button click');
    });
});

Working jsFiddle example: http://jsfiddle.net/Gajotres/CCfL4/

Each time you visit page #index click event will is going to be bound to button #test-button. Test it by moving from page 1 to page 2 and back several times. There are few ways to prevent this problem:

Solution 1

Best solution would be to use pageinit to bind events. If you take a look at an official documentation you will find out that pageinit will trigger ONLY once, just like document ready, so there's no way events will be bound again. This is best solution because you don't have processing overhead like when removing events with off method.

Working jsFiddle example: http://jsfiddle.net/Gajotres/AAFH8/

This working solution is made on a basis of a previous problematic example.

Solution 2

Remove event before you bind it:

$(document).on('pagebeforeshow', '#index', function(){
    $(document).off('click', '#test-button').on('click', '#test-button',function(e) {
        alert('Button click');
    });
});

Working jsFiddle example: http://jsfiddle.net/Gajotres/K8YmG/

Solution 3

Use a jQuery Filter selector, like this:

$('#carousel div:Event(!click)').each(function(){
    //If click is not bind to #carousel div do something
});

Because event filter is not a part of official jQuery framework it can be found here: http://www.codenothing.com/archives/2009/event-filter/

In a nutshell, if speed is your main concern then Solution 2 is much better than Solution 1.

Solution 4

A new one, probably an easiest of them all.

$(document).on('pagebeforeshow', '#index', function(){
    $(document).on('click', '#test-button',function(e) {
        if(e.handled !== true) // This will prevent event triggering more than once
        {
            alert('Clicked');
            e.handled = true;
        }
    });
});

Working jsFiddle example: http://jsfiddle.net/Gajotres/Yerv9/

Tnx to the sholsinger for this solution: http://sholsinger.com/archive/2011/08/prevent-jquery-live-handlers-from-firing-multiple-times/

pageChange event quirks - triggering twice

Sometimes pagechange event can trigger twice and it does not have anything to do with the problem mentioned before.

The reason the pagebeforechange event occurs twice is due to the recursive call in changePage when toPage is not a jQuery enhanced DOM object. This recursion is dangerous, as the developer is allowed to change the toPage within the event. If the developer consistently sets toPage to a string, within the pagebeforechange event handler, regardless of whether or not it was an object an infinite recursive loop will result. The pageload event passes the new page as the page property of the data object (This should be added to the documentation, it's not listed currently). The pageload event could therefore be used to access the loaded page.

In few words this is happening because you are sending additional parameters through pageChange.

Example:

<a data-role="button" data-icon="arrow-r" data-iconpos="right" href="#care-plan-view?id=9e273f31-2672-47fd-9baa-6c35f093a800&amp;name=Sat"><h3>Sat</h3></a>

To fix this problem use any page event listed in Page events transition order.

Page Change Times

As mentioned, when you change from one jQuery Mobile page to another, typically either through clicking on a link to another jQuery Mobile page that already exists in the DOM, or by manually calling $.mobile.changePage, several events and subsequent actions occur. At a high level the following actions occur:

  • A page change process is begun
  • A new page is loaded
  • The content for that page is “enhanced” (styled)
  • A transition (slide/pop/etc) from the existing page to the new page occurs

This is a average page transition benchmark:

Page load and processing: 3 ms

Page enhance: 45 ms

Transition: 604 ms

Total time: 670 ms

*These values are in milliseconds.

So as you can see a transition event is eating almost 90% of execution time.

Data/Parameters manipulation between page transitions

It is possible to send a parameter/s from one page to another during page transition. It can be done in few ways.

Reference: https://stackoverflow.com/a/13932240/1848600

Solution 1:

You can pass values with changePage:

$.mobile.changePage('page2.html', { dataUrl : "page2.html?paremeter=123", data : { 'paremeter' : '123' }, reloadPage : true, changeHash : true });

And read them like this:

$(document).on('pagebeforeshow', "#index", function (event, data) {
    var parameters = $(this).data("url").split("?")[1];;
    parameter = parameters.replace("parameter=","");
    alert(parameter);
});

Example:

index.html

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
  <html>_x000D_
    <head>_x000D_
    <meta charset="utf-8" />_x000D_
    <meta name="viewport" content="widdiv=device-widdiv, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />_x000D_
    <meta name="apple-mobile-web-app-capable" content="yes" />_x000D_
    <meta name="apple-mobile-web-app-status-bar-style" content="black" />_x000D_
    <title>_x000D_
    </title>_x000D_
    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />_x000D_
    <script src="http://www.dragan-gaic.info/js/jquery-1.8.2.min.js">_x000D_
    </script>_x000D_
    <script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>_x000D_
    <script>_x000D_
        $(document).on('pagebeforeshow', "#index",function () {_x000D_
            $(document).on('click', "#changePage",function () {_x000D_
                $.mobile.changePage('second.html', { dataUrl : "second.html?paremeter=123", data : { 'paremeter' : '123' }, reloadPage : false, changeHash : true });_x000D_
            });_x000D_
        });_x000D_
_x000D_
        $(document).on('pagebeforeshow', "#second",function () {_x000D_
            var parameters = $(this).data("url").split("?")[1];;_x000D_
            parameter = parameters.replace("parameter=","");_x000D_
            alert(parameter);_x000D_
        });_x000D_
    </script>_x000D_
   </head>_x000D_
   <body>_x000D_
    <!-- Home -->_x000D_
    <div data-role="page" id="index">_x000D_
        <div data-role="header">_x000D_
            <h3>_x000D_
                First Page_x000D_
            </h3>_x000D_
        </div>_x000D_
        <div data-role="content">_x000D_
          <a data-role="button" id="changePage">Test</a>_x000D_
        </div> <!--content-->_x000D_
    </div><!--page-->_x000D_
_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

second.html

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
  <html>_x000D_
    <head>_x000D_
    <meta charset="utf-8" />_x000D_
    <meta name="viewport" content="widdiv=device-widdiv, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />_x000D_
    <meta name="apple-mobile-web-app-capable" content="yes" />_x000D_
    <meta name="apple-mobile-web-app-status-bar-style" content="black" />_x000D_
    <title>_x000D_
    </title>_x000D_
    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />_x000D_
    <script src="http://www.dragan-gaic.info/js/jquery-1.8.2.min.js">_x000D_
    </script>_x000D_
    <script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>_x000D_
   </head>_x000D_
   <body>_x000D_
    <!-- Home -->_x000D_
    <div data-role="page" id="second">_x000D_
        <div data-role="header">_x000D_
            <h3>_x000D_
                Second Page_x000D_
            </h3>_x000D_
        </div>_x000D_
        <div data-role="content">_x000D_
_x000D_
        </div> <!--content-->_x000D_
    </div><!--page-->_x000D_
_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Solution 2:

Or you can create a persistent JavaScript object for a storage purpose. As long Ajax is used for page loading (and page is not reloaded in any way) that object will stay active.

var storeObject = {
    firstname : '',
    lastname : ''
}

Example: http://jsfiddle.net/Gajotres/9KKbx/

Solution 3:

You can also access data from the previous page like this:

$(document).on('pagebeforeshow', '#index',function (e, data) {
    alert(data.prevPage.attr('id'));
});

prevPage object holds a complete previous page.

Solution 4:

As a last solution we have a nifty HTML implementation of localStorage. It only works with HTML5 browsers (including Android and iOS browsers) but all stored data is persistent through page refresh.

if(typeof(Storage)!=="undefined") {
    localStorage.firstname="Dragan";
    localStorage.lastname="Gaic";
}

Example: http://jsfiddle.net/Gajotres/J9NTr/

Probably best solution but it will fail in some versions of iOS 5.X. It is a well know error.

Don’t Use .live() / .bind() / .delegate()

I forgot to mention (and tnx andleer for reminding me) use on/off for event binding/unbinding, live/die and bind/unbind are deprecated.

The .live() method of jQuery was seen as a godsend when it was introduced to the API in version 1.3. In a typical jQuery app there can be a lot of DOM manipulation and it can become very tedious to hook and unhook as elements come and go. The .live() method made it possible to hook an event for the life of the app based on its selector. Great right? Wrong, the .live() method is extremely slow. The .live() method actually hooks its events to the document object, which means that the event must bubble up from the element that generated the event until it reaches the document. This can be amazingly time consuming.

It is now deprecated. The folks on the jQuery team no longer recommend its use and neither do I. Even though it can be tedious to hook and unhook events, your code will be much faster without the .live() method than with it.

Instead of .live() you should use .on(). .on() is about 2-3x faster than .live(). Take a look at this event binding benchmark: http://jsperf.com/jquery-live-vs-delegate-vs-on/34, everything will be clear from there.

Benchmarking:

There's an excellent script made for jQuery Mobile page events benchmarking. It can be found here: https://github.com/jquery/jquery-mobile/blob/master/tools/page-change-time.js. But before you do anything with it I advise you to remove its alert notification system (each “change page” is going to show you this data by halting the app) and change it to console.log function.

Basically this script will log all your page events and if you read this article carefully (page events descriptions) you will know how much time jQm spent of page enhancements, page transitions ....

Final notes

Always, and I mean always read official jQuery Mobile documentation. It will usually provide you with needed information, and unlike some other documentation this one is rather good, with enough explanations and code examples.

Changes:

  • 30.01.2013 - Added a new method of multiple event triggering prevention
  • 31.01.2013 - Added a better clarification for chapter Data/Parameters manipulation between page transitions
  • 03.02.2013 - Added new content/examples to the chapter Data/Parameters manipulation between page transitions
  • 22.05.2013 - Added a solution for page transition/change prevention and added links to the official page events API documentation
  • 18.05.2013 - Added another solution against multiple event binding

SqlServer: Login failed for user

I ran into the same issue, and I fixed it by adding my windows username to SQL and then to my server, here is how I did:

First, create a new login with your Windows username: enter image description here

Click Search, then type your name in the box and click check names. enter image description here

Then add your that user to the server:

Right click on the Server > Permissions > Search > Browse > Select your user (You will notice that now the user you created is available in the list)

enter image description here

I hope it helps ;-)

Query to convert from datetime to date mysql

Use the DATE function:

SELECT DATE(orders.date_purchased) AS date

How to apply a patch generated with git format-patch?

Or, if you're kicking it old school:

cd /path/to/other/repository
patch -p1 < 0001-whatever.patch

Easiest way to copy a single file from host to Vagrant guest?

The best ans for me is to write the file / directory(to be copied) to the vagrant file directory, now any file present there is available to vagrant in path /vagrant.

That's it, no need of scp or any other methods,

similarly you can copy any file from VM to host by pasting in /vagrant directory.

Selecting Values from Oracle Table Variable / Array?

You might need a GLOBAL TEMPORARY TABLE.

In Oracle these are created once and then when invoked the data is private to your session.

Oracle Documentation Link

Try something like this...

CREATE GLOBAL TEMPORARY TABLE temp_number
   ( number_column   NUMBER( 10, 0 )
   )
   ON COMMIT DELETE ROWS;

BEGIN 
   INSERT INTO temp_number
      ( number_column )
      ( select distinct sgbstdn_pidm 
          from sgbstdn 
         where sgbstdn_majr_code_1 = 'HS04' 
           and sgbstdn_program_1 = 'HSCOMPH' 
      ); 

    FOR pidms_rec IN ( SELECT number_column FROM temp_number )
    LOOP 
        -- Do something here
        NULL; 
    END LOOP; 
END; 
/

Anchor links in Angularjs?

You can also Navigate to HTML id from inside controller

$location.hash('id_in_html');

How to disable Google Chrome auto update?

On Windows OS:

1) open following file for edit (as an admin): C:\Windows\System32\drivers\etc\hosts (this file has no extension)

2) on the bottom, add one line: 127.0.0.1 tools.google.com

3) save the file

4) enjoy old Chrome

HTTP error 403 in Python 3 Web Scraping

Definitely it's blocking because of your use of urllib based on the user agent. This same thing is happening to me with OfferUp. You can create a new class called AppURLopener which overrides the user-agent with Mozilla.

import urllib.request

class AppURLopener(urllib.request.FancyURLopener):
    version = "Mozilla/5.0"

opener = AppURLopener()
response = opener.open('http://httpbin.org/user-agent')

Source

Common Header / Footer with static HTML

You can try loading them via the client-side, like this:

<!DOCTYPE html>
<html>
  <head>
    <!-- ... -->
  </head>
  <body>

    <div id="headerID"> <!-- your header --> </div>
    <div id="pageID"> <!-- your header --> </div>
    <div id="footerID"> <!-- your header --> </div>

    <script>
      $("#headerID").load("header.html");
      $("#pageID").load("page.html");
      $("#footerID").load("footer.html");
    </script>
  </body>
</html>

NOTE: the content will load from top to bottom and replace the content of the container you load it into.

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

You can use innerHTML to just concat the extra field string;

document.head.innerHTML = document.head.innerHTML + '<link rel="stylesheet>...'

However, you can't guarantee that the extra things you add to the head will be recognised by the browser after the first load, and it's possible you will get a FOUC (flash of unstyled content) as the extra stylesheets are loaded.

I haven't looked at the API in years, but you could also use document.write, which is what was designed for this sort of action. However, this would require you to block the page from rendering until your initial AJAX request has completed.

How to define the css :hover state in a jQuery selector?

Well, you can't add styling using pseudo selectors like :hover, :after, :nth-child, or anything like that using jQuery.

If you want to add a CSS rule like that you have to create a <style> element and add that :hover rule to it just like you would in CSS. Then you would have to add that <style> element to the page.

Using the .hover function seems to be more appropriate if you can't just add the css to a stylesheet, but if you insist you can do:

$('head').append('<style>.myclass:hover div {background-color : red;}</style>')

If you want to read more on adding CSS with javascript you can check out one of David Walsh's Blog posts.

How can I print using JQuery

There is a jquery print area. I've been using it for some time now.

$(".printMe").click(function(){
   $("#outprint").printArea({ mode: 'popup', popClose: true });
});

Remove an item from an IEnumerable<T> collection

You can not remove an item from an IEnumerable; it can only be enumerated, as described here: http://msdn.microsoft.com/en-us/library/system.collections.ienumerable.aspx

You have to use an ICollection if you want to add and remove items. Maybe you can try and casting your IEnumerable; this will off course only work if the underlying object implements ICollection`.

See here for more on ICollection: http://msdn.microsoft.com/en-us/library/92t2ye13.aspx

You can, of course, just create a new list from your IEnumerable, as pointed out by lante, but this might be "sub optimal", depending on your actual use case, of course.

ICollection is probably the way to go.

Programmatically obtain the phone number of the Android phone

TelephonyManager is not the right solution, because in some cases the number is not stored in the SIM. I suggest that you should use the shared preference to store the user's phone number for the first time the application is open and the number will used whenever you need.

IIS URL Rewrite and Web.config

Just tried this rule, and it worked with GoDaddy hosting since they've already have the Microsoft URL Rewriting module installed for every IIS 7 account.

<rewrite>
  <rules>
    <rule name="enquiry" stopProcessing="true">
      <match url="^enquiry$" />
      <action type="Rewrite" url="/Enquiry.aspx" />
    </rule>
  </rules>
</rewrite>

Search a string in a file and delete it from this file by Shell Script

sed -i '/pattern/d' file

Use 'd' to delete a line. This works at least with GNU-Sed.

If your Sed doesn't have the option, to change a file in place, maybe you can use an intermediate file, to store the modification:

sed '/pattern/d' file > tmpfile && mv tmpfile file

Writing directly to the source usually doesn't work: sed '/pattern/d' file > file so make a copy before trying out, if you doubt it.

tomcat - CATALINA_BASE and CATALINA_HOME variables

CATALINA_BASE is optional.

However, in the following scenarios it helps to setup CATALINA_BASE that is separate from CATALINA_HOME.

  1. When more than 1 instances of tomcat are running on same host

    • This helps have only 1 runtime of tomcat installation, with multiple CATALINA_BASE server configurations running on separate ports.
    • If any patching, or version upgrade needs be, only 1 installation changes required, or need to be tested/verified/signed-off.
  2. Separation of concern (Single responsibility)

    • Tomcat runtime is standard and does not change during every release process. i.e. Tomcat binaries
    • Release process may add more stuff as webapplication (webapps folder), environment configuration (conf directory), logs/temp/work directory

How to get datas from List<Object> (Java)?

For starters you aren't iterating over the result list properly, you are not using the index i at all. Try something like this:

List<Object> list = getHouseInfo();
for (int i=0; i<list.size; i++){
   System.out.println("Element "+i+list.get(i));
}

It looks like the query reutrns a List of Arrays of Objects, because Arrays are not proper objects that override toString you need to do a cast first and then use Arrays.toString().

 List<Object> list = getHouseInfo();
for (int i=0; i<list.size; i++){
   Object[] row = (Object[]) list.get(i);
   System.out.println("Element "+i+Arrays.toString(row));
}

Update data on a page without refreshing

In general, if you don't know how something works, look for an example which you can learn from.

For this problem, consider this DEMO

You can see loading content with AJAX is very easily accomplished with jQuery:

$(function(){
    // don't cache ajax or content won't be fresh
    $.ajaxSetup ({
        cache: false
    });
    var ajax_load = "<img src='http://automobiles.honda.com/images/current-offers/small-loading.gif' alt='loading...' />";

    // load() functions
    var loadUrl = "http://fiddle.jshell.net/deborah/pkmvD/show/";
    $("#loadbasic").click(function(){
        $("#result").html(ajax_load).load(loadUrl);
    });

// end  
});

Try to understand how this works and then try replicating it. Good luck.

You can find the corresponding tutorial HERE

Update

Right now the following event starts the ajax load function:

$("#loadbasic").click(function(){
        $("#result").html(ajax_load).load(loadUrl);
    });

You can also do this periodically: How to fire AJAX request Periodically?

(function worker() {
  $.ajax({
    url: 'ajax/test.html', 
    success: function(data) {
      $('.result').html(data);
    },
    complete: function() {
      // Schedule the next request when the current one's complete
      setTimeout(worker, 5000);
    }
  });
})();

I made a demo of this implementation for you HERE. In this demo, every 2 seconds (setTimeout(worker, 2000);) the content is updated.

You can also just load the data immediately:

$("#result").html(ajax_load).load(loadUrl);

Which has THIS corresponding demo.

Random / noise functions for GLSL

A straight, jagged version of 1d Perlin, essentially a random lfo zigzag.

half  rn(float xx){         
    half x0=floor(xx);
    half x1=x0+1;
    half v0 = frac(sin (x0*.014686)*31718.927+x0);
    half v1 = frac(sin (x1*.014686)*31718.927+x1);          

    return (v0*(1-frac(xx))+v1*(frac(xx)))*2-1*sin(xx);
}

I also have found 1-2-3-4d perlin noise on shadertoy owner inigo quilez perlin tutorial website, and voronoi and so forth, he has full fast implementations and codes for them.

Example use of "continue" statement in Python?

It is not absolutely necessary since it can be done with IFs but it's more readable and also less expensive in run time.

I use it in order to skip an iteration in a loop if the data does not meet some requirements:

# List of times at which git commits were done.
# Formatted in hour, minutes in tuples.
# Note the last one has some fantasy.
commit_times = [(8,20), (9,30), (11, 45), (15, 50), (17, 45), (27, 132)]

for time in commit_times:
    hour = time[0]
    minutes = time[1]

    # If the hour is not between 0 and 24
    # and the minutes not between 0 and 59 then we know something is wrong.
    # Then we don't want to use this value,
    # we skip directly to the next iteration in the loop.
    if not (0 <= hour <= 24 and 0 <= minutes <= 59):
        continue

    # From here you know the time format in the tuples is reliable.
    # Apply some logic based on time.
    print("Someone commited at {h}:{m}".format(h=hour, m=minutes))

Output:

Someone commited at 8:20
Someone commited at 9:30
Someone commited at 11:45
Someone commited at 15:50
Someone commited at 17:45

As you can see, the wrong value did not make it after the continue statement.

How to read a .properties file which contains keys that have a period character using Shell script

Since variable names in the BASH shell cannot contain a dot or space it is better to use an associative array in BASH like this:

#!/bin/bash

# declare an associative array
declare -A arr

# read file line by line and populate the array. Field separator is "="
while IFS='=' read -r k v; do
   arr["$k"]="$v"
done < app.properties

Testing:

Use declare -p to show the result:

  > declare -p arr  

        declare -A arr='([db.uat.passwd]="secret" [db.uat.user]="saple user" )'

How to clear Route Caching on server: Laravel 5.2.37

If you are uploading your files through GIT from your local machine then you can use the same command you are using in your local machine while you are connected to your live server using BASH or something like.You can use this as like you use locally.

php artisan cache:clear

php artisan route:cache

It should work.

How to use Google App Engine with my own naked domain (not subdomain)?

Here is a tutorial from Google about mapping your App on custom domain: https://cloud.google.com/appengine/docs/domain?hl=FR

It should be the latest update. But please note these 2 things:

1- You may not find you App in the new developer console, then the only workaround for that is download your source code, create a new app from the new developer console and deploy it.

2- You find your App on the developer console, but under the Compute menu you may not find the App Engine Settings as mentioned in the tutorial, then you have to proceed the same as i explained in the first point (create another application)

I hope this helps !

pip is not able to install packages correctly: Permission denied error

It looks like you're having a permissions error, based on this message in your output: error: could not create '/lib/python2.7/site-packages/lxml': Permission denied.

One thing you can try is doing a user install of the package with pip install lxml --user. For more information on how that works, check out this StackOverflow answer. (Thanks to Ishaan Taylor for the suggestion)

You can also run pip install as a superuser with sudo pip install lxml but it is not generally a good idea because it can cause issues with your system-level packages.

Is there a list of screen resolutions for all Android based phones and tablets?

These are the sizes. Try to take a look in Supporting Mutiple Screens

320dp: a typical phone screen (240x320 ldpi, 320x480 mdpi, 480x800 hdpi, etc).
480dp: a tweener tablet like the Streak (480x800 mdpi).
600dp: a 7” tablet (600x1024 mdpi).
720dp: a 10” tablet (720x1280 mdpi, 800x1280 mdpi, etc).

I use this to make more than one layout:

res/layout/main_activity.xml           # For handsets (smaller than 600dp available width)
res/layout-sw600dp/main_activity.xml   # For 7” tablets (600dp wide and bigger)
res/layout-sw720dp/main_activity.xml   # For 10” tablets (720dp wide and bigger)

Dynamically add script tag with src that may include document.write

Well, there are multiple ways you can include dynamic javascript, I use this one for many of the projects.

var script = document.createElement("script")
script.type = "text/javascript";
//Chrome,Firefox, Opera, Safari 3+
script.onload = function(){
console.log("Script is loaded");
};
script.src = "file1.js";
document.getElementsByTagName("head")[0].appendChild(script);

You can call create a universal function which can help you to load as many javascript files as needed. There is a full tutorial about this here.

Inserting Dynamic Javascript the right way

How to stop C++ console application from exiting immediately?

Instead of pressing the run button, press CTRL and F5 at the same time, it will give you the press any key to continue message. Or type "(warning use this only for testing not actual programs as an antiviruses don't like it!!!!)" at the end of your main function but: (warning use this only for testing not actual programs as an antiviruses don't like it!!!!)

What does `void 0` mean?

void is a reserved JavaScript keyword. It evaluates the expression and always returns undefined.