Programs & Examples On #Quicksort

Quicksort is a sorting algorithm invented by C. A. R. Hoare that has an average-case complexity of O(n log n) and worst-case quadratic complexity. It is one of the fastest general-purpose sorting algorithms.

Why is quicksort better than mergesort?

As many people have noted, the average case performance for quicksort is faster than mergesort. But this is only true if you are assuming constant time to access any piece of memory on demand.

In RAM this assumption is generally not too bad (it is not always true because of caches, but it is not too bad). However if your data structure is big enough to live on disk, then quicksort gets killed by the fact that your average disk does something like 200 random seeks per second. But that same disk has no trouble reading or writing megabytes per second of data sequentially. Which is exactly what mergesort does.

Therefore if data has to be sorted on disk, you really, really want to use some variation on mergesort. (Generally you quicksort sublists, then start merging them together above some size threshold.)

Furthermore if you have to do anything with datasets of that size, think hard about how to avoid seeks to disk. For instance this is why it is standard advice that you drop indexes before doing large data loads in databases, and then rebuild the index later. Maintaining the index during the load means constantly seeking to disk. By contrast if you drop the indexes, then the database can rebuild the index by first sorting the information to be dealt with (using a mergesort of course!) and then loading it into a BTREE datastructure for the index. (BTREEs are naturally kept in order, so you can load one from a sorted dataset with few seeks to disk.)

There have been a number of occasions where understanding how to avoid disk seeks has let me make data processing jobs take hours rather than days or weeks.

Quicksort: Choosing the pivot

I recommend using the middle index, as it can be calculated easily.

You can calculate it by rounding (array.length / 2).

Quicksort with Python

Partition - Split an array by a pivot that smaller elements move to the left and greater elemets move to the right or vice versa. A pivot can be an random element from an array. To make this algorith we need to know what is begin and end index of an array and where is a pivot. Then set two auxiliary pointers L, R.

So we have an array user[...,begin,...,end,...]

The start position of L and R pointers
[...,begin,next,...,end,...]
     R       L

while L < end
  1. If a user[pivot] > user[L] then move R by one and swap user[R] with user[L]
  2. move L by one

After while swap user[R] with user[pivot]

Quick sort - Use the partition algorithm until every next part of the split by a pivot will have begin index greater or equals than end index.

def qsort(user, begin, end):

    if begin >= end:
        return

    # partition
    # pivot = begin
    L = begin+1
    R = begin
    while L < end:
        if user[begin] > user[L]:
            R+=1
            user[R], user[L] = user[L], user[R]
        L+= 1
    user[R], user[begin] = user[begin], user[R]

    qsort(user, 0, R)
    qsort(user, R+1, end)

tests = [
    {'sample':[1],'answer':[1]},
    {'sample':[3,9],'answer':[3,9]},
    {'sample':[1,8,1],'answer':[1,1,8]},
    {'sample':[7,5,5,1],'answer':[1,5,5,7]},
    {'sample':[4,10,5,9,3],'answer':[3,4,5,9,10]},
    {'sample':[6,6,3,8,7,7],'answer':[3,6,6,7,7,8]},
    {'sample':[3,6,7,2,4,5,4],'answer':[2,3,4,4,5,6,7]},
    {'sample':[1,5,6,1,9,0,7,4],'answer':[0,1,1,4,5,6,7,9]},
    {'sample':[0,9,5,2,2,5,8,3,8],'answer':[0,2,2,3,5,5,8,8,9]},
    {'sample':[2,5,3,3,2,0,9,0,0,7],'answer':[0,0,0,2,2,3,3,5,7,9]}
]

for test in tests:

    sample = test['sample'][:]
    answer = test['answer']

    qsort(sample,0,len(sample))

    print(sample == answer)

Concatenate two JSON objects

okay, you can do this in one line of code. you'll need json2.js for this (you probably already have.). the two json objects here are unparsed strings.

json1 = '[{"foo":"bar"},{"bar":"foo"},{"name":"craig"}]';

json2 = '[{"foo":"baz"},{"bar":"fob"},{"name":"george"}]';

concattedjson = JSON.stringify(JSON.parse(json1).concat(JSON.parse(json2)));

IE8 crashes when loading website - res://ieframe.dll/acr_error.htm

There is a known bug in jQuery 1.6.2 that is triggered by a background image being placed on the body element.

The bug report and patch are:

http://bugs.jquery.com/ticket/9823

https://github.com/jquery/jquery/commit/5c4a9cc001fcd803efa65ff95571c72cbdafbe69

I've also had modernizr trigger this error but since I could work around it I never chased it down.

Angular2 - Http POST request parameters

Update for Angualar 4.3+

Now we can use HttpClient instead of Http

Guide is here

Sample code

const myheader = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
let body = new HttpParams();
body = body.set('username', USERNAME);
body = body.set('password', PASSWORD);
http
  .post('/api', body, {
    headers: myheader),
  })
  .subscribe();

Deprecated

Or you can do like this:

let urlSearchParams = new URLSearchParams();
urlSearchParams.append('username', username);
urlSearchParams.append('password', password);
let body = urlSearchParams.toString()

Update Oct/2017

From angular4+, we don't need headers, or .toString() stuffs. Instead, you can do like below example

import { URLSearchParams } from '@angular/http';

POST/PUT method

let urlSearchParams = new URLSearchParams();
urlSearchParams.append('username', username);
urlSearchParams.append('password', password);
this.http.post('/api', urlSearchParams).subscribe(
      data => {
        alert('ok');
      },
      error => {
        console.log(JSON.stringify(error.json()));
      }
    )

GET/DELETE method

    let urlSearchParams = new URLSearchParams();
    urlSearchParams.append('username', username);
    urlSearchParams.append('password', password);
    this.http.get('/api', { search: urlSearchParams }).subscribe(
      data => {
        alert('ok');
      },
      error => {
        console.log(JSON.stringify(error.json()));
      }
    )

For JSON application/json Content-Type

this.http.post('/api',
      JSON.stringify({
        username: username,
        password: password,
      })).subscribe(
      data => {
        alert('ok');
      },
      error => {
        console.log(JSON.stringify(error.json()));
      }
      )

How to convert ‘false’ to 0 and ‘true’ to 1 in Python

Any of the following will work:

s = "true"

(s == 'true').real
1

(s == 'false').real
0

(s == 'true').conjugate()    
1

(s == '').conjugate()
0

(s == 'true').__int__()
1

(s == 'opal').__int__()    
0


def as_int(s):
    return (s == 'true').__int__()

>>>> as_int('false')
0
>>>> as_int('true')
1

Download file using libcurl in C/C++

Just for those interested you can avoid writing custom function by passing NULL as last parameter (if you do not intend to do extra processing of returned data).
In this case default internal function is used.

Details
http://curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTWRITEDATA

Example

#include <stdio.h>
#include <curl/curl.h>

int main(void)
{
    CURL *curl;
    FILE *fp;
    CURLcode res;
    char *url = "http://stackoverflow.com";
    char outfilename[FILENAME_MAX] = "page.html";
    curl = curl_easy_init();                                                                                                                                                                                                                                                           
    if (curl)
    {   
        fp = fopen(outfilename,"wb");
        curl_easy_setopt(curl, CURLOPT_URL, url);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, NULL);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
        res = curl_easy_perform(curl);
        curl_easy_cleanup(curl);
        fclose(fp);
    }   
    return 0;
}

How to remove an app with active device admin enabled on Android?

For Redmi users,

Settings -> Password & security -> Privacy -> Special app access -> Device admin apps

Click the deactivate the apps

Show/Hide Table Rows using Javascript classes

Well one way to do it would be to just put a class on the "parent" rows and remove all the ids and inline onclick attributes:

<table id="products">
    <thead>
    <tr>
        <th>Product</th>
        <th>Price</th>
        <th>Destination</th>
        <th>Updated on</th>
    </tr>
    </thead>
    <tbody>
    <tr class="parent">
        <td>Oranges</td>
        <td>100</td>
        <td><a href="#">+ On Store</a></td>
        <td>22/10</td>
    </tr>
    <tr>
        <td></td>
        <td>120</td>
        <td>City 1</td>
        <td>22/10</td>
    </tr>
    <tr>
        <td></td>
        <td>140</td>
        <td>City 2</td>
        <td>22/10</td>
    </tr>
    ...etc.
    </tbody>
</table>

And then have some CSS that hides all non-parents:

tbody tr {
    display : none;          // default is hidden
}
tr.parent {
    display : table-row;     // parents are shown
}
tr.open {
    display : table-row;     // class to be given to "open" child rows
}

That greatly simplifies your html. Note that I've added <thead> and <tbody> to your markup to make it easy to hide data rows and ignore heading rows.

With jQuery you can then simply do this:

// when an anchor in the table is clicked
$("#products").on("click","a",function(e) {
    // prevent default behaviour
    e.preventDefault();
    // find all the following TR elements up to the next "parent"
    // and toggle their "open" class
    $(this).closest("tr").nextUntil(".parent").toggleClass("open");
});

Demo: http://jsfiddle.net/CBLWS/1/

Or, to implement something like that in plain JavaScript, perhaps something like the following:

document.getElementById("products").addEventListener("click", function(e) {
    // if clicked item is an anchor
    if (e.target.tagName === "A") {
        e.preventDefault();
        // get reference to anchor's parent TR
        var row = e.target.parentNode.parentNode;
        // loop through all of the following TRs until the next parent is found
        while ((row = nextTr(row)) && !/\bparent\b/.test(row.className))
            toggle_it(row);
    }
});

function nextTr(row) {
    // find next sibling that is an element (skip text nodes, etc.)
    while ((row = row.nextSibling) && row.nodeType != 1);
    return row;
}

function toggle_it(item){ 
     if (/\bopen\b/.test(item.className))       // if item already has the class
         item.className = item.className.replace(/\bopen\b/," "); // remove it
     else                                       // otherwise
         item.className += " open";             // add it
}

Demo: http://jsfiddle.net/CBLWS/

Either way, put the JavaScript in a <script> element that is at the end of the body, so that it runs after the table has been parsed.

Angular 2 select option (dropdown) - how to get the value on change so it can be used in a function?

Another solution would be,you can get the object itself as value if you are not mentioning it's id as value: Note: [value] and [ngValue] both works here.

<select (change)="your_method(values[$event.target.selectedIndex])">
  <option *ngFor="let v of values" [value]="v" >  
    {{v.name}}
  </option>
</select>

In ts:

your_method(v:any){
  //access values here as needed. 
  // v.id or v.name
}

Note: If you are using reactive form and you want to catch selected value on form Submit, you should use [ngValue] directive instead of [value] in above scanerio

Example:

  <select (change)="your_method(values[$event.target.selectedIndex])" formControlName="form_control_name">
      <option *ngFor="let v of values" [ngValue]="v" >  
        {{v.name}}
      </option>
    </select>

In ts:

form_submit_method(){
        let v : any = this.form_group_name.value.form_control_name;  
    }

Increase Tomcat memory settings

try setting this

CATALINA_OPTS="-Djava.awt.headless=true -Dfile.encoding=UTF-8 
-server -Xms1536m -Xmx1536m
-XX:NewSize=256m -XX:MaxNewSize=256m -XX:PermSize=256m 
-XX:MaxPermSize=256m -XX:+DisableExplicitGC"

in {$tomcat-folder}\bin\setenv.sh (create it if necessary).

See http://www.mkyong.com/tomcat/tomcat-javalangoutofmemoryerror-permgen-space/ for more details.

How do you extract a JAR in a UNIX filesystem with a single command and specify its target directory using the JAR command?

Can't you just change working directory within the python script using os.chdir(target)? I agree, I can't see any way of doing it from the jar command itself.

If you don't want to permanently change directory, then store the current directory (using os.getcwd())in a variable and change back afterwards.

How do I do top 1 in Oracle?

select * from (
    select FName from MyTbl
)
where rownum <= 1;

Key hash for Android-Facebook app

Official Documentation on facebook developer site:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Add code to print out the key hash
    try {
        PackageInfo info = getPackageManager().getPackageInfo(
                "com.facebook.samples.hellofacebook", 
                PackageManager.GET_SIGNATURES);
        for (Signature signature : info.signatures) {
            MessageDigest md = MessageDigest.getInstance("SHA");
            md.update(signature.toByteArray());
            Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
            }
    } catch (NameNotFoundException e) {

    } catch (NoSuchAlgorithmException e) {

    }

Print out the values of a (Mat) matrix in OpenCV C++

#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>

#include <iostream>
#include <iomanip>

using namespace cv;
using namespace std;

int main(int argc, char** argv)
{
    double data[4] = {-0.0000000077898273846583732, -0.03749374753019832, -0.0374787251930463, -0.000000000077893623846343843};
    Mat src = Mat(1, 4, CV_64F, &data);
    for(int i=0; i<4; i++)
        cout << setprecision(3) << src.at<double>(0,i) << endl;

    return 0;
}

Axios having CORS issue

I have encountered with same issue. When I changed content type it has solved. I'm not sure this solution will help you but maybe it is. If you don't mind about content-type, it worked for me.

axios.defaults.headers.post['Content-Type'] ='application/x-www-form-urlencoded';

How to fix: Error device not found with ADB.exe

Try changing USB port. Try restarting adb server.

How to create a collapsing tree table in html/css/js?

I'll throw jsTree into the ring, too. I've found it fairly adaptable to your particular situation. It's packed as a jQuery plugin.

It can run from a variety of data sources, but my favorite is a simple nested list, as described by @joe_coolish or here:

<ul>
  <li>
    Item 1
    <ul>
      <li>Item 1.1</li>
      ...
    </ul>
  </li>
  ...
</ul>

This structure fails gracefully into a static tree when JS is not available in the client, and is easy enough to read and understand from a coding perspective.

Android studio, gradle and NDK

I have used the following code to compile native dropbox libraries, I am using Android Studio v1.1.

task nativeLibsToJar(type: Zip) {
    destinationDir file("$buildDir/native-libs")
    baseName 'native-libs'
    extension 'jar'
    from fileTree(dir: 'src/main/libs', include: '**/*.so')
    into 'lib/'
}

tasks.withType(JavaCompile) {
    compileTask -> compileTask.dependsOn(nativeLibsToJar)
}

Best way to make a shell script daemon?

Have a look at the daemon tool from the libslack package:

http://ingvar.blog.linpro.no/2009/05/18/todays-sysadmin-tip-using-libslack-daemon-to-daemonize-a-script/

On Mac OS X use a launchd script for shell daemon.

Escape double quotes in Java

For a String constant you have no choice other than escaping via backslash.

Maybe you find the MyBatis project interesting. It is a thin layer over JDBC where you can externalize your SQL queries in XML configuration files without the need to escape double quotes.

How to view the roles and permissions granted to any database user in Azure SQL server instance?

Building on @tmullaney 's answer, you can also left join in the sys.objects view to get insight when explicit permissions have been granted on objects. Make sure to use the LEFT join:

SELECT DISTINCT pr.principal_id, pr.name AS [UserName], pr.type_desc AS [User_or_Role], pr.authentication_type_desc AS [Auth_Type], pe.state_desc,
    pe.permission_name, pe.class_desc, o.[name] AS 'Object' 
    FROM sys.database_principals AS pr 
    JOIN sys.database_permissions AS pe ON pe.grantee_principal_id = pr.principal_id
    LEFT JOIN sys.objects AS o on (o.object_id = pe.major_id)

How do you use "git --bare init" repository?

I'm adding this answer because after arriving here (with the same question), none of the answers really describe all the required steps needed to go from nothing to a fully usable remote (bare) repo.

Note: this example uses local paths for the location of the bare repo, but other git protocols (like SSH indicated by the OP) should work just fine.

I've tried to add some notes along the way for those less familiar with git.

1. Initialise the bare repo...

> git init --bare /path/to/bare/repo.git
Initialised empty Git repository in /path/to/bare/repo.git/

This creates a folder (repo.git) and populates it with git files representing a git repo. As it stands, this repo is useless - it has no commits and more importantly, no branches. Although you can clone this repo, you cannot pull from it.

Next, we need to create a working folder. There are a couple of ways of doing this, depending upon whether you have existing files.

2a. Create a new working folder (no existing files) by cloning the empty repo

git clone /path/to/bare/repo.git /path/to/work
Cloning into '/path/to/work'...
warning: You appear to have cloned an empty repository.
done.

This command will only work if /path/to/work does not exist or is an empty folder. Take note of the warning - at this stage, you still don't have anything useful. If you cd /path/to/work and run git status, you'll get something like:

On branch master

Initial commit

nothing to commit (create/copy files and use "git add" to track)

but this is a lie. You are not really on branch master (because git branch returns nothing) and so far, there are no commits.

Next, copy/move/create some files in the working folder, add them to git and create the first commit.

> cd /path/to/work
> echo 123 > afile.txt
> git add .
> git config --local user.name adelphus
> git config --local user.email [email protected]
> git commit -m "added afile"
[master (root-commit) 614ab02] added afile
 1 file changed, 1 insertion(+)
 create mode 100644 afile.txt

The git config commands are only needed if you haven't already told git who you are. Note that if you now run git branch, you'll now see the master branch listed. Now run git status:

On branch master
Your branch is based on 'origin/master', but the upstream is gone.
  (use "git branch --unset-upstream" to fixup)

nothing to commit, working directory clean

This is also misleading - upstream has not "gone", it just hasn't been created yet and git branch --unset-upstream will not help. But that's OK, now that we have our first commit, we can push and master will be created on the bare repo.

> git push origin master
Counting objects: 3, done.
Writing objects: 100% (3/3), 207 bytes | 0 bytes/s, done.
Total 3 (delta 0), reused 0 (delta 0)
To /path/to/bare/repo.git
 * [new branch]      master -> master

At this point, we have a fully functional bare repo which can be cloned elsewhere on a master branch as well as a local working copy which can pull and push.

> git pull
Already up-to-date.
> git push origin master
Everything up-to-date

2b. Create a working folder from existing files If you already have a folder with files in it (so you cannot clone into it), you can initialise a new git repo, add a first commit and then link it to the bare repo afterwards.

> cd /path/to/work_with_stuff
> git init 
Initialised empty Git repository in /path/to/work_with_stuff
> git add .
# add git config stuff if needed
> git commit -m "added stuff"

[master (root-commit) 614ab02] added stuff
 20 files changed, 1431 insertions(+)
 create mode 100644 stuff.txt
...

At this point we have our first commit and a local master branch which we need to turn into a remote-tracked upstream branch.

> git remote add origin /path/to/bare/repo.git
> git push -u origin master
Counting objects: 31, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (31/31), done.
Writing objects: 100% (31/31), 43.23 KiB | 0 bytes/s, done.
Total 31 (delta 11), reused 0 (delta 0)
To /path/to/bare/repo.git
 * [new branch]      master -> master
Branch master set up to track remote branch master from origin.

Note the -u flag on git push to set the (new) tracked upstream branch. Just as before, we now have a fully functional bare repo which can be cloned elsewhere on a master branch as well as a local working copy which can pull and push.

All this may seem obvious to some, but git confuses me at the best of times (it's error and status messages really need some rework) - hopefully, this will help others.

Get ID from URL with jQuery

Just because I can:

function pathName(url, a) {
   return (a = document.createElement('a'), a.href = url, a.pathname); //optionally, remove leading '/'
}

pathName("http://www.site.com/234234234") -> "/234234234"

jquery select element by xpath

If you are debugging or similar - In chrome developer tools, you can simply use

$x('/html/.//div[@id="text"]')

Get the name of an object's type

Here is an implementation based on the accepted answer:

_x000D_
_x000D_
/**_x000D_
 * Returns the name of an object's type._x000D_
 *_x000D_
 * If the input is undefined, returns "Undefined"._x000D_
 * If the input is null, returns "Null"._x000D_
 * If the input is a boolean, returns "Boolean"._x000D_
 * If the input is a number, returns "Number"._x000D_
 * If the input is a string, returns "String"._x000D_
 * If the input is a named function or a class constructor, returns "Function"._x000D_
 * If the input is an anonymous function, returns "AnonymousFunction"._x000D_
 * If the input is an arrow function, returns "ArrowFunction"._x000D_
 * If the input is a class instance, returns "Object"._x000D_
 *_x000D_
 * @param {Object} object an object_x000D_
 * @return {String} the name of the object's class_x000D_
 * @see <a href="https://stackoverflow.com/a/332429/14731">https://stackoverflow.com/a/332429/14731</a>_x000D_
 * @see getFunctionName_x000D_
 * @see getObjectClass _x000D_
 */_x000D_
function getTypeName(object)_x000D_
{_x000D_
  const objectToString = Object.prototype.toString.call(object).slice(8, -1);_x000D_
  if (objectToString === "Function")_x000D_
  {_x000D_
    const instanceToString = object.toString();_x000D_
    if (instanceToString.indexOf(" => ") != -1)_x000D_
      return "ArrowFunction";_x000D_
    const getFunctionName = /^function ([^(]+)\(/;_x000D_
    const match = instanceToString.match(getFunctionName);_x000D_
    if (match === null)_x000D_
      return "AnonymousFunction";_x000D_
    return "Function";_x000D_
  }_x000D_
  // Built-in types (e.g. String) or class instances_x000D_
  return objectToString;_x000D_
};_x000D_
_x000D_
/**_x000D_
 * Returns the name of a function._x000D_
 *_x000D_
 * If the input is an anonymous function, returns ""._x000D_
 * If the input is an arrow function, returns "=>"._x000D_
 *_x000D_
 * @param {Function} fn a function_x000D_
 * @return {String} the name of the function_x000D_
 * @throws {TypeError} if {@code fn} is not a function_x000D_
 * @see getTypeName_x000D_
 */_x000D_
function getFunctionName(fn)_x000D_
{_x000D_
  try_x000D_
  {_x000D_
    const instanceToString = fn.toString();_x000D_
    if (instanceToString.indexOf(" => ") != -1)_x000D_
      return "=>";_x000D_
    const getFunctionName = /^function ([^(]+)\(/;_x000D_
    const match = instanceToString.match(getFunctionName);_x000D_
    if (match === null)_x000D_
    {_x000D_
      const objectToString = Object.prototype.toString.call(fn).slice(8, -1);_x000D_
      if (objectToString === "Function")_x000D_
        return "";_x000D_
      throw TypeError("object must be a Function.\n" +_x000D_
        "Actual: " + getTypeName(fn));_x000D_
    }_x000D_
    return match[1];_x000D_
  }_x000D_
  catch (e)_x000D_
  {_x000D_
    throw TypeError("object must be a Function.\n" +_x000D_
      "Actual: " + getTypeName(fn));_x000D_
  }_x000D_
};_x000D_
_x000D_
/**_x000D_
 * @param {Object} object an object_x000D_
 * @return {String} the name of the object's class_x000D_
 * @throws {TypeError} if {@code object} is not an Object_x000D_
 * @see getTypeName_x000D_
 */_x000D_
function getObjectClass(object)_x000D_
{_x000D_
  const getFunctionName = /^function ([^(]+)\(/;_x000D_
  const result = object.constructor.toString().match(getFunctionName)[1];_x000D_
  if (result === "Function")_x000D_
  {_x000D_
    throw TypeError("object must be an Object.\n" +_x000D_
      "Actual: " + getTypeName(object));_x000D_
  }_x000D_
  return result;_x000D_
};_x000D_
_x000D_
_x000D_
function UserFunction()_x000D_
{_x000D_
}_x000D_
_x000D_
function UserClass()_x000D_
{_x000D_
}_x000D_
_x000D_
let anonymousFunction = function()_x000D_
{_x000D_
};_x000D_
_x000D_
let arrowFunction = i => i + 1;_x000D_
_x000D_
console.log("getTypeName(undefined): " + getTypeName(undefined));_x000D_
console.log("getTypeName(null): " + getTypeName(null));_x000D_
console.log("getTypeName(true): " + getTypeName(true));_x000D_
console.log("getTypeName(5): " + getTypeName(5));_x000D_
console.log("getTypeName(\"text\"): " + getTypeName("text"));_x000D_
console.log("getTypeName(userFunction): " + getTypeName(UserFunction));_x000D_
console.log("getFunctionName(userFunction): " + getFunctionName(UserFunction));_x000D_
console.log("getTypeName(anonymousFunction): " + getTypeName(anonymousFunction));_x000D_
console.log("getFunctionName(anonymousFunction): " + getFunctionName(anonymousFunction));_x000D_
console.log("getTypeName(arrowFunction): " + getTypeName(arrowFunction));_x000D_
console.log("getFunctionName(arrowFunction): " + getFunctionName(arrowFunction));_x000D_
//console.log("getFunctionName(userClass): " + getFunctionName(new UserClass()));_x000D_
console.log("getTypeName(userClass): " + getTypeName(new UserClass()));_x000D_
console.log("getObjectClass(userClass): " + getObjectClass(new UserClass()));_x000D_
//console.log("getObjectClass(userFunction): " + getObjectClass(UserFunction));_x000D_
//console.log("getObjectClass(userFunction): " + getObjectClass(anonymousFunction));_x000D_
//console.log("getObjectClass(arrowFunction): " + getObjectClass(arrowFunction));_x000D_
console.log("getTypeName(nativeObject): " + getTypeName(navigator.mediaDevices.getUserMedia));_x000D_
console.log("getFunctionName(nativeObject): " + getFunctionName(navigator.mediaDevices.getUserMedia));
_x000D_
_x000D_
_x000D_

We only use the constructor property when we have no other choice.

How do I get today's date in C# in mm/dd/yyyy format?

DateTime.Now.ToString("dd/MM/yyyy");

MySQL Trigger - Storing a SELECT in a variable

`CREATE TRIGGER `category_before_ins_tr` BEFORE INSERT ON `category`
  FOR EACH ROW
BEGIN
    **SET @tableId= (SELECT id FROM dummy LIMIT 1);**

END;`;

How to disable an Android button?

first in xml make the button as android:clickable="false"

<Button
        android:id="@+id/btn_send"
        android:clickable="false"/>

then in your code, inside oncreate() method set the button property as

btn.setClickable(true);

then inside the button click change the code into

btn.setClickable(false);

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    btnSend = (Button) findViewById(R.id.btn_send);
    btnSend.setClickable(true);
    btnSend.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            btnSend.setClickable(false);

        }
    });
}

How to compare 2 dataTables

or this, I did not implement the array comparison so you will also have some fun :)

public bool CompareTables(DataTable a, DataTable b)
{
    if(a.Rows.Count != b.Rows.Count)
    {
        // different size means different tables
        return false;
    }

    for(int rowIndex=0; rowIndex<a.Rows.Count; ++rowIndex)
    {
        if(!arraysHaveSameContent(a.Rows[rowIndex].ItemArray, b.Rows[rowIndex].ItemArray,))
        {
            return false;
        }
    }

    // Tables have same data
    return true;
}

private bool arraysHaveSameContent(object[] a, object[] b)
{
    // Here your super cool method to compare the two arrays with LINQ,
    // or if you are a loser do it with a for loop :D
}

Bash mkdir and subfolders

FWIW,

Poor mans security folder (to protect a public shared folder from little prying eyes ;) )

mkdir -p {0..9}/{0..9}/{0..9}/{0..9}

Now you can put your files in a pin numbered folder. Not exactly waterproof, but it's a barrier for the youngest.

Format decimal for percentage values?

I have found the above answer to be the best solution, but I don't like the leading space before the percent sign. I have seen somewhat complicated solutions, but I just use this Replace addition to the answer above instead of using other rounding solutions.

String.Format("Value: {0:P2}.", 0.8526).Replace(" %","%") // formats as 85.26% (varies by culture)

What does Include() do in LINQ?

Think of it as enforcing Eager-Loading in a scenario where you sub-items would otherwise be lazy-loading.

The Query EF is sending to the database will yield a larger result at first, but on access no follow-up queries will be made when accessing the included items.

On the other hand, without it, EF would execute separte queries later, when you first access the sub-items.

Run a PostgreSQL .sql file using command line arguments

Walk through on how to run an SQL on the command line for PostgreSQL in Linux:

Open a terminal and make sure you can run the psql command:

psql --version
which psql

Mine is version 9.1.6 located in /bin/psql.

Create a plain textfile called mysqlfile.sql

Edit that file, put a single line in there:

select * from mytable;

Run this command on commandline (substituting your username and the name of your database for pgadmin and kurz_prod):

psql -U pgadmin -d kurz_prod -a -f mysqlfile.sql

The following is the result I get on the terminal (I am not prompted for a password):

select * from mytable;

test1
--------
hi
me too

(2 rows)

How to convert a factor to integer\numeric without loss of information?

Note: this particular answer is not for converting numeric-valued factors to numerics, it is for converting categorical factors to their corresponding level numbers.


Every answer in this post failed to generate results for me , NAs were getting generated.

y2<-factor(c("A","B","C","D","A")); 
as.numeric(levels(y2))[y2] 
[1] NA NA NA NA NA Warning message: NAs introduced by coercion

What worked for me is this -

as.integer(y2)
# [1] 1 2 3 4 1

Call a method of a controller from another controller using 'scope' in AngularJS

The best approach for you to communicate between the two controllers is to use events.

Scope Documentation

In this check out $on, $broadcast and $emit.

In general use case the usage of angular.element(catapp).scope() was designed for use outside the angular controllers, like within jquery events.

Ideally in your usage you would write an event in controller 1 as:

$scope.$on("myEvent", function (event, args) {
   $scope.rest_id = args.username;
   $scope.getMainCategories();
});

And in the second controller you'd just do

$scope.initRestId = function(){
   $scope.$broadcast("myEvent", {username: $scope.user.username });
};

Edit: Realised it was communication between two modules

Can you try including the firstApp module as a dependency to the secondApp where you declare the angular.module. That way you can communicate to the other app.

sql use statement with variable

try this:

DECLARE @Query         varchar(1000)
DECLARE @DatabaseName  varchar(500)

SET @DatabaseName='xyz'
SET @Query='SELECT * FROM Server.'+@DatabaseName+'.Owner.Table1'
EXEC (@Query)

SET @DatabaseName='abc'
SET @Query='SELECT * FROM Server.'+@DatabaseName+'.Owner.Table2'
EXEC (@Query)

C++ inheritance - inaccessible base?

By default, inheritance is private. You have to explicitly use public:

class Bar : public Foo

See :hover state in Chrome Developer Tools

In case it helps, this seems to be easier in the latest Chrome (47.0.2526.106):

Inspect element and then click on the three white dots in the left gutter:
click on the three white dots

Then choose the desired element state from this dropdown:
this dropdown

how to force maven to update local repo

You can also use this command on the command line:

mvn dependency:purge-local-repository clean install

How to install grunt and how to build script with it

I got the same issue, but i solved it with changing my Grunt.js to Gruntfile.js Check your file name before typing grunt.cmd on windows cmd (if you're using windows).

How to escape JSON string?

I ran speed tests on some of these answers for a long string and a short string. Clive Paterson's code won by a good bit, presumably because the others are taking into account serialization options. Here are my results:

Apple Banana
System.Web.HttpUtility.JavaScriptStringEncode: 140ms
System.Web.Helpers.Json.Encode: 326ms
Newtonsoft.Json.JsonConvert.ToString: 230ms
Clive Paterson: 108ms

\\some\long\path\with\lots\of\things\to\escape\some\long\path\t\with\lots\of\n\things\to\escape\some\long\path\with\lots\of\"things\to\escape\some\long\path\with\lots"\of\things\to\escape
System.Web.HttpUtility.JavaScriptStringEncode: 2849ms
System.Web.Helpers.Json.Encode: 3300ms
Newtonsoft.Json.JsonConvert.ToString: 2827ms
Clive Paterson: 1173ms

And here is the test code:

public static void Main(string[] args)
{
    var testStr1 = "Apple Banana";
    var testStr2 = @"\\some\long\path\with\lots\of\things\to\escape\some\long\path\t\with\lots\of\n\things\to\escape\some\long\path\with\lots\of\""things\to\escape\some\long\path\with\lots""\of\things\to\escape";

    foreach (var testStr in new[] { testStr1, testStr2 })
    {
        var results = new Dictionary<string,List<long>>();

        for (var n = 0; n < 10; n++)
        {
            var count = 1000 * 1000;

            var sw = Stopwatch.StartNew();
            for (var i = 0; i < count; i++)
            {
                var s = System.Web.HttpUtility.JavaScriptStringEncode(testStr);
            }
            var t = sw.ElapsedMilliseconds;
            results.GetOrCreate("System.Web.HttpUtility.JavaScriptStringEncode").Add(t);

            sw = Stopwatch.StartNew();
            for (var i = 0; i < count; i++)
            {
                var s = System.Web.Helpers.Json.Encode(testStr);
            }
            t = sw.ElapsedMilliseconds;
            results.GetOrCreate("System.Web.Helpers.Json.Encode").Add(t);

            sw = Stopwatch.StartNew();
            for (var i = 0; i < count; i++)
            {
                var s = Newtonsoft.Json.JsonConvert.ToString(testStr);
            }
            t = sw.ElapsedMilliseconds;
            results.GetOrCreate("Newtonsoft.Json.JsonConvert.ToString").Add(t);

            sw = Stopwatch.StartNew();
            for (var i = 0; i < count; i++)
            {
                var s = cleanForJSON(testStr);
            }
            t = sw.ElapsedMilliseconds;
            results.GetOrCreate("Clive Paterson").Add(t);
        }

        Console.WriteLine(testStr);
        foreach (var result in results)
        {
            Console.WriteLine(result.Key + ": " + Math.Round(result.Value.Skip(1).Average()) + "ms");
        }
        Console.WriteLine();
    }

    Console.ReadLine();
}

How to check internet access on Android? InetAddress never times out

public class Network {

Context context;

public Network(Context context){
    this.context = context;
}

public boolean isOnline() {
    ConnectivityManager cm =
            (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    return activeNetwork != null &&
                          activeNetwork.isConnectedOrConnecting();
}

}

Android Gradle 5.0 Update:Cause: org.jetbrains.plugins.gradle.tooling.util

The easiest way I've found is delete Android Studio from the applications folder, then download & install it again.

Example using Hyperlink in WPF

In addition to Fuji's response, we can make the handler reusable turning it into an attached property:

public static class HyperlinkExtensions
{
    public static bool GetIsExternal(DependencyObject obj)
    {
        return (bool)obj.GetValue(IsExternalProperty);
    }

    public static void SetIsExternal(DependencyObject obj, bool value)
    {
        obj.SetValue(IsExternalProperty, value);
    }
    public static readonly DependencyProperty IsExternalProperty =
        DependencyProperty.RegisterAttached("IsExternal", typeof(bool), typeof(HyperlinkExtensions), new UIPropertyMetadata(false, OnIsExternalChanged));

    private static void OnIsExternalChanged(object sender, DependencyPropertyChangedEventArgs args)
    {
        var hyperlink = sender as Hyperlink;

        if ((bool)args.NewValue)
            hyperlink.RequestNavigate += Hyperlink_RequestNavigate;
        else
            hyperlink.RequestNavigate -= Hyperlink_RequestNavigate;
    }

    private static void Hyperlink_RequestNavigate(object sender, System.Windows.Navigation.RequestNavigateEventArgs e)
    {
        Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri));
        e.Handled = true;
    }
}

And use it like this:

<TextBlock>
    <Hyperlink NavigateUri="https://stackoverflow.com"
               custom:HyperlinkExtensions.IsExternal="true">
        Click here
    </Hyperlink>
</TextBlock>

Add jars to a Spark Job - spark-submit

Other configurable Spark option relating to jars and classpath, in case of yarn as deploy mode are as follows
From the spark documentation,

spark.yarn.jars

List of libraries containing Spark code to distribute to YARN containers. By default, Spark on YARN will use Spark jars installed locally, but the Spark jars can also be in a world-readable location on HDFS. This allows YARN to cache it on nodes so that it doesn't need to be distributed each time an application runs. To point to jars on HDFS, for example, set this configuration to hdfs:///some/path. Globs are allowed.

spark.yarn.archive

An archive containing needed Spark jars for distribution to the YARN cache. If set, this configuration replaces spark.yarn.jars and the archive is used in all the application's containers. The archive should contain jar files in its root directory. Like with the previous option, the archive can also be hosted on HDFS to speed up file distribution.

Users can configure this parameter to specify their jars, which inturn gets included in Spark driver's classpath.

Header and footer in CodeIgniter

Here's what I do:

<?php

/**
 * /application/core/MY_Loader.php
 *
 */
class MY_Loader extends CI_Loader {
    public function template($template_name, $vars = array(), $return = FALSE)
    {
        $content  = $this->view('templates/header', $vars, $return);
        $content .= $this->view($template_name, $vars, $return);
        $content .= $this->view('templates/footer', $vars, $return);

        if ($return)
        {
            return $content;
        }
    }
}

For CI 3.x:

class MY_Loader extends CI_Loader {
    public function template($template_name, $vars = array(), $return = FALSE)
    {
        if($return):
        $content  = $this->view('templates/header', $vars, $return);
        $content .= $this->view($template_name, $vars, $return);
        $content .= $this->view('templates/footer', $vars, $return);

        return $content;
    else:
        $this->view('templates/header', $vars);
        $this->view($template_name, $vars);
        $this->view('templates/footer', $vars);
    endif;
    }
}

Then, in your controller, this is all you have to do:

<?php
$this->load->template('body');

phpMyAdmin ERROR: mysqli_real_connect(): (HY000/1045): Access denied for user 'pma'@'localhost' (using password: NO)

My default 3306 port was in use, so Ive changed it to 8111, then I had this error. Ive fixed it by adding

$cfg['Servers'][$i]['port'] = '8111';

into config.inc.php . If you are using different port number then set yours.

SQL how to make null values come last when sorting ascending

If you're using MariaDB, they mention the following in the NULL Values documentation.

Ordering

When you order by a field that may contain NULL values, any NULLs are considered to have the lowest value. So ordering in DESC order will see the NULLs appearing last. To force NULLs to be regarded as highest values, one can add another column which has a higher value when the main field is NULL. Example:

SELECT col1 FROM tab ORDER BY ISNULL(col1), col1;

Descending order, with NULLs first:

SELECT col1 FROM tab ORDER BY IF(col1 IS NULL, 0, 1), col1 DESC;

All NULL values are also regarded as equivalent for the purposes of the DISTINCT and GROUP BY clauses.

The above shows two ways to order by NULL values, you can combine these with the ASC and DESC keywords as well. For example the other way to get the NULL values first would be:

SELECT col1 FROM tab ORDER BY ISNULL(col1) DESC, col1;
--                                         ^^^^

How do I exclude Weekend days in a SQL Server query?

When dealing with day-of-week calculations, it's important to take account of the current DATEFIRST settings. This query will always correctly exclude weekend days, using @@DATEFIRST to account for any possible setting for the first day of the week.

SELECT *
FROM your_table
WHERE ((DATEPART(dw, date_created) + @@DATEFIRST) % 7) NOT IN (0, 1)

how to change namespace of entire project?

I know its quite late but for anyone looking to do it from now on, I hope this answer proves of some help. If you have CodeRush Express (free version, and a 'must have') installed, it offers a simple way to change a project wide namespace. You just place your cursor on the namespace that you want to change and it shall display a smart tag (a little blue box) underneath namespace string. You can either click that box or press Ctrl + keys to see the Rename option. Select it and then type in the new name for the project wide namespace, click Apply and select what places in your project you'd want it to change, in the new dialog and OK it. Done! :-)

Can I disable a CSS :hover effect via JavaScript?

I used the not() CSS operator and jQuery's addClass() function. Here is an example, when you click on a list item, it won't hover anymore:

For example:

HTML

<ul class="vegies">
    <li>Onion</li>
    <li>Potato</li>
    <li>Lettuce</li>
<ul>

CSS

.vegies li:not(.no-hover):hover { color: blue; }

jQuery

$('.vegies li').click( function(){
    $(this).addClass('no-hover');
});

JavaScript get child element

ULs don't have a name attribute, but you can reference the ul by tag name.

Try replacing line 3 in your script with this:

var sub = cat.getElementsByTagName("UL");

How to detect the device orientation using CSS media queries?

I would go for aspect-ratio, it offers way more possibilities.

/* Exact aspect ratio */
@media (aspect-ratio: 2/1) {
    ...
}

/* Minimum aspect ratio */
@media (min-aspect-ratio: 16/9) {
    ...
}

/* Maximum aspect ratio */
@media (max-aspect-ratio: 8/5) {
    ...
}

Both, orientation and aspect-ratio depend on the actual size of the viewport and have nothing todo with the device orientation itself.

Read more: https://dev.to/ananyaneogi/useful-css-media-query-features-o7f

Android WebView progress bar

It's true, there are also more complete option, like changing the name of the app for a sentence you want. Check this tutorial it can help:

http://www.firstdroid.com/2010/08/04/adding-progress-bar-on-webview-android-tutorials/

In that tutorial you have a complete example how to use the progressbar in a webview app.

Adrian.

How to Run a jQuery or JavaScript Before Page Start to Load

Don't use $(document).ready() just put the script directly in the head section of the page. Pages are processed top to bottom so things at the top are processed first.

How to align an indented line in a span that wraps into multiple lines?

Also you can try to use

display:inline-block;

if you would like the span element to align horizontally.

Incase you would like to align span elements vertically, just use

 display:block;

Spring @Transactional - isolation, propagation

PROPAGATION_REQUIRED = 0; If DataSourceTransactionObject T1 is already started for Method M1. If for another Method M2 Transaction object is required, no new Transaction object is created. Same object T1 is used for M2.

PROPAGATION_MANDATORY = 2; method must run within a transaction. If no existing transaction is in progress, an exception will be thrown.

PROPAGATION_REQUIRES_NEW = 3; If DataSourceTransactionObject T1 is already started for Method M1 and it is in progress (executing method M1). If another method M2 start executing then T1 is suspended for the duration of method M2 with new DataSourceTransactionObject T2 for M2. M2 run within its own transaction context.

PROPAGATION_NOT_SUPPORTED = 4; If DataSourceTransactionObject T1 is already started for Method M1. If another method M2 is run concurrently. Then M2 should not run within transaction context. T1 is suspended till M2 is finished.

PROPAGATION_NEVER = 5; None of the methods run in transaction context.


An isolation level: It is about how much a transaction may be impacted by the activities of other concurrent transactions. It a supports consistency leaving the data across many tables in a consistent state. It involves locking rows and/or tables in a database.

The problem with multiple transaction

Scenario 1. If T1 transaction reads data from table A1 that was written by another concurrent transaction T2. If on the way T2 is rollback, the data obtained by T1 is invalid one. E.g. a=2 is original data. If T1 read a=1 that was written by T2. If T2 rollback then a=1 will be rollback to a=2 in DB. But, now, T1 has a=1 but in DB table it is changed to a=2.

Scenario2. If T1 transaction reads data from table A1. If another concurrent transaction (T2) update data on table A1. Then the data that T1 has read is different from table A1. Because T2 has updated the data on table A1. E.g. if T1 read a=1 and T2 updated a=2. Then a!=b.

Scenario 3. If T1 transaction reads data from table A1 with certain number of rows. If another concurrent transaction (T2) inserts more rows on table A1. The number of rows read by T1 is different from rows on table A1.

Scenario 1 is called Dirty reads.

Scenario 2 is called Non-repeatable reads.

Scenario 3 is called Phantom reads.

So, isolation level is the extend to which Scenario 1, Scenario 2, Scenario 3 can be prevented. You can obtain complete isolation level by implementing locking. That is preventing concurrent reads and writes to the same data from occurring. But it affects performance. The level of isolation depends upon application to application how much isolation is required.

ISOLATION_READ_UNCOMMITTED: Allows to read changes that haven’t yet been committed. It suffer from Scenario 1, Scenario 2, Scenario 3.

ISOLATION_READ_COMMITTED: Allows reads from concurrent transactions that have been committed. It may suffer from Scenario 2 and Scenario 3. Because other transactions may be updating the data.

ISOLATION_REPEATABLE_READ: Multiple reads of the same field will yield the same results untill it is changed by itself. It may suffer from Scenario 3. Because other transactions may be inserting the data.

ISOLATION_SERIALIZABLE: Scenario 1, Scenario 2, Scenario 3 never happen. It is complete isolation. It involves full locking. It affects performace because of locking.

You can test using:

public class TransactionBehaviour {
   // set is either using xml Or annotation
    DataSourceTransactionManager manager=new DataSourceTransactionManager();
    SimpleTransactionStatus status=new SimpleTransactionStatus();
   ;
  
    
    public void beginTransaction()
    {
        DefaultTransactionDefinition Def = new DefaultTransactionDefinition();
        // overwrite default PROPAGATION_REQUIRED and ISOLATION_DEFAULT
        // set is either using xml Or annotation
        manager.setPropagationBehavior(XX);
        manager.setIsolationLevelName(XX);
       
        status = manager.getTransaction(Def);
    
    }

    public void commitTransaction()
    {
       
      
            if(status.isCompleted()){
                manager.commit(status);
        } 
    }

    public void rollbackTransaction()
    {
       
            if(!status.isCompleted()){
                manager.rollback(status);
        }
    }
    Main method{
        beginTransaction()
        M1();
        If error(){
            rollbackTransaction()
        }
         commitTransaction();
    }
   
}

You can debug and see the result with different values for isolation and propagation.

python: urllib2 how to send cookie with urlopen request

Cookie is just another HTTP header.

import urllib2
opener = urllib2.build_opener()
opener.addheaders.append(('Cookie', 'cookiename=cookievalue'))
f = opener.open("http://example.com/")

See urllib2 examples for other ways how to add HTTP headers to your request.

There are more ways how to handle cookies. Some modules like cookielib try to behave like web browser - remember what cookies did you get previously and automatically send them again in following requests.

Keyboard shortcut to paste clipboard content into command prompt window (Win XP)

Thanks, Pablo, for referring to AutoHotkey utility. Since I have Launchy installed which uses Alt+Space I had to modify it a but to add Shift key as shown:

; Paste in command window
^V::
; Spanish menu (Editar->Pegar, I suppose English version is the same, Edit->Paste)
Send !+{Space}ep
return

WAMP Server doesn't load localhost

Change the port 80 to port 8080 and restart all services and access like localhost:8080/

It will work fine.

How can I view the Git history in Visual Studio Code?

You won't need a plugin to see commit history with Visual Studio Code 1.42 or more.

Timeline view

In this milestone, we've made progress on the new Timeline view, and have an early preview to share.
This is a unified view for visualizing time-series events (e.g. commits, saves, test runs, etc.) for a resource (file, folder, etc.).

To enable the Timeline view, you must be using the Insiders Edition (VSCode 1.44 March 2020) and then add the following setting:

"timeline.showView": true

https://media.githubusercontent.com/media/microsoft/vscode-docs/vnext/release-notes/images/1_42/timeline.png

Looking for a short & simple example of getters/setters in C#

My explanation would be following. (It's not so short, but it's quite simple.)


Imagine a class with a variable:

class Something
{
    int weight;
    // and other methods, of course, not shown here
}

Well, there is a small problem with this class: no one can see the weight. We could make weight public, but then everyone would be able to change the weight at any moment (which is perhaps not what we want). So, well, we can do a function:

class Something
{
    int weight;
    public int GetWeight() { return weight; }
    // and other methods
}

This is already better, but now everyone instead of plain something.Weight has to type something.GetWeight(), which is, well, ugly.

With properties, we can do the same, but the code stays clean:

class Something
{
    public int weight { get; private set; }
    // and other methods
}

int w = something.weight // works!
something.weight = x; // doesn't even compile

Nice, so with the properties we have finer control over the variable access.

Another problem: okay, we want the outer code to be able to set weight, but we'd like to control its value, and not allow the weights lower than 100. Moreover, there are is some other inner variable density, which depends on weight, so we'd want to recalculate the density as soon as the weight changes.

This is traditionally achieved in the following way:

class Something
{
    int weight;
    public int SetWeight(int w)
    {
        if (w < 100)
            throw new ArgumentException("weight too small");
        weight = w;
        RecalculateDensity();
    }
    // and other methods
}

something.SetWeight(anotherSomething.GetWeight() + 1);

But again, we don't want expose to our clients that setting the weight is a complicated operation, it's semantically nothing but assigning a new weight. So the code with a setter looks the same way, but nicer:

class Something
{
    private int _w;
    public int Weight
    {
        get { return _w; }
        set
        {
            if (value < 100)
                throw new ArgumentException("weight too small");
            _w = value;
            RecalculateDensity();
        }
    }
    // and other methods
}

something.Weight = otherSomething.Weight + 1; // much cleaner, right?

So, no doubt, properties are "just" a syntactic sugar. But it makes the client's code be better. Interestingly, the need for property-like things arises very often, you can check how often you find the functions like GetXXX() and SetXXX() in the other languages.

How can I permanently enable line numbers in IntelliJ?

Ok in intelliJ 14 Ultimate using the Mac version this is it.

IntelliJ Idea > Preferences > Editor > General > Appearance > Show Line Numbers

Add a fragment to the URL without causing a redirect?

For straight HTML, with no JavaScript required:

<a href="#something">Add '#something' to URL</a>

Or, to take your question more literally, to just add '#' to the URL:

<a href="#">Add '#' to URL</a>

Calculate RSA key fingerprint

On Windows, if you're running PuTTY/Pageant, the fingerprint is listed when you load your PuTTY (.ppk) key into Pageant. It is pretty useful in case you forget which one you're using.

Enter image description here

how to split the ng-repeat data with three columns using bootstrap

I found myself in a similar case, wanting to generate display groups of 3 columns each. However, although I was using bootstrap, I was trying to separate these groups into different parent divs. I also wanted to make something generically useful.

I approached it with 2 ng-repeat as below:

<div ng-repeat="items in quotes" ng-if="!($index % 3)">
  <div ng-repeat="quote in quotes" ng-if="$index <= $parent.$index + 2 && $index >= $parent.$index">
                ... some content ...
  </div>
</div>

This makes it very easy to change to a different number of columns, and separated out into several parent divs.

How to serialize an object to XML without getting xmlns="..."?

I Suggest this helper class:

public static class Xml
{
    #region Fields

    private static readonly XmlWriterSettings WriterSettings = new XmlWriterSettings {OmitXmlDeclaration = true, Indent = true};
    private static readonly XmlSerializerNamespaces Namespaces = new XmlSerializerNamespaces(new[] {new XmlQualifiedName("", "")});

    #endregion

    #region Methods

    public static string Serialize(object obj)
    {
        if (obj == null)
        {
            return null;
        }

        return DoSerialize(obj);
    }

    private static string DoSerialize(object obj)
    {
        using (var ms = new MemoryStream())
        using (var writer = XmlWriter.Create(ms, WriterSettings))
        {
            var serializer = new XmlSerializer(obj.GetType());
            serializer.Serialize(writer, obj, Namespaces);
            return Encoding.UTF8.GetString(ms.ToArray());
        }
    }

    public static T Deserialize<T>(string data)
        where T : class
    {
        if (string.IsNullOrEmpty(data))
        {
            return null;
        }

        return DoDeserialize<T>(data);
    }

    private static T DoDeserialize<T>(string data) where T : class
    {
        using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(data)))
        {
            var serializer = new XmlSerializer(typeof (T));
            return (T) serializer.Deserialize(ms);
        }
    }

    #endregion
}

:)

How to use boolean datatype in C?

C99 introduced _Bool as intrinsic pure boolean type. No #includes needed:

int main(void)
{
  _Bool b = 1;
  b = 0;
}

On a true C99 (or higher) compliant C compiler the above code should compile perfectly fine.

How to change color of ListView items on focus and on click

<selector xmlns:android="http://schemas.android.com/apk/res/android" >    
    <item android:state_pressed="true" android:drawable="@drawable/YOUR DRAWABLE XML" /> 
    <item android:drawable="@drawable/YOUR DRAWABLE XML" />
</selector>

allowing only alphabets in text box using java script

just use onkeypress event like below:

<input type="text" name="onlyalphabet" onkeypress="return (event.charCode > 64 && event.charCode < 91) || (event.charCode > 96 && event.charCode < 123)">

'Conda' is not recognized as internal or external command

This problem arose for me when I installed Anaconda multiple times. I was careful to do an uninstall but there are some things that the uninstall process doesn't undo.

In my case, I needed to remove a file Microsoft.PowerShell_profile.ps1 from ~\Documents\WindowsPowerShell\. I identified that this file was the culprit by opening it in a text editor. I saw that it referenced the old installation location C:\Anaconda3\.

Flutter : Vertically center column

You could use. mainAxisAlignment:MainAxisAlignment.center This will the material through the center in the column wise. `crossAxisAlignment: CrossAxisAlignment.center' This will align the items in the center in the row wise.

Container( alignment:Alignment.center, Child: Column () )

Simply use. Center ( Child: Column () ) or rap with Padding widget . And adjust the Padding such the the column children are in the center.

How can I turn a DataTable to a CSV?

4 lines of code:

public static string ToCSV(DataTable tbl)
{
    StringBuilder strb = new StringBuilder();

    //column headers
    strb.AppendLine(string.Join(",", tbl.Columns.Cast<DataColumn>()
        .Select(s => "\"" + s.ColumnName + "\"")));

    //rows
    tbl.AsEnumerable().Select(s => strb.AppendLine(
        string.Join(",", s.ItemArray.Select(
            i => "\"" + i.ToString() + "\"")))).ToList();

    return strb.ToString();
}

Note that the ToList() at the end is important; I need something to force an expression evaluation. If I was code golfing, I could use Min() instead.

Also note that the result will have a newline at the end because of the last call to AppendLine(). You may not want this. You can simply call TrimEnd() to remove it.

How to check if a string contains text from an array of substrings in JavaScript?

Javascript function to search an array of tags or keywords using a search string or an array of search strings. (Uses ES5 some array method and ES6 arrow functions)

// returns true for 1 or more matches, where 'a' is an array and 'b' is a search string or an array of multiple search strings
function contains(a, b) {
    // array matches
    if (Array.isArray(b)) {
        return b.some(x => a.indexOf(x) > -1);
    }
    // string match
    return a.indexOf(b) > -1;
}

Example usage:

var a = ["a","b","c","d","e"];
var b = ["a","b"];
if ( contains(a, b) ) {
    // 1 or more matches found
}

How to give a user only select permission on a database

You could add the user to the Database Level Role db_datareader.

Members of the db_datareader fixed database role can run a SELECT statement against any table or view in the database.

See Books Online for reference:

http://msdn.microsoft.com/en-us/library/ms189121%28SQL.90%29.aspx

You can add a database user to a database role using the following query:

EXEC sp_addrolemember N'db_datareader', N'userName'

How to check if a column exists in a SQL Server table?

This worked for me in SQL 2000:

IF EXISTS 
(
    SELECT * 
    FROM INFORMATION_SCHEMA.COLUMNS 
    WHERE table_name = 'table_name' 
    AND column_name = 'column_name'
)
BEGIN
...
END

Getting content/message from HttpResponseMessage

You can use the GetStringAsync method:

var uri = new Uri("http://yoururlhere");
var response = await client.GetStringAsync(uri);

Using ffmpeg to change framerate

To the best of my knowledge you can't do this with ffmpeg without re-encoding. I had a 24fps file I wanted at 25fps to match some other material I was working with. I used the command ffmpeg -i inputfile -r 25 outputfile which worked perfectly with a webm,matroska input and resulted in an h264, matroska output utilizing encoder: Lavc56.60.100

You can accomplish the same thing at 6fps but as you noted the duration will not change (which in most cases is a good thing as otherwise you will lose audio sync). If this doesn't fit your requirements I suggest that you try this answer although my experience has been that it still re-encodes the output file.

For the best frame accuracy you are still better off decoding to raw streams as previously suggested. I use a script for this as reproduced below:

#!/bin/bash
#This script will decompress all files in the current directory, video to huffyuv and audio to PCM
#unsigned 8-bit and place the output #in an avi container to ease frame accurate editing.
for f in *
do
ffmpeg -i "$f" -c:v huffyuv -c:a pcm_u8 "$f".avi
done

Clearly this script expects all files in the current directory to be media files but can easily be changed to restrict processing to a specific extension of your choosing. Be aware that your file size will increase by a rather large factor when you decompress into raw streams.

Matplotlib tight_layout() doesn't take into account figure suptitle

I had a similar issue that cropped up when using tight_layout for a very large grid of plots (more than 200 subplots) and rendering in a jupyter notebook. I made a quick solution that always places your suptitle at a certain distance above your top subplot:

import matplotlib.pyplot as plt

n_rows = 50
n_col = 4
fig, axs = plt.subplots(n_rows, n_cols)

#make plots ...

# define y position of suptitle to be ~20% of a row above the top row
y_title_pos = axs[0][0].get_position().get_points()[1][1]+(1/n_rows)*0.2
fig.suptitle('My Sup Title', y=y_title_pos)

For variably-sized subplots, you can still use this method to get the top of the topmost subplot, then manually define an additional amount to add to the suptitle.

Android Whatsapp/Chat Examples

Check out yowsup
https://github.com/tgalal/yowsup

Yowsup is a python library that allows you to do all the previous in your own app. Yowsup allows you to login and use the Whatsapp service and provides you with all capabilities of an official Whatsapp client, allowing you to create a full-fledged custom Whatsapp client.

A solid example of Yowsup's usage is Wazapp. Wazapp is full featured Whatsapp client that is being used by hundreds of thousands of people around the world. Yowsup is born out of the Wazapp project. Before becoming a separate project, it was only the engine powering Wazapp. Now that it matured enough, it was separated into a separate project, allowing anyone to build their own Whatsapp client on top of it. Having such a popular client as Wazapp, built on Yowsup, helped bring the project into a much advanced, stable and mature level, and ensures its continuous development and maintaince.

Yowsup also comes with a cross platform command-line frontend called yowsup-cli. yowsup-cli allows you to jump into connecting and using Whatsapp service directly from command line.

Reading an Excel file in python using pandas

Thought i should add here, that if you want to access rows or columns to loop through them, you do this:

import pandas as pd

# open the file
xlsx = pd.ExcelFile("PATH\FileName.xlsx")

# get the first sheet as an object
sheet1 = xlsx.parse(0)
    
# get the first column as a list you can loop through
# where the is 0 in the code below change to the row or column number you want    
column = sheet1.icol(0).real

# get the first row as a list you can loop through
row = sheet1.irow(0).real

Edit:

The methods icol(i) and irow(i) are deprecated now. You can use sheet1.iloc[:,i] to get the i-th col and sheet1.iloc[i,:] to get the i-th row.

C++ "was not declared in this scope" compile error

grid is not present on nonrecursivecountcells's scope.

Either make grid a global array, or pass it as a parameter to the function.

Visual Studio can't build due to rc.exe

This might be a little outdated. But if copying the rc.exe and exdll.dll did not work, there is a chance that the windows sdk is not installed properly even if the windows sdk folder exists. You can update the sdk for win 8 in the following page: http://msdn.microsoft.com/en-US/windows/hardware/hh852363 After re-installing the sdk, the problem would get solved. Also make sure that platform toolset is set properly.

How to get length of a list of lists in python

You can do it with reduce:

a = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [], [1, 2]]
print(reduce(lambda count, l: count + len(l), a, 0))
# result is 11

Query to search all packages for table and/or column

you can use the views *_DEPENDENCIES, for example:

SELECT owner, NAME
  FROM dba_dependencies
 WHERE referenced_owner = :table_owner
   AND referenced_name = :table_name
   AND TYPE IN ('PACKAGE', 'PACKAGE BODY')

Add a new line to the end of a JtextArea

Instead of using JTextArea.setText(String text), use JTextArea.append(String text).

Appends the given text to the end of the document. Does nothing if the model is null or the string is null or empty.

This will add text on to the end of your JTextArea.

Another option would be to use getText() to get the text from the JTextArea, then manipulate the String (add or remove or change the String), then use setText(String text) to set the text of the JTextArea to be the new String.

NPM: npm-cli.js not found when running npm

npm install -g npm@[version] fixed the problem

What is the difference between "mvn deploy" to a local repo and "mvn install"?

From the Maven docs, sounds like it's just a difference in which repository you install the package into:

  • install - install the package into the local repository, for use as a dependency in other projects locally
  • deploy - done in an integration or release environment, copies the final package to the remote repository for sharing with other developers and projects.

Maybe there is some confusion in that "install" to the CI server installs it to it's local repository, which then you as a user are sharing?

How to sort the files according to the time stamp in unix?

File modification:

ls -t

Inode change:

ls -tc

File access:

ls -tu

"Newest" one at the bottom:

ls -tr

None of this is a creation time. Most Unix filesystems don't support creation timestamps.

Pass table as parameter into sql server UDF

You can, however no any table. From documentation:

For Transact-SQL functions, all data types, including CLR user-defined types and user-defined table types, are allowed except the timestamp data type.

You can use user-defined table types.

Example of user-defined table type:

CREATE TYPE TableType 
AS TABLE (LocationName VARCHAR(50))
GO 

DECLARE @myTable TableType
INSERT INTO @myTable(LocationName) VALUES('aaa')
SELECT * FROM @myTable

So what you can do is to define your table type, for example TableType and define the function which takes the parameter of this type. An example function:

CREATE FUNCTION Example( @TableName TableType READONLY)
RETURNS VARCHAR(50)
AS
BEGIN
    DECLARE @name VARCHAR(50)

    SELECT TOP 1 @name = LocationName FROM @TableName
    RETURN @name
END

The parameter has to be READONLY. And example usage:

DECLARE @myTable TableType
INSERT INTO @myTable(LocationName) VALUES('aaa')
SELECT * FROM @myTable

SELECT dbo.Example(@myTable)

Depending on what you want achieve you can modify this code.

EDIT: If you have a data in a table you may create a variable:

DECLARE @myTable TableType

And take data from your table to the variable

INSERT INTO @myTable(field_name)
SELECT field_name_2 FROM my_other_table

Combining the results of two SQL queries as separate columns

how to club the 4 query's as a single query

show below query

  1. total number of cases pending + 2.cases filed during this month ( base on sysdate) + total number of cases (1+2) + no. cases disposed where nse= disposed + no. of cases pending (other than nse <> disposed)

nsc = nature of case

report is taken on 06th of every month

( monthly report will be counted from 05th previous month to 05th present of present month)

using favicon with css

You don't need to - if the favicon is place in the root at favicon.ico, browsers will automatically pick it up.

If you don't see it working, clear your cache etc, it does work without the markup. You only need to use the code if you want to call it something else, or put it on a CDN for instance.

onCreateOptionsMenu inside Fragments

I tried the @Alexander Farber and @Sino Raj answers. Both answers are nice, but I couldn't use the onCreateOptionsMenu inside my fragment, until I discover what was missing:

Add setSupportActionBar(toolbar) in my Activity, like this:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.id.activity_main);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
}

I hope this answer can be helpful for someone with the same problem.

jQuery: If this HREF contains

use this

$("a").each(function () {
    var href=$(this).prop('href');
    if (href.indexOf('?') > -1) {
        alert("Contains questionmark");
    }
});

What are the recommendations for html <base> tag?

Working with AngularJS the BASE tag broke $cookieStore silently and it took me a while to figure out why my app couldn't write cookies anymore. Be warned...

How to show text on image when hovering?

<!DOCTYPE html><html lang='en' class=''>
<head><script src='//production-assets.codepen.io/assets/editor/live/console_runner-079c09a0e3b9ff743e39ee2d5637b9216b3545af0de366d4b9aad9dc87e26bfd.js'></script><script src='//production-assets.codepen.io/assets/editor/live/events_runner-73716630c22bbc8cff4bd0f07b135f00a0bdc5d14629260c3ec49e5606f98fdd.js'></script><script src='//production-assets.codepen.io/assets/editor/live/css_live_reload_init-2c0dc5167d60a5af3ee189d570b1835129687ea2a61bee3513dee3a50c115a77.js'></script><meta charset='UTF-8'><meta name="robots" content="noindex"><link rel="shortcut icon" type="image/x-icon" href="//production-assets.codepen.io/assets/favicon/favicon-8ea04875e70c4b0bb41da869e81236e54394d63638a1ef12fa558a4a835f1164.ico" /><link rel="mask-icon" type="" href="//production-assets.codepen.io/assets/favicon/logo-pin-f2d2b6d2c61838f7e76325261b7195c27224080bc099486ddd6dccb469b8e8e6.svg" color="#111" /><link rel="canonical" href="https://codepen.io/nelsonleite/pen/RaGwba?depth=everything&order=popularity&page=4&q=product&show_forks=false" />
<link href='https://fonts.googleapis.com/css?family=Raleway' rel='stylesheet' type='text/css'>
<link rel='stylesheet prefetch' href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css'>
<style class="cp-pen-styles">.product-description {
  transform: translate3d(0, 0, 0);
  transform-style: preserve-3d;
  perspective: 1000;
  backface-visibility: hidden;
}

body {
  color: #212121;
}

.container {
  padding-top: 25px;
  padding-bottom: 25px;
}

img {
  max-width: 100%;
}

hr {
  border-color: #e5e5e5;
  margin: 15px 0;
}

.secondary-text {
  color: #b6b6b6;
}

.list-inline {
  margin: 0;
}
.list-inline li {
  padding: 0;
}

.card-wrapper {
  position: relative;
  width: 100%;
  height: 390px;
  border: 1px solid #e5e5e5;
  border-bottom-width: 2px;
  overflow: hidden;
  margin-bottom: 30px;
}
.card-wrapper:after {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  opacity: 0;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
  transition: opacity 0.6s cubic-bezier(0.165, 0.84, 0.44, 1);
}
.card-wrapper:hover:after {
  opacity: 1;
}
.card-wrapper:hover .image-holder:before {
  opacity: .75;
}
.card-wrapper:hover .image-holder:after {
  opacity: 1;
  transform: translate(-50%, -50%);
}
.card-wrapper:hover .image-holder--original {
  transform: translateY(-15px);
}
.card-wrapper:hover .product-description {
  height: 205px;
}
@media (min-width: 768px) {
  .card-wrapper:hover .product-description {
    height: 185px;
  }
}

.image-holder {
  display: block;
  position: relative;
  width: 100%;
  height: 310px;
  background-color: #ffffff;
  z-index: 1;
}
@media (min-width: 768px) {
  .image-holder {
    height: 325px;
  }
}
.image-holder:before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: #4CAF50;
  opacity: 0;
  z-index: 5;
  transition: opacity 0.6s;
}
.image-holder:after {
  content: '+';
  font-family: 'Raleway', sans-serif;
  font-size: 70px;
  color: #4CAF50;
  text-align: center;
  position: absolute;
  top: 92.5px;
  left: 50%;
  width: 75px;
  height: 75px;
  line-height: 75px;
  background-color: #ffffff;
  opacity: 0;
  border-radius: 50%;
  z-index: 10;
  transform: translate(-50%, 100%);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
  transition: all 0.4s ease-out;
}
@media (min-width: 768px) {
  .image-holder:after {
    top: 107.5px;
  }
}
.image-holder .image-holder__link {
  display: block;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 15;
}
.image-holder .image-holder--original {
  transition: transform 0.8s cubic-bezier(0.165, 0.84, 0.44, 1);
}

.image-liquid {
  width: 100%;
  height: 325px;
  background-size: cover;
  background-position: center center;
}

.product-description {
  position: absolute;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 80px;
  padding: 10px 15px;
  overflow: hidden;
  background-color: #fafafa;
  border-top: 1px solid #e5e5e5;
  transition: height 0.6s cubic-bezier(0.165, 0.84, 0.44, 1);
  z-index: 2;
}
@media (min-width: 768px) {
  .product-description {
    height: 65px;
  }
}
.product-description p {
  margin: 0 0 5px;
}
.product-description .product-description__title {
  font-family: 'Raleway', sans-serif;
  position: relative;
  white-space: nowrap;
  overflow: hidden;
  margin: 0;
  font-size: 18px;
  line-height: 1.25;
}
.product-description .product-description__title:after {
  content: '';
  width: 60px;
  height: 100%;
  position: absolute;
  top: 0;
  right: 0;
  background: linear-gradient(to right, rgba(255, 255, 255, 0), #fafafa);
}
.product-description .product-description__title a {
  text-decoration: none;
  color: inherit;
}
.product-description .product-description__category {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.product-description .product-description__price {
  color: #4CAF50;
  text-align: left;
  font-weight: bold;
  letter-spacing: 0.06em;
}
@media (min-width: 768px) {
  .product-description .product-description__price {
    text-align: right;
  }
}
.product-description .sizes-wrapper {
  margin-bottom: 15px;
}
.product-description .color-list {
  font-size: 0;
}
.product-description .color-list__item {
  width: 25px;
  height: 10px;
  position: relative;
  z-index: 1;
  transition: all .2s;
}
.product-description .color-list__item:hover {
  width: 40px;
}
.product-description .color-list__item--red {
  background-color: #F44336;
}
.product-description .color-list__item--blue {
  background-color: #448AFF;
}
.product-description .color-list__item--green {
  background-color: #CDDC39;
}
.product-description .color-list__item--orange {
  background-color: #FF9800;
}
.product-description .color-list__item--purple {
  background-color: #673AB7;
}
</style></head><body>
<!--
Inspired in this dribbble
https://dribbble.com/shots/986548-Product-Catalog
-->

<div class="container">
    <div class="row">

        <div class="col-xs-12 col-sm-6 col-md-4">
            <article class="card-wrapper">
                <div class="image-holder">
                    <a href="#" class="image-holder__link"></a>
                    <div class="image-liquid image-holder--original" style="background-image: url('https://upload.wikimedia.org/wikipedia/commons/2/24/Blue_Tshirt.jpg')">
                    </div>
                </div>

                <div class="product-description">
                    <!-- title -->
                    <h1 class="product-description__title">
                        <a href="#">                        
                            Adidas Originals
                            </a>
                    </h1>

                    <!-- category and price -->
                    <div class="row">
                        <div class="col-xs-12 col-sm-8 product-description__category secondary-text">
                            Men's running shirt
                        </div>
                        <div class="col-xs-12 col-sm-4 product-description__price">
                            € 499
                        </div>
                    </div>

                    <!-- divider -->
                    <hr />

                    <!-- sizes -->
                    <div class="sizes-wrapper">
                        <b>Sizes</b>
                        <br />
                        <span class="secondary-text text-uppercase">
                            <ul class="list-inline">
                                <li>xs,</li>                                
                                <li>s,</li>                             
                                <li>sm,</li>                                
                                <li>m,</li>
                                <li>l,</li>                             
                                <li>xl,</li>                                
                                <li>xxl</li>                                
                            </ul>
                        </span>
                    </div>

                    <!-- colors -->
                    <div class="color-wrapper">
                        <b>Colors</b>
                        <br />
                        <ul class="list-inline color-list">
                            <li class="color-list__item color-list__item--red"></li>
                            <li class="color-list__item color-list__item--blue"></li>
                            <li class="color-list__item color-list__item--green"></li>
                            <li class="color-list__item color-list__item--orange"></li>
                            <li class="color-list__item color-list__item--purple"></li>
                        </ul>
                    </div>
                </div>

            </article>
        </div>

        <div class="col-xs-12 col-sm-6 col-md-4">
            <article class="card-wrapper">
                <div class="image-holder">
                    <a href="#" class="image-holder__link"></a>
                    <div class="image-liquid image-holder--original" style="background-image: url('https://upload.wikimedia.org/wikipedia/commons/thumb/7/75/Jeans_BW_2_(3213391837).jpg/543px-Jeans_BW_2_(3213391837).jpg')">
                    </div>
                </div>

                <div class="product-description">
                    <!-- title -->
                    <h1 class="product-description__title">
                        <a href="#">                        
                            Adidas Originals
                            </a>
                    </h1>

                    <!-- category and price -->
                    <div class="row">
                        <div class="col-sm-8 product-description__category secondary-text">
                            Men's running shirt
                        </div>
                        <div class="col-sm-4 product-description__price text-right">
                            € 499
                        </div>
                    </div>

                    <!-- divider -->
                    <hr />

                    <!-- sizes -->
                    <div class="sizes-wrapper">
                        <b>Sizes</b>
                        <br />
                        <span class="secondary-text text-uppercase">
                            <ul class="list-inline">
                                <li>xs,</li>                                
                                <li>s,</li>                             
                                <li>sm,</li>                                
                                <li>m,</li>
                                <li>l,</li>                             
                                <li>xl,</li>                                
                                <li>xxl</li>                                
                            </ul>
                        </span>
                    </div>

                    <!-- colors -->
                    <div class="color-wrapper">
                        <b>Colors</b>
                        <br />
                        <ul class="list-inline color-list">
                            <li class="color-list__item color-list__item--red"></li>
                            <li class="color-list__item color-list__item--blue"></li>
                            <li class="color-list__item color-list__item--green"></li>
                            <li class="color-list__item color-list__item--orange"></li>
                            <li class="color-list__item color-list__item--purple"></li>
                        </ul>
                    </div>
                </div>

            </article>
        </div>

        <div class="col-xs-12 col-sm-6 col-md-4">
            <article class="card-wrapper">
                <div class="image-holder">
                    <a href="#" class="image-holder__link"></a>
                    <div class="image-liquid image-holder--original" style="background-image: url('https://upload.wikimedia.org/wikipedia/commons/b/b8/Columbia_Sportswear_Jacket.jpg')">
                    </div>
                </div>

                <div class="product-description">
                    <!-- title -->
                    <h1 class="product-description__title">
                        <a href="#">                        
                            Adidas Originals
                            </a>
                    </h1>

                    <!-- category and price -->
                    <div class="row">
                        <div class="col-sm-8 product-description__category secondary-text">
                            Men's running shirt
                        </div>
                        <div class="col-sm-4 product-description__price text-right">
                            € 499
                        </div>
                    </div>

                    <!-- divider -->
                    <hr />

                    <!-- sizes -->
                    <div class="sizes-wrapper">
                        <b>Sizes</b>
                        <br />
                        <span class="secondary-text text-uppercase">
                            <ul class="list-inline">
                                <li>xs,</li>                                
                                <li>s,</li>                             
                                <li>sm,</li>                                
                                <li>m,</li>
                                <li>l,</li>                             
                                <li>xl,</li>                                
                                <li>xxl</li>                                
                            </ul>
                        </span>
                    </div>

                    <!-- colors -->
                    <div class="color-wrapper">
                        <b>Colors</b>
                        <br />
                        <ul class="list-inline color-list">
                            <li class="color-list__item color-list__item--red"></li>
                            <li class="color-list__item color-list__item--blue"></li>
                            <li class="color-list__item color-list__item--green"></li>
                            <li class="color-list__item color-list__item--orange"></li>
                            <li class="color-list__item color-list__item--purple"></li>
                        </ul>
                    </div>
                </div>

            </article>
        </div>

        <div class="col-xs-12 col-sm-6 col-md-4">
            <article class="card-wrapper">
                <div class="image-holder">
                    <a href="#" class="image-holder__link"></a>
                    <div class="image-liquid image-holder--original" style="background-image: url('http://www.publicdomainpictures.net/pictures/20000/nahled/red-shoes-isolated.jpg')">
                    </div>
                </div>

                <div class="product-description">
                    <!-- title -->
                    <h1 class="product-description__title">
                        <a href="#">                        
                            Adidas Originals
                            </a>
                    </h1>

                    <!-- category and price -->
                    <div class="row">
                        <div class="col-sm-8 product-description__category secondary-text">
                            Men's running shirt
                        </div>
                        <div class="col-sm-4 product-description__price text-right">
                            € 499
                        </div>
                    </div>

                    <!-- divider -->
                    <hr />

                    <!-- sizes -->
                    <div class="sizes-wrapper">
                        <b>Sizes</b>
                        <br />
                        <span class="secondary-text text-uppercase">
                            <ul class="list-inline">
                                <li>xs,</li>                                
                                <li>s,</li>                             
                                <li>sm,</li>                                
                                <li>m,</li>
                                <li>l,</li>                             
                                <li>xl,</li>                                
                                <li>xxl</li>                                
                            </ul>
                        </span>
                    </div>

                    <!-- colors -->
                    <div class="color-wrapper">
                        <b>Colors</b>
                        <br />
                        <ul class="list-inline color-list">
                            <li class="color-list__item color-list__item--red"></li>
                            <li class="color-list__item color-list__item--blue"></li>
                            <li class="color-list__item color-list__item--green"></li>
                            <li class="color-list__item color-list__item--orange"></li>
                            <li class="color-list__item color-list__item--purple"></li>
                        </ul>
                    </div>
                </div>

            </article>
        </div>

    </div>
</div>

</body></html>

The sample is made

GitHub - error: failed to push some refs to '[email protected]:myrepo.git'

I have faced the same issue and resolved as follows (if you have a project in local folder then follow the steps):

  1. create a new repo in guthub
  2. go to local folder and do "git init"
  3. git remote add origin (with your repo url) // simply copy from your repo
  4. git add -A
  5. git commit -m "your commit"
  6. git push -u origin master

What is a Java String's default initial value?

The answer is - it depends.

Is the variable an instance variable / class variable ? See this for more details.

The list of default values can be found here.

Passing data between different controller action methods

Personally I don't like to use TempData, but I prefer to pass a strongly typed object as explained in Passing Information Between Controllers in ASP.Net-MVC.

You should always find a way to make it explicit and expected.

How to get the full URL of a Drupal page?

drupal_get_destination() has some internal code that points at the correct place to getthe current internal path. To translate that path into an absolute URL, the url() function should do the trick. If the 'absolute' option is passed in it will generate the full URL, not just the internal path. It will also swap in any path aliases for the current path as well.

$path = isset($_GET['q']) ? $_GET['q'] : '<front>';
$link = url($path, array('absolute' => TRUE));

SQL SERVER, SELECT statement with auto generate row id

Select (Select count(y.au_lname) from dbo.authors y
where y.au_lname + y.au_fname <= x.au_lname + y.au_fname) as Counterid,
x.au_lname,x.au_fname from authors x group by au_lname,au_fname
order by Counterid --Alternatively that can be done which is equivalent as above..

Convert string to binary then back again using PHP

Why you are using PHP for the conversion. Now, there are so many front end languages available, Why you are still including a server? You can convert the password into the binary number in the front-end and send the converted string in the Database. According to my point of view, this would be convenient.

var bintext, textresult="", binlength;
    this.aaa = this.text_value;
    bintext = this.aaa.replace(/[^01]/g, "");
        binlength = bintext.length-(bintext.length%8);
        for(var z=0; z<binlength; z=z+8) {
            textresult += String.fromCharCode(parseInt(bintext.substr(z,8),2));
                            this.ans = textresult;

This is a Javascript code which I have found here: http://binarytotext.net/, they have used this code with Vue.js. In the code, this.aaa is the v-model dynamic value. To convert the binary into the text values, they have used big numbers. You need to install an additional package and convert it back into the text field. In my point of view, it would be easy.

Nginx fails to load css files

style.css is actually being process via fastcgi due to your "location /" directive. So it is fastcgi that is serving up the file (nginx > fastcgi > filesystem), and not the filesystem directly (nginx > filesystem).

For a reason I have yet to figure out (I'm sure there's a directive somewhere), NGINX applies the mime type text/html to anything being served from fastcgi, unless the backend application explicitly says otherwise.

The culprit is this configuration block specifically:

location / {
     root    /usr/share/nginx/html;
     index  index.html index.htm index.php;
     fastcgi_pass   127.0.0.1:9000;
     fastcgi_index  index.php;
     fastcgi_param  SCRIPT_FILENAME  /usr/share/nginx/html$fastcgi_script_name;
     include        fastcgi_params;
}

It should be:

location ~ \.php$ { # this line
     root    /usr/share/nginx/html;
     index  index.html index.htm index.php;
     fastcgi_split_path_info ^(.+\.php)(/.+)$; #this line
     fastcgi_pass   127.0.0.1:9000;
     fastcgi_index  index.php;
     fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name; # update this too
     include        fastcgi_params;
}

This change makes sure only *.php files are requested from fastcgi. At this point, NGINX will apply the correct MIME type. If you have any URL rewriting happening, you must handle this before the location directive (location ~\.php$) so that the correct extension is derived and properly routed to fastcgi.

Be sure to check out this article regarding additional security considerations using try_files. Given the security implications, I consider this a feature and not a bug.

Showing the same file in both columns of a Sublime Text window

Inside sublime editor,Find the Tab named View,

View --> Layout --> "select your need"

Buiding Hadoop with Eclipse / Maven - Missing artifact jdk.tools:jdk.tools:jar:1.6

If you can live without tools.jar and it's only included as a chained dependency, you can exclude it from the offending project:

<dependency>
    <groupId>org.apache.ambari</groupId>
    <artifactId>ambari-metrics-common</artifactId>
    <version>2.1.0.0</version>
    <exclusions>
        <exclusion>
            <artifactId>jdk.tools</artifactId>
            <groupId>jdk.tools</groupId>
        </exclusion>
    </exclusions>
</dependency>

Unable to import a module that is definitely installed

When you install via easy_install or pip, is it completing successfully? What is the full output? Which python installation are you using? You may need to use sudo before your installation command, if you are installing modules to a system directory (if you are using the system python installation, perhaps). There's not a lot of useful information in your question to go off of, but some tools that will probably help include:

  • echo $PYTHONPATH and/or echo $PATH: when importing modules, Python searches one of these environment variables (lists of directories, : delimited) for the module you want. Importing problems are often due to the right directory being absent from these lists

  • which python, which pip, or which easy_install: these will tell you the location of each executable. It may help to know.

  • Use virtualenv, like @JesseBriggs suggests. It works very well with pip to help you isolate and manage the modules and environment for separate Python projects.

When to use reinterpret_cast?

The C++ standard guarantees the following:

static_casting a pointer to and from void* preserves the address. That is, in the following, a, b and c all point to the same address:

int* a = new int();
void* b = static_cast<void*>(a);
int* c = static_cast<int*>(b);

reinterpret_cast only guarantees that if you cast a pointer to a different type, and then reinterpret_cast it back to the original type, you get the original value. So in the following:

int* a = new int();
void* b = reinterpret_cast<void*>(a);
int* c = reinterpret_cast<int*>(b);

a and c contain the same value, but the value of b is unspecified. (in practice it will typically contain the same address as a and c, but that's not specified in the standard, and it may not be true on machines with more complex memory systems.)

For casting to and from void*, static_cast should be preferred.

Difference between <input type='submit' /> and <button type='submit'>text</button>

In summary :

<input type="submit">

<button type="submit"> Submit </button>

Both by default will visually draw a button that performs the same action (submit the form).

However, it is recommended to use <button type="submit"> because it has better semantics, better ARIA support and it is easier to style.

Insert Update trigger how to determine if insert or update

DECLARE @ActionType CHAR(6);
SELECT  @ActionType = COALESCE(CASE WHEN EXISTS(SELECT * FROM INSERTED)
                                     AND EXISTS(SELECT * FROM DELETED)  THEN 'UPDATE' END,
                               CASE WHEN EXISTS(SELECT * FROM DELETED)  THEN 'DELETE' END,
                               CASE WHEN EXISTS(SELECT * FROM INSERTED) THEN 'INSERT' END);
PRINT   @ActionType;

How to iterate a table rows with JQuery and access some cell values?

try this

var value = iterate('tr.item span.value');
var quantity = iterate('tr.item span.quantity');

function iterate(selector)
{
  var result = '';
  if ($(selector))
  {
    $(selector).each(function ()
    {
      if (result == '')
      {
        result = $(this).html();
      }
      else
      {
        result = result + "," + $(this).html();
      }
    });
  }
}

How can I create an editable dropdownlist in HTML?

You can accomplish this by using the <datalist> tag in HTML5.

_x000D_
_x000D_
<input type="text" name="product" list="productName"/>
    <datalist id="productName">
        <option value="Pen">Pen</option>
        <option value="Pencil">Pencil</option>
        <option value="Paper">Paper</option>
    </datalist>
_x000D_
_x000D_
_x000D_

If you double click on the input text in the browser a list with the defined option will appear.

What is the optimal algorithm for the game 2048?

I wrote a 2048 solver in Haskell, mainly because I'm learning this language right now.

My implementation of the game slightly differs from the actual game, in that a new tile is always a '2' (rather than 90% 2 and 10% 4). And that the new tile is not random, but always the first available one from the top left. This variant is also known as Det 2048.

As a consequence, this solver is deterministic.

I used an exhaustive algorithm that favours empty tiles. It performs pretty quickly for depth 1-4, but on depth 5 it gets rather slow at a around 1 second per move.

Below is the code implementing the solving algorithm. The grid is represented as a 16-length array of Integers. And scoring is done simply by counting the number of empty squares.

bestMove :: Int -> [Int] -> Int
bestMove depth grid = maxTuple [ (gridValue depth (takeTurn x grid), x) | x <- [0..3], takeTurn x grid /= [] ]

gridValue :: Int -> [Int] -> Int
gridValue _ [] = -1
gridValue 0 grid = length $ filter (==0) grid  -- <= SCORING
gridValue depth grid = maxInList [ gridValue (depth-1) (takeTurn x grid) | x <- [0..3] ]

I thinks it's quite successful for its simplicity. The result it reaches when starting with an empty grid and solving at depth 5 is:

Move 4006
[2,64,16,4]
[16,4096,128,512]
[2048,64,1024,16]
[2,4,16,2]

Game Over

Source code can be found here: https://github.com/popovitsj/2048-haskell

update one table with data from another

Use the following block of query to update Table1 with Table2 based on ID:

UPDATE Table1, Table2 
SET Table1.DataColumn= Table2.DataColumn
where Table1.ID= Table2.ID;

This is the easiest and fastest way to tackle this problem.

Produce a random number in a range using C#

You can try

Random r = new Random();
int rInt = r.Next(0, 100); //for ints
int range = 100;
double rDouble = r.NextDouble()* range; //for doubles

Have a look at

Random Class, Random.Next Method (Int32, Int32) and Random.NextDouble Method

.c vs .cc vs. .cpp vs .hpp vs .h vs .cxx

I use ".hpp" for C++ headers and ".h" for C language headers. The ".hpp" reminds me that the file contains statements for the C++ language which are not valid for the C language, such as "class" declarations.

laravel select where and where condition

The error is coming from $userRecord->email. You need to use the ->get() or ->first() methods when calling from the database otherwise you're only getting the Eloquent\Builder object rather than an Eloquent\Collection

The ->first() method is pretty self-explanatory, it will return the first row found. ->get() returns all the rows found

$userRecord = Model::where('email', '=', $email)->where('password', '=', $password)->get();
echo "First name: " . $userRecord->email;

How to use jQuery in chrome extension?

Apart from the solutions already mentioned, you can also download jquery.min.js locally and then use it -

For downloading -

wget "https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"

manifest.json -

"content_scripts": [
   {
    "js": ["/path/to/jquery.min.js", ...]
   }
],

in html -

<script src="/path/to/jquery.min.js"></script>

Reference - https://developer.chrome.com/extensions/contentSecurityPolicy

Register comdlg32.dll gets Regsvr32: DllRegisterServer entry point was not found

Have you unistalled your Internet Explorer? I did, and I had the same issues, if so, you have to:

  1. Reactivate IE (Control Panel -- Programs and Features -- Turn Windows features on or off).
  2. restarting the computer
  3. (important!) running Windows Update to get all available updates for Microsoft Explorer
  4. restarting the computer (again)

Finally it works!

How do I initialize Kotlin's MutableList to empty MutableList?

You can simply write:

val mutableList = mutableListOf<Kolory>()

This is the most idiomatic way.

Alternative ways are

val mutableList : MutableList<Kolory> = arrayListOf()

or

val mutableList : MutableList<Kolory> = ArrayList()

This is exploiting the fact that java types like ArrayList are implicitly implementing the type MutableList via a compiler trick.

Add back button to action bar

this one worked for me:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_your_activity);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    // ... other stuff
}

@Override
public boolean onSupportNavigateUp(){
    finish();
    return true;
}

The method onSupportNavigateUp() is called when you use the back button in the SupportActionBar.

Compilation error: stray ‘\302’ in program etc

You have invalid chars in your source. If you don't have any valid non ascii chars in your source, maybe in a double quoted string literal, you can simply convert your file back to ascii with:

tr -cd '\11\12\15\40-\176' < old.c > new.c

Edit: method with iconv will stop at wrong chars which makes no sense. The above command line is working with the example file. Good luck :-)

What is the definition of "interface" in object oriented programming

Conventional Definition - An interface is a contract that specifies the methods which needs to be implemented by the class implementing it.

The Definition of Interface has changed over time. Do you think Interface just have method declarations only ? What about static final variables and what about default definitions after Java 5.

Interfaces were introduced to Java because of the Diamond problem with multiple Inheritance and that's what they actually intend to do.

Interfaces are the constructs that were created to get away with the multiple inheritance problem and can have abstract methods , default definitions and static final variables.

http://www.quora.com/Why-does-Java-allow-static-final-variables-in-interfaces-when-they-are-only-intended-to-be-contracts

Add a CSS border on hover without moving the element

add margin:-1px; which reduces 1px to each side. or if you need only for side you can do margin-left:-1px etc.

Flutter.io Android License Status Unknown

Here are the steps that solve my problem:

  1. Open your terminal
  2. type flutter doctor --android-licenses
  3. press y to accept, this process may occurred several times. Done!

macro - open all files in a folder

You can use Len(StrFile) > 0 in loop check statement !

Sub openMyfile()

    Dim Source As String
    Dim StrFile As String

    'do not forget last backslash in source directory.
    Source = "E:\Planning\03\"
    StrFile = Dir(Source)

    Do While Len(StrFile) > 0                        
        Workbooks.Open Filename:=Source & StrFile
        StrFile = Dir()
    Loop
End Sub

"for" vs "each" in Ruby

This is the only difference:

each:

irb> [1,2,3].each { |x| }
  => [1, 2, 3]
irb> x
NameError: undefined local variable or method `x' for main:Object
    from (irb):2
    from :0

for:

irb> for x in [1,2,3]; end
  => [1, 2, 3]
irb> x
  => 3

With the for loop, the iterator variable still lives after the block is done. With the each loop, it doesn't, unless it was already defined as a local variable before the loop started.

Other than that, for is just syntax sugar for the each method.

When @collection is nil both loops throw an exception:

Exception: undefined local variable or method `@collection' for main:Object

How to use the 'og' (Open Graph) meta tag for Facebook share

Use:

<!-- For Google -->
<meta name="description" content="" />
<meta name="keywords" content="" />

<meta name="author" content="" />
<meta name="copyright" content="" />
<meta name="application-name" content="" />

<!-- For Facebook -->
<meta property="og:title" content="" />
<meta property="og:type" content="article" />
<meta property="og:image" content="" />
<meta property="og:url" content="" />
<meta property="og:description" content="" />

<!-- For Twitter -->
<meta name="twitter:card" content="summary" />
<meta name="twitter:title" content="" />
<meta name="twitter:description" content="" />
<meta name="twitter:image" content="" />

Fill the content =" ... " according to the content of your page.

For more information, visit 18 Meta Tags Every Webpage Should Have in 2013.

Is it possible to force Excel recognize UTF-8 CSV files automatically?

I tried everything I could find on this thread and similar, nothing worked fully. However, importing to google sheets and simply downloading as csv worked like a charm. Try it out if you come to my frustration point.

Check whether a value is a number in JavaScript or jQuery

there is a function called isNaN it return true if it's (Not-a-number) , so u can check for a number this way

if(!isNaN(miscCharge))
{
   //do some thing if it's a number
}else{
   //do some thing if it's NOT a number
}

hope it works

Rails :include vs. :joins

In addition to a performance considerations, there's a functional difference too. When you join comments, you are asking for posts that have comments- an inner join by default. When you include comments, you are asking for all posts- an outer join.

How to make rpm auto install dependencies

The link @gertvdijk provided shows a quick way to achieve the desired results without configuring a local repository:

$ yum --nogpgcheck localinstall packagename.arch.rpm

Just change packagename.arch.rpm to the RPM filename you want to install.

Edit Just a clarification, this will automatically install all dependencies that are already available via system YUM repositories.

If you have dependencies satisfied by other RPMs that are not in the system's repositories, then this method will not work unless each RPM is also specified along with packagename.arch.rpm on the command line.

How to change background and text colors in Sublime Text 3

For How do I change the overall colors (background and font)?

For MAC : goto Sublime text -> Preferences -> color scheme

How do I set vertical space between list items?

Old question but I think it lacked an answer. I would use an adjacent siblings selector. This way we only write "one" line of CSS and take into consideration the space at the end or beginning, which most of the answers lacks.

li + li {
  margin-top: 10px;
}

Internet Explorer 11 detection

I use the following function to detect version 9, 10 and 11 of IE:

function ieVersion() {
    var ua = window.navigator.userAgent;
    if (ua.indexOf("Trident/7.0") > -1)
        return 11;
    else if (ua.indexOf("Trident/6.0") > -1)
        return 10;
    else if (ua.indexOf("Trident/5.0") > -1)
        return 9;
    else
        return 0;  // not IE9, 10 or 11
}  

Can we locate a user via user's phone number in Android?

The answer is: you can't only through sms, i have tried that approach before.

You could fetch the base station IDs, but this won't help you a lot without the location of the base station itself and this informations are really hard to retrieve from the providers.

I have looked through the 3 apps you have listed in your question:

  1. The App uses WiFi and GPRS location service, quite the same approach as Google uses on the phone. phonesavvy maybe has a base station location database or uses a database retrieved e.g. from OpenStreetMap or some similar crowd-based project.
  2. The app analyzes just the number for country code and city code. No location there.
  3. Dito.

Python script to convert from UTF-8 to ASCII

import codecs

 ...

fichier = codecs.open(filePath, "r", encoding="utf-8")

 ...

fichierTemp = codecs.open("tempASCII", "w", encoding="ascii", errors="ignore")
fichierTemp.write(contentOfFile)

 ...

What is a monad?

(See also the answers at What is a monad?)

A good motivation to Monads is sigfpe (Dan Piponi)'s You Could Have Invented Monads! (And Maybe You Already Have). There are a LOT of other monad tutorials, many of which misguidedly try to explain monads in "simple terms" using various analogies: this is the monad tutorial fallacy; avoid them.

As DR MacIver says in Tell us why your language sucks:

So, things I hate about Haskell:

Let’s start with the obvious. Monad tutorials. No, not monads. Specifically the tutorials. They’re endless, overblown and dear god are they tedious. Further, I’ve never seen any convincing evidence that they actually help. Read the class definition, write some code, get over the scary name.

You say you understand the Maybe monad? Good, you're on your way. Just start using other monads and sooner or later you'll understand what monads are in general.

[If you are mathematically oriented, you might want to ignore the dozens of tutorials and learn the definition, or follow lectures in category theory :) The main part of the definition is that a Monad M involves a "type constructor" that defines for each existing type "T" a new type "M T", and some ways for going back and forth between "regular" types and "M" types.]

Also, surprisingly enough, one of the best introductions to monads is actually one of the early academic papers introducing monads, Philip Wadler's Monads for functional programming. It actually has practical, non-trivial motivating examples, unlike many of the artificial tutorials out there.

Restore LogCat window within Android Studio

When you are opening the project in the android studio instead of opening android directory open app directory

enter image description here

How to download source in ZIP format from GitHub?

Even though this is fairly an old question, I have my 2 cents to share.

You can download the repo as tar.gz as well

Like the zipball link pointed by various answers here, There is a tarball link as well which downloads the content of the git repository in tar.gz format.

curl -L http://github.com/zoul/Finch/tarball/master/

A better way

Git also provides a different URL pattern where you can simply append the type of file you want to download at the end of url. This way is better if you want to process these urls in a batch or bash script.

curl -L http://github.com/zoul/Finch/archive/master.zip

curl -L http://github.com/zoul/Finch/archive/master.tar.gz

To download a specific commit or branch

Replace master with the commit-hash or the branch-name in the above urls like below.

curl -L http://github.com/zoul/Finch/archive/cfeb671ac55f6b1aba6ed28b9bc9b246e0e.zip    
curl -L http://github.com/zoul/Finch/archive/cfeb671ac55f6b1aba6ed28b9bc9b246e0e.tar.gz

curl -L http://github.com/zoul/Finch/archive/your-branch-name.zip
curl -L http://github.com/zoul/Finch/archive/your-branch-name.tar.gz

phpexcel to download

posible you already solved your problem, any way i hope this help you.

all files downloaded starts with empty line, in my case where four empty lines, and it make a problem. No matter if you work with readfile(); or save('php://output');, This can be fixed with adding ob_start(); at the beginning of the script and ob_end_clean(); just before the readfile(); or save('php://output');.

Sass Nesting for :hover does not work

For concatenating selectors together when nesting, you need to use the parent selector (&):

.class {
    margin:20px;
    &:hover {
        color:yellow;
    }
}

exclude @Component from @ComponentScan

The configuration seem alright, except that you should use excludeFilters instead of excludes:

@Configuration @EnableSpringConfigured
@ComponentScan(basePackages = {"com.example"}, excludeFilters={
  @ComponentScan.Filter(type=FilterType.ASSIGNABLE_TYPE, value=Foo.class)})
public class MySpringConfiguration {}

HTML: how to force links to open in a new tab, not new window

I didn't try this but I think it works in all browsers:

target="_parent"

Apply function to each element of a list

Or, alternatively, you can take a list comprehension approach:

>>> mylis = ['this is test', 'another test']
>>> [item.upper() for item in mylis]
['THIS IS TEST', 'ANOTHER TEST']

How to access the contents of a vector from a pointer to the vector in C++?

vector <int> numbers {10,20,30,40};
vector <int> *ptr {nullptr};

ptr = &numbers;

for(auto num: *ptr){
 cout << num << endl;
}


cout << (*ptr).at(2) << endl; // 20

cout << "-------" << endl;

cout << ptr -> at(2) << endl; // 20

What is newline character -- '\n'

I think this post by Jeff Attwood addresses your question perfectly. It takes you through the differences between newlines on Dos, Mac and Unix, and then explains the history of CR (Carriage return) and LF (Line feed).

laravel Unable to prepare route ... for serialization. Uses Closure

the solustion when we use routes like this:

Route::get('/', function () {
    return view('welcome');
});

laravel call them Closure so you cant optimize routes uses as Closures you must route to controller to use php artisan optimize

file_get_contents() Breaks Up UTF-8 Characters

Alright. I have found out the file_get_contents() is not causing this problem. There's a different reason which I talk about in another question. Silly me.

See this question: Why Does DOM Change Encoding?

How to do relative imports in Python?

main.py
setup.py
app/ ->
    __init__.py
    package_a/ ->
       __init__.py
       module_a.py
    package_b/ ->
       __init__.py
       module_b.py
  1. You run python main.py.
  2. main.py does: import app.package_a.module_a
  3. module_a.py does import app.package_b.module_b

Alternatively 2 or 3 could use: from app.package_a import module_a

That will work as long as you have app in your PYTHONPATH. main.py could be anywhere then.

So you write a setup.py to copy (install) the whole app package and subpackages to the target system's python folders, and main.py to target system's script folders.

Sort array of objects by object fields

A simple alternative that allows you to determine dynamically the field on which the sorting is based:

$order_by = 'name';
usort($your_data, function ($a, $b) use ($order_by)
{
    return strcmp($a->{$order_by}, $b->{$order_by});
});

This is based on the Closure class, which allows anonymous functions. It is available since PHP 5.3.

SQLite Query in Android to count rows

DatabaseUtils.queryNumEntries (since api:11) is useful alternative that negates the need for raw SQL(yay!).

SQLiteDatabase db = getReadableDatabase();
DatabaseUtils.queryNumEntries(db, "users",
                "uname=? AND pwd=?", new String[] {loginname,loginpass});

How do I turn off the mysql password validation?

On some installations, you cannot execute this command until you have reset the root password. You cannot reset the root password, until you execute this command. Classic Catch-22.

One solution not mention by other responders is to temporarily disable the plugin via mysql configuration. In any my.cnf, in the [mysqld] section, add:

skip-validate_password=1

and restart the server. Change the password, and set the value back to 0, and restart again.

How to get text from each cell of an HTML table?

its

selenium.getTable("tablename".rowNumber.colNumber)

not

selenium.getTable("tablename".colNumber.rowNumber)

How to Execute SQL Script File in Java?

Flyway library is really good for this:

    Flyway flyway = new Flyway();
    flyway.setDataSource(dbConfig.getUrl(), dbConfig.getUsername(), dbConfig.getPassword());
    flyway.setLocations("classpath:db/scripts");
    flyway.clean();
    flyway.migrate();

This scans the locations for scripts and runs them in order. Scripts can be versioned with V01__name.sql so if just the migrate is called then only those not already run will be run. Uses a table called 'schema_version' to keep track of things. But can do other things too, see the docs: flyway.

The clean call isn't required, but useful to start from a clean DB. Also, be aware of the location (default is "classpath:db/migration"), there is no space after the ':', that one caught me out.

laravel 5 : Class 'input' not found

Miscall of Class it should be Input not input

Click event doesn't work on dynamically generated elements

Also you can use onclick="do_something(this)"inside element

How to create a secure random AES key in Java?

Using KeyGenerator would be the preferred method. As Duncan indicated, I would certainly give the key size during initialization. KeyFactory is a method that should be used for pre-existing keys.

OK, so lets get to the nitty-gritty of this. In principle AES keys can have any value. There are no "weak keys" as in (3)DES. Nor are there any bits that have a specific meaning as in (3)DES parity bits. So generating a key can be as simple as generating a byte array with random values, and creating a SecretKeySpec around it.

But there are still advantages to the method you are using: the KeyGenerator is specifically created to generate keys. This means that the code may be optimized for this generation. This could have efficiency and security benefits. It might be programmed to avoid a timing side channel attacks that would expose the key, for instance. Note that it may already be a good idea to clear any byte[] that hold key information as they may be leaked into a swap file (this may be the case anyway though).

Furthermore, as said, not all algorithms are using fully random keys. So using KeyGenerator would make it easier to switch to other algorithms. More modern ciphers will only accept fully random keys though; this is seen as a major benefit over e.g. DES.

Finally, and in my case the most important reason, it that the KeyGenerator method is the only valid way of handling AES keys within a secure token (smart card, TPM, USB token or HSM). If you create the byte[] with the SecretKeySpec then the key must come from memory. That means that the key may be put in the secure token, but that the key is exposed in memory regardless. Normally, secure tokens only work with keys that are either generated in the secure token or are injected by e.g. a smart card or a key ceremony. A KeyGenerator can be supplied with a provider so that the key is directly generated within the secure token.

As indicated in Duncan's answer: always specify the key size (and any other parameters) explicitly. Do not rely on provider defaults as this will make it unclear what your application is doing, and each provider may have its own defaults.

How to access remote server with local phpMyAdmin client?

You can set in the config.inc.php file of your phpMyAdmin installation.

$cfg['Servers'][$i]['host'] = '';

Drop all duplicate rows across multiple columns in Python Pandas

This is much easier in pandas now with drop_duplicates and the keep parameter.

import pandas as pd
df = pd.DataFrame({"A":["foo", "foo", "foo", "bar"], "B":[0,1,1,1], "C":["A","A","B","A"]})
df.drop_duplicates(subset=['A', 'C'], keep=False)

How do you parse and process HTML/XML in PHP?

There are many ways to process HTML/XML DOM of which most have already been mentioned. Hence, I won't make any attempt to list those myself.

I merely want to add that I personally prefer using the DOM extension and why :

  • iit makes optimal use of the performance advantage of the underlying C code
  • it's OO PHP (and allows me to subclass it)
  • it's rather low level (which allows me to use it as a non-bloated foundation for more advanced behavior)
  • it provides access to every part of the DOM (unlike eg. SimpleXml, which ignores some of the lesser known XML features)
  • it has a syntax used for DOM crawling that's similar to the syntax used in native Javascript.

And while I miss the ability to use CSS selectors for DOMDocument, there is a rather simple and convenient way to add this feature: subclassing the DOMDocument and adding JS-like querySelectorAll and querySelector methods to your subclass.

For parsing the selectors, I recommend using the very minimalistic CssSelector component from the Symfony framework. This component just translates CSS selectors to XPath selectors, which can then be fed into a DOMXpath to retrieve the corresponding Nodelist.

You can then use this (still very low level) subclass as a foundation for more high level classes, intended to eg. parse very specific types of XML or add more jQuery-like behavior.

The code below comes straight out my DOM-Query library and uses the technique I described.

For HTML parsing :

namespace PowerTools;

use \Symfony\Component\CssSelector\CssSelector as CssSelector;

class DOM_Document extends \DOMDocument {
    public function __construct($data = false, $doctype = 'html', $encoding = 'UTF-8', $version = '1.0') {
        parent::__construct($version, $encoding);
        if ($doctype && $doctype === 'html') {
            @$this->loadHTML($data);
        } else {
            @$this->loadXML($data);
        }
    }

    public function querySelectorAll($selector, $contextnode = null) {
        if (isset($this->doctype->name) && $this->doctype->name == 'html') {
            CssSelector::enableHtmlExtension();
        } else {
            CssSelector::disableHtmlExtension();
        }
        $xpath = new \DOMXpath($this);
        return $xpath->query(CssSelector::toXPath($selector, 'descendant::'), $contextnode);
    }

    [...]

    public function loadHTMLFile($filename, $options = 0) {
        $this->loadHTML(file_get_contents($filename), $options);
    }

    public function loadHTML($source, $options = 0) {
        if ($source && $source != '') {
            $data = trim($source);
            $html5 = new HTML5(array('targetDocument' => $this, 'disableHtmlNsInDom' => true));
            $data_start = mb_substr($data, 0, 10);
            if (strpos($data_start, '<!DOCTYPE ') === 0 || strpos($data_start, '<html>') === 0) {
                $html5->loadHTML($data);
            } else {
                @$this->loadHTML('<!DOCTYPE html><html><head><meta charset="' . $encoding . '" /></head><body></body></html>');
                $t = $html5->loadHTMLFragment($data);
                $docbody = $this->getElementsByTagName('body')->item(0);
                while ($t->hasChildNodes()) {
                    $docbody->appendChild($t->firstChild);
                }
            }
        }
    }

    [...]
}

See also Parsing XML documents with CSS selectors by Symfony's creator Fabien Potencier on his decision to create the CssSelector component for Symfony and how to use it.

Get last 5 characters in a string

Dim a As String = Microsoft.VisualBasic.right("I will be going to school in 2011!", 5)
MsgBox("the value is:" & a)

Difference between PACKETS and FRAMES

Consider TCP over ATM. ATM uses 48 byte frames, but clearly TCP packets can be bigger than that. A frame is the chunk of data sent as a unit over the data link (Ethernet, ATM). A packet is the chunk of data sent as a unit over the layer above it (IP). If the data link is made specifically for IP, as Ethernet and WiFi are, these will be the same size and packets will correspond to frames.

How do I add an element to a list in Groovy?

From the documentation:

We can add to a list in many ways:

assert [1,2] + 3 + [4,5] + 6 == [1, 2, 3, 4, 5, 6]
assert [1,2].plus(3).plus([4,5]).plus(6) == [1, 2, 3, 4, 5, 6]
    //equivalent method for +
def a= [1,2,3]; a += 4; a += [5,6]; assert a == [1,2,3,4,5,6]
assert [1, *[222, 333], 456] == [1, 222, 333, 456]
assert [ *[1,2,3] ] == [1,2,3]
assert [ 1, [2,3,[4,5],6], 7, [8,9] ].flatten() == [1, 2, 3, 4, 5, 6, 7, 8, 9]

def list= [1,2]
list.add(3) //alternative method name
list.addAll([5,4]) //alternative method name
assert list == [1,2,3,5,4]

list= [1,2]
list.add(1,3) //add 3 just before index 1
assert list == [1,3,2]
list.addAll(2,[5,4]) //add [5,4] just before index 2
assert list == [1,3,5,4,2]

list = ['a', 'b', 'z', 'e', 'u', 'v', 'g']
list[8] = 'x'
assert list == ['a', 'b', 'z', 'e', 'u', 'v', 'g', null, 'x']

You can also do:

def myNewList = myList << "fifth"

displaying a string on the textview when clicking a button in android

MainActivity.java:

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.view.View;
import android.view.View.OnClickListener;

public class MainActivity extends Activity {

    Button button1;
    TextView textView1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

         button1=(Button)findViewById(R.id.button1);
         textView1=(TextView)findViewById(R.id.textView1);
        button1.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

            textView1.setText("TextView displayed Successfully");

            }
        });

}

}  

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Click here" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
         />

</LinearLayout>

What USB driver should we use for the Nexus 5?

Everything else here failed for me initially (it kept coming up as an MTP device no matter how many times I uninstalled and restarted).

However, by going and enabling USB debugging, it worked. Just do this:

  1. Uninstall the Nexus 5 driver
  2. Disconnect from the computer
  3. Enable developer options, see How to Enable Developer Options on the Nexus 5 & KitKat.
  4. Enable USB debugging: Go to Settings -> Developer Options -> USB Debugging
  5. Reconnect
  6. It will probably fail to install all drivers. Go update the drivers as described in other answers.

How do you convert a jQuery object into a string?

jQuery is up in here, so:

jQuery.fn.goodOLauterHTML= function() {
    return $('<a></a>').append( this.clone() ).html();
}

Return all that HTML stuff:

$('div' /*elys with HTML text stuff that you want */ ).goodOLauterHTML(); // alerts tags and all

Invalid argument supplied for foreach()

i would do the same thing as Andy but i'ld use the 'empty' function.

like so:

if(empty($yourArray))
{echo"<p>There's nothing in the array.....</p>";}
else
{
foreach ($yourArray as $current_array_item)
  {
    //do something with the current array item here
  } 
}

substring index range

public String substring(int beginIndex, int endIndex)

beginIndex—the begin index, inclusive.

endIndex—the end index, exclusive.

Example:

public class Test {

    public static void main(String args[]) {
        String Str = new String("Hello World");

        System.out.println(Str.substring(3, 8));
    }
 }

Output: "lo Wo"

From 3 to 7 index.

Also there is another kind of substring() method:

public String substring(int beginIndex)

beginIndex—the begin index, inclusive. Returns a sub string starting from beginIndex to the end of the main String.

Example:

public class Test {

    public static void main(String args[]) {
        String Str = new String("Hello World");

        System.out.println(Str.substring(3));
    }
}

Output: "lo World"

From 3 to the last index.

SASS and @font-face

For those looking for an SCSS mixin instead, including woff2:

@mixin fface($path, $family, $type: '', $weight: 400, $svg: '', $style: normal) {
  @font-face {
    font-family: $family;
    @if $svg == '' {
      // with OTF without SVG and EOT
      src: url('#{$path}#{$type}.otf') format('opentype'), url('#{$path}#{$type}.woff2') format('woff2'), url('#{$path}#{$type}.woff') format('woff'), url('#{$path}#{$type}.ttf') format('truetype');
    } @else {
      // traditional src inclusions
      src: url('#{$path}#{$type}.eot');
      src: url('#{$path}#{$type}.eot?#iefix') format('embedded-opentype'), url('#{$path}#{$type}.woff2') format('woff2'), url('#{$path}#{$type}.woff') format('woff'), url('#{$path}#{$type}.ttf') format('truetype'), url('#{$path}#{$type}.svg##{$svg}') format('svg');
    }
    font-weight: $weight;
    font-style: $style;
  }
}
// ========================================================importing
$dir: '/assets/fonts/';
$famatic: 'AmaticSC';
@include fface('#{$dir}amatic-sc-v11-latin-regular', $famatic, '', 400, $famatic);

$finter: 'Inter';
// adding specific types of font-weights
@include fface('#{$dir}#{$finter}', $finter, '-Thin-BETA', 100);
@include fface('#{$dir}#{$finter}', $finter, '-Regular', 400);
@include fface('#{$dir}#{$finter}', $finter, '-Medium', 500);
@include fface('#{$dir}#{$finter}', $finter, '-Bold', 700);
// ========================================================usage
.title {
  font-family: Inter;
  font-weight: 700; // Inter-Bold font is loaded
}
.special-title {
  font-family: AmaticSC;
  font-weight: 700; // default font is loaded
}

The $type parameter is useful for stacking related families with different weights.

The @if is due to the need of supporting the Inter font (similar to Roboto), which has OTF but doesn't have SVG and EOT types at this time.

If you get a can't resolve error, remember to double check your fonts directory ($dir).

send mail to multiple receiver with HTML mailto

"There are no safe means of assigning multiple recipients to a single mailto: link via HTML. There are safe, non-HTML, ways of assigning multiple recipients from a mailto: link."

http://www.sightspecific.com/~mosh/www_faq/multrec.html

For a quick fix to your problem, change your ; to a comma , and eliminate the spaces between email addresses

<a href='mailto:[email protected],[email protected]'>Email Us</a>

SQLSTATE[28000] [1045] Access denied for user 'root'@'localhost' (using password: YES) Symfony2

I dont know what is the exact reason but I solved the problem running:

   app/console cache:clear --env=prod

How do you import an Eclipse project into Android Studio now?

Export from Eclipse

  1. Update your Eclipse ADT Plugin to 22.0 or higher, then go to File | Export

  2. Go to Android now then click on Generate Gradle build files, then it would generate gradle file for you.

    enter image description here

  3. Select your project you want to export

    enter image description here

  4. Click on finish now

    enter image description here

Import into Android Studio

  1. In Android Studio, close any projects currently open. You should see the Welcome to Android Studio window.

  2. Click Import Project.

  3. Locate the project you exported from Eclipse, expand it, select it and click OK.

Javascript reduce() on Object

What you actually want in this case are the Object.values. Here is a concise ES6 implementation with that in mind:

const add = {
  a: {value:1},
  b: {value:2},
  c: {value:3}
}

const total = Object.values(add).reduce((t, {value}) => t + value, 0)

console.log(total) // 6

or simply:

const add = {
  a: 1,
  b: 2,
  c: 3
}

const total = Object.values(add).reduce((t, n) => t + n)

console.log(total) // 6

How to set standard encoding in Visual Studio

What

It is possible with EditorConfig.

EditorConfig helps developers define and maintain consistent coding styles between different editors and IDEs.

This also includes file encoding.

EditorConfig is built-in Visual Studio 2017 by default, and I there were plugins available for versions as old as VS2012. Read more from EditorConfig Visual Studio Plugin page.

How

You can set up a EditorConfig configuration file high enough in your folder structure to span all your intended repos (up to your drive root should your files be really scattered everywhere) and configure the setting charset:

charset: set to latin1, utf-8, utf-8-bom, utf-16be or utf-16le to control the character set.

You can add filters and exceptions etc on every folder level or by file name/type should you wish for finer control.

Once configured then compatible IDEs should automatically do it's thing to make matching files comform to set rules. Note that Visual Studio does not automatically convert all your files but do its bit when you work with files in IDE (open and save).

What next

While you could have a Visual-studio-wide setup, I strongly suggest to still include an EditorConfig root to your solution version control, so that explicit settings are automatically synced to all team members as well. Your drive root editorconfig file can be the fallback should some project not have their own editorconfig files set up yet.

How to get a index value from foreach loop in jstl

I face Similar problem now I understand we have some more option : varStatus="loop", Here will be loop will variable which will hold the index of lop.

It can use for use to read for Zeor base index or 1 one base index.

${loop.count}` it will give 1 starting base index.

${loop.index} it will give 0 base index as normal Index of array start from 0.

For Example :

<c:forEach var="currentImage" items="${cityBannerImages}" varStatus="loop">
<picture>
   <source srcset="${currentImage}" media="(min-width: 1000px)"></source>
   <source srcset="${cityMobileImages[loop.count]}" media="(min-width:600px)"></source>
   <img srcset="${cityMobileImages[loop.count]}" alt=""></img>
</picture>
</c:forEach>

For more Info please refer this link

Pointtype command for gnuplot

You first have to tell Gnuplot to use a style that uses points, e.g. with points or with linespoints. Try for example:

plot sin(x) with points

Output:

Now try:

plot sin(x) with points pointtype 5

Output:

You may also want to look at the output from the test command which shows you the capabilities of the current terminal. Here are the capabilities for my pngairo terminal:

Writing data into CSV file in C#

I would highly recommend you to go the more tedious route. Especially if your file size is large.

using(var w = new StreamWriter(path))
{
    for( /* your loop */)
    {
        var first = yourFnToGetFirst();
        var second = yourFnToGetSecond();
        var line = string.Format("{0},{1}", first, second);
        w.WriteLine(line);
        w.Flush();
    }
}

File.AppendAllText() opens a new file, writes the content and then closes the file. Opening files is a much resource-heavy operation, than writing data into open stream. Opening\closing a file inside a loop will cause performance drop.

The approach suggested by Johan solves that problem by storing all the output in memory and then writing it once. However (in case of big files) you program will consume a large amount of RAM and even crash with OutOfMemoryException

Another advantage of my solution is that you can implement pausing\resuming by saving current position in input data.

upd. Placed using in the right place

Fatal error: Maximum execution time of 300 seconds exceeded

I encountered a similar situation, and it turns out that Codeigniter (the PHP framework I was using) actually sets its own time limit:

In system/core/Codeigniter.php, line 106 in version 2.1.3 the following appears:

if (function_exists("set_time_limit") == TRUE AND @ini_get("safe_mode") == 0)
{
    @set_time_limit(300);
}

As there was no other way to avoid changing the core file, I removed it so as to allow configuration through php.ini, as well as give the infinite maximum execution time for a CLI request.

I recommend recording this change somewhere in the case of future CI version upgrades however.

How to create composite primary key in SQL Server 2008

To create a composite unique key on table

ALTER TABLE [TableName] ADD UNIQUE ([Column1], [Column2], [column3]);

Python - Passing a function into another function

Treat function as variable in your program so you can just pass them to other functions easily:

def test ():
   print "test was invoked"

def invoker(func):
   func()

invoker(test)  # prints test was invoked

Isn't the size of character in Java 2 bytes?

A char represents a character in Java (*). It is 2 bytes large (at least that's what the valid value range suggests).

That doesn't necessarily mean that every representation of a character is 2 bytes long. In fact many encodings only reserve 1 byte for every character (or use 1 byte for the most common characters).

When you call the String(byte[]) constructor you ask Java to convert the byte[] to a String using the platform default encoding. Since the platform default encoding is usually a 1-byte encoding such as ISO-8859-1 or a variable-length encoding such as UTF-8, it can easily convert that 1 byte to a single character.

If you run that code on a platform that uses UTF-16 (or UTF-32 or UCS-2 or UCS-4 or ...) as the platform default encoding, then you will not get a valid result (you'll get a String containing the Unicode Replacement Character instead).

That's one of the reasons why you should not depend on the platform default encoding: when converting between byte[] and char[]/String or between InputStream and Reader or between OutputStream and Writer, you should always specify which encoding you want to use. If you don't, then your code will be platform-dependent.

(*) that's not entirely true: a char represents a UTF-16 codepoint. Either one or two UTF-16 codepoints represent a Unicode codepoint. A Unicode codepoint usually represents a character, but sometimes multiple Unicode codepoints are used to make up a single character. But the approximation above is close enough to discuss the topic at hand.

What is recursion and when should I use it?

I have created a recursive function to concatenate a list of strings with a separator between them. I use it mostly to create SQL expressions, by passing a list of fields as the 'items' and a 'comma+space' as the separator. Here's the function (It uses some Borland Builder native data types, but can be adapted to fit any other environment):

String ArrangeString(TStringList* items, int position, String separator)
{
  String result;

  result = items->Strings[position];

  if (position <= items->Count)
    result += separator + ArrangeString(items, position + 1, separator);

  return result;
}

I call it this way:

String columnsList;
columnsList = ArrangeString(columns, 0, ", ");

Imagine you have an array named 'fields' with this data inside it: 'albumName', 'releaseDate', 'labelId'. Then you call the function:

ArrangeString(fields, 0, ", ");

As the function starts to work, the variable 'result' receives the value of the position 0 of the array, which is 'albumName'.

Then it checks if the position it's dealing with is the last one. As it isn't, then it concatenates the result with the separator and the result of a function, which, oh God, is this same function. But this time, check it out, it call itself adding 1 to the position.

ArrangeString(fields, 1, ", ");

It keeps repeating, creating a LIFO pile, until it reaches a point where the position being dealt with IS the last one, so the function returns only the item on that position on the list, not concatenating anymore. Then the pile is concatenated backwards.

Got it? If you don't, I have another way to explain it. :o)

Changing the git user inside Visual Studio Code

From VSCode Commande Palette select :

GitHub Pull Requests : Sign out of GitHub.

Then Sign in with your new credential.

how to define ssh private key for servers fetched by dynamic inventory in files

I'm using the following configuration:

#site.yml:
- name: Example play
  hosts: all
  remote_user: ansible
  become: yes
  become_method: sudo
  vars:
    ansible_ssh_private_key_file: "/home/ansible/.ssh/id_rsa"

surface plots in matplotlib

Just to chime in, Emanuel had the answer that I (and probably many others) are looking for. If you have 3d scattered data in 3 separate arrays, pandas is an incredible help and works much better than the other options. To elaborate, suppose your x,y,z are some arbitrary variables. In my case these were c,gamma, and errors because I was testing a support vector machine. There are many potential choices to plot the data:

  • scatter3D(cParams, gammas, avg_errors_array) - this works but is overly simplistic
  • plot_wireframe(cParams, gammas, avg_errors_array) - this works, but will look ugly if your data isn't sorted nicely, as is potentially the case with massive chunks of real scientific data
  • ax.plot3D(cParams, gammas, avg_errors_array) - similar to wireframe

Wireframe plot of the data

Wireframe plot of the data

3d scatter of the data

3d scatter of the data

The code looks like this:

    fig = plt.figure()
    ax = fig.gca(projection='3d')
    ax.set_xlabel('c parameter')
    ax.set_ylabel('gamma parameter')
    ax.set_zlabel('Error rate')
    #ax.plot_wireframe(cParams, gammas, avg_errors_array)
    #ax.plot3D(cParams, gammas, avg_errors_array)
    #ax.scatter3D(cParams, gammas, avg_errors_array, zdir='z',cmap='viridis')

    df = pd.DataFrame({'x': cParams, 'y': gammas, 'z': avg_errors_array})
    surf = ax.plot_trisurf(df.x, df.y, df.z, cmap=cm.jet, linewidth=0.1)
    fig.colorbar(surf, shrink=0.5, aspect=5)    
    plt.savefig('./plots/avgErrs_vs_C_andgamma_type_%s.png'%(k))
    plt.show()

Here is the final output:

plot_trisurf of xyz data

What is the max size of localStorage values?

I'm doing the following:

getLocalStorageSizeLimit = function () {

    var maxLength = Math.pow(2,24);
    var preLength = 0;
    var hugeString = "0";
    var testString;
    var keyName = "testingLengthKey";

    //2^24 = 16777216 should be enough to all browsers
    testString = (new Array(Math.pow(2, 24))).join("X");

    while (maxLength !== preLength) {
        try  {
            localStorage.setItem(keyName, testString);

            preLength = testString.length;
            maxLength = Math.ceil(preLength + ((hugeString.length - preLength) / 2));

            testString = hugeString.substr(0, maxLength);
        } catch (e) {
            hugeString = testString;

            maxLength = Math.floor(testString.length - (testString.length - preLength) / 2);
            testString = hugeString.substr(0, maxLength);
        }
    }

    localStorage.removeItem(keyName);

    maxLength = JSON.stringify(this.storageObject).length + maxLength + keyName.length - 2;

    return maxLength;
};

Hide scroll bar, but while still being able to scroll

The following was working for me on Microsoft, Chrome and Mozilla for a specific div element:

div.rightsidebar {
    overflow-y: auto;
    scrollbar-width: none;
    -ms-overflow-style: none;
}
div.rightsidebar::-webkit-scrollbar { 
    width: 0 !important;
}

How to print values separated by spaces instead of new lines in Python 2.7

This does almost everything you want:

f = open('data.txt', 'rb')

while True:
    char = f.read(1)
    if not char: break
    print "{:02x}".format(ord(char)),

With data.txt created like this:

f = open('data.txt', 'wb')
f.write("ab\r\ncd")
f.close()

I get the following output:

61 62 0d 0a 63 64

tl;dr -- 1. You are using poor variable names. 2. You are slicing your hex strings incorrectly. 3. Your code is never going to replace any newlines. You may just want to forget about that feature. You do not quite yet understand the difference between a character, its integer code, and the hex string that represents the integer. They are all different: two are strings and one is an integer, and none of them are equal to each other. 4. For some files, you shouldn't remove newlines.

===

1. Your variable names are horrendous.

That's fine if you never want to ask anybody questions. But since every one needs to ask questions, you need to use descriptive variable names that anyone can understand. Your variable names are only slightly better than these:

fname = 'data.txt'
f = open(fname, 'rb')
xxxyxx = f.read()

xxyxxx = len(xxxyxx)
print "Length of file is", xxyxxx, "bytes. "
yxxxxx = 0

while yxxxxx < xxyxxx:
    xyxxxx = hex(ord(xxxyxx[yxxxxx]))
    xyxxxx = xyxxxx[-2:]
    yxxxxx = yxxxxx + 1
    xxxxxy = chr(13) + chr(10)
    xxxxyx = str(xxxxxy)
    xyxxxxx = str(xyxxxx)
    xyxxxxx.replace(xxxxyx, ' ')
    print xyxxxxx

That program runs fine, but it is impossible to understand.

2. The hex() function produces strings of different lengths.

For instance,

print hex(61)
print hex(15)

--output:--
0x3d
0xf

And taking the slice [-2:] for each of those strings gives you:

3d
xf

See how you got the 'x' in the second one? The slice:

[-2:] 

says to go to the end of the string and back up two characters, then grab the rest of the string. Instead of doing that, take the slice starting 3 characters in from the beginning:

[2:]  

3. Your code will never replace any newlines.

Suppose your file has these two consecutive characters:

"\r\n"

Now you read in the first character, "\r", and convert it to an integer, ord("\r"), giving you the integer 13. Now you convert that to a string, hex(13), which gives you the string "0xd", and you slice off the first two characters giving you:

"d"

Next, this line in your code:

bndtx.replace(entx, ' ')

tries to find every occurrence of the string "\r\n" in the string "d" and replace it. There is never going to be any replacement because the replacement string is two characters long and the string "d" is one character long.

The replacement won't work for "\r\n" and "0d" either. But at least now there is a possibility it could work because both strings have two characters. Let's reduce both strings to a common denominator: ascii codes. The ascii code for "\r" is 13, and the ascii code for "\n" is 10. Now what about the string "0d"? The ascii code for the character "0" is 48, and the ascii code for the character "d" is 100. Those strings do not have a single character in common. Even this doesn't work:

 x = '0d' + '0a'
 x.replace("\r\n", " ")
 print x

 --output:--
 '0d0a'

Nor will this:

x = 'd' + 'a'
x.replace("\r\n", " ")
print x

--output:--
da

The bottom line is: converting a character to an integer then to a hex string does not end up giving you the original character--they are just different strings. So if you do this:

char = "a"
code = ord(char)
hex_str = hex(code)

print char.replace(hex_str, " ")

...you can't expect "a" to be replaced by a space. If you examine the output here:

char = "a"
print repr(char)

code = ord(char)
print repr(code)

hex_str = hex(code)
print repr(hex_str)

print repr(
    char.replace(hex_str, " ")
)

--output:--
'a'
97
'0x61'
'a'

You can see that 'a' is a string with one character in it, and '0x61' is a string with 4 characters in it: '0', 'x', '6', and '1', and you can never find a four character string inside a one character string.

4) Removing newlines can corrupt the data.

For some files, you do not want to replace newlines. For instance, if you were reading in a .jpg file, which is a file that contains a bunch of integers representing colors in an image, and some colors in the image happened to be represented by the number 13 followed by the number 10, your code would eliminate those colors from the output.

However, if you are writing a program to read only text files, then replacing newlines is fine. But then, different operating systems use different newlines. You are trying to replace Windows newlines(\r\n), which means your program won't work on files created by a Mac or Linux computer, which use \n for newlines. There are easy ways to solve that, but maybe you don't want to worry about that just yet.

I hope all that's not too confusing.

Slidedown and slideup layout with animation

This doesn't work for me, I want to to like jquery slideUp / slideDown function, I tried this code, but it only move the content wich stay at the same place after animation end, the view should have a 0dp height at start of slideDown and the view height (with wrap_content) after the end of the animation.

Sending email from Command-line via outlook without having to click send

Send SMS/Text Messages from Command Line with VBScript!

If VBA meets the rules for VB Script then it can be called from command line by simply placing it into a text file - in this case there's no need to specifically open Outlook.

I had a need to send automated text messages to myself from the command line, so I used the code below, which is just a compressed version of @Geoff's answer above.

Most mobile phone carriers worldwide provide an email address "version" of your mobile phone number. For example in Canada with Rogers or Chatr Wireless, an email sent to <YourPhoneNumber> @pcs.rogers.com will be immediately delivered to your Rogers/Chatr phone as a text message.

* You may need to "authorize" the first message on your phone, and some carriers may charge an additional fee for theses message although as far as I know, all Canadian carriers provide this little-known service for free. Check your carrier's website for details.

There are further instructions and various compiled lists of worldwide carrier's Email-to-Text addresses available online such as this and this and this.


Code & Instructions

  1. Copy the code below and paste into a new file in your favorite text editor.
  2. Save the file with any name with a .VBS extension, such as TextMyself.vbs.

That's all!
Just double-click the file to send a test message, or else run it from a batch file using START.

Sub SendMessage()
    Const EmailToSMSAddy = "[email protected]"
    Dim objOutlookRecip
    With CreateObject("Outlook.Application").CreateItem(0)
        Set objOutlookRecip = .Recipients.Add(EmailToSMSAddy)
        objOutlookRecip.Type = 1
        .Subject = "The computer needs your attention!"
        .Body = "Go see why Windows Command Line is texting you!"
        .Save
        .Send
    End With
End Sub

Example Batch File Usage:

START x:\mypath\TextMyself.vbs

Of course there are endless possible ways this could be adapted and customized to suit various practical or creative needs.

Clear text from textarea with selenium

With a simple call of clear() it appears in the DOM that the corresponding input/textarea component still has its old value, so any following changes on that component (e.g. filling the component with a new value) will not be processed in time.

If you take a look in the selenium source code you'll find that the clear()-method is documented with the following comment:

/** If this element is a text entry element, this will clear the value. Has no effect on other elements. Text entry elements are INPUT and TEXTAREA elements. Note that the events fired by this event may not be as you'd expect. In particular, we don't fire any keyboard or mouse events. If you want to ensure keyboard events are fired, consider using something like {@link #sendKeys(CharSequence...)} with the backspace key. To ensure you get a change event, consider following with a call to {@link #sendKeys(CharSequence...)} with the tab key. */

So using this helpful hint to clear an input/textarea (component that already has a value) AND assign a new value to it, you'll get some code like the following:

public void waitAndClearFollowedByKeys(By by, CharSequence keys) {
    LOG.debug("clearing element");
    wait(by, true).clear();
    sendKeys(by, Keys.BACK_SPACE.toString() + keys);
}

public void sendKeys(By by, CharSequence keysToSend) {
    WebElement webElement = wait(by, true);
    LOG.info("sending keys '{}' to {}", escapeProperly(keysToSend), by);
    webElement.sendKeys(keysToSend);
    LOG.info("keys sent");
}

private String escapeProperly(CharSequence keysToSend) {
    String result = "" + keysToSend;
    result = result.replace(Keys.TAB, "\\t");
    result = result.replace(Keys.ENTER, "\\n");
    result = result.replace(Keys.RETURN, "\\r");

    return result;
}

Sorry for this code being Java and not Python. Also, I had to skip out an additional "waitUntilPageIsReady()-method that would make this post way too long.

Hope this helps you on your journey with Selenium!

Place a button right aligned

Another possibility is to use an absolute positioning oriented to the right. You can do it this way:

style="position: absolute; right: 0;"

Sleep function Visual Basic

Since you are asking about .NET, you should change the parameter from Long to Integer. .NET's Integer is 32-bit. (Classic VB's integer was only 16-bit.)

Declare Sub Sleep Lib "kernel32.dll" (ByVal Milliseconds As Integer)

Really though, the managed method isn't difficult...

System.Threading.Thread.CurrentThread.Sleep(5000)

Be careful when you do this. In a forms application, you block the message pump and what not, making your program to appear to have hanged. Rarely is sleep a good idea.

Check if cookie exists else set cookie to Expire in 10 days

if (/(^|;)\s*visited=/.test(document.cookie)) {
    alert("Hello again!");
} else {
    document.cookie = "visited=true; max-age=" + 60 * 60 * 24 * 10; // 60 seconds to a minute, 60 minutes to an hour, 24 hours to a day, and 10 days.
    alert("This is your first time!");
}

is one way to do it. Note that document.cookie is a magic property, so you don't have to worry about overwriting anything, either.

There are also more convenient libraries to work with cookies, and if you don’t need the information you’re storing sent to the server on every request, HTML5’s localStorage and friends are convenient and useful.

How do you post to an iframe?

An iframe is used to embed another document inside a html page.

If the form is to be submitted to an iframe within the form page, then it can be easily acheived using the target attribute of the tag.

Set the target attribute of the form to the name of the iframe tag.

<form action="action" method="post" target="output_frame">
    <!-- input elements here --> 
</form>
<iframe name="output_frame" src="" id="output_frame" width="XX" height="YY">
</iframe>           

Advanced iframe target use
This property can also be used to produce an ajax like experience, especially in cases like file upload, in which case where it becomes mandatory to submit the form, in order to upload the files

The iframe can be set to a width and height of 0, and the form can be submitted with the target set to the iframe, and a loading dialog opened before submitting the form. So, it mocks a ajax control as the control still remains on the input form jsp, with the loading dialog open.

Exmaple

<script>
$( "#uploadDialog" ).dialog({ autoOpen: false, modal: true, closeOnEscape: false,                 
            open: function(event, ui) { jQuery('.ui-dialog-titlebar-close').hide(); } });

function startUpload()
{            
    $("#uploadDialog").dialog("open");
}

function stopUpload()
{            
    $("#uploadDialog").dialog("close");
}
</script>

<div id="uploadDialog" title="Please Wait!!!">
            <center>
            <img src="/imagePath/loading.gif" width="100" height="100"/>
            <br/>
            Loading Details...
            </center>
 </div>

<FORM  ENCTYPE="multipart/form-data" ACTION="Action" METHOD="POST" target="upload_target" onsubmit="startUpload()"> 
<!-- input file elements here--> 
</FORM>

<iframe id="upload_target" name="upload_target" src="#" style="width:0;height:0;border:0px solid #fff;" onload="stopUpload()">   
        </iframe>

How to copy java.util.list Collection

You may create a new list with an input of a previous list like so:

List one = new ArrayList()
//... add data, sort, etc
List two = new ArrayList(one);

This will allow you to modify the order or what elemtents are contained independent of the first list.

Keep in mind that the two lists will contain the same objects though, so if you modify an object in List two, the same object will be modified in list one.

example:

MyObject value1 = one.get(0);
MyObject value2 = two.get(0);
value1 == value2 //true
value1.setName("hello");
value2.getName(); //returns "hello"

Edit

To avoid this you need a deep copy of each element in the list like so:

List<Torero> one = new ArrayList<Torero>();
//add elements

List<Torero> two = new Arraylist<Torero>();
for(Torero t : one){
    Torero copy = deepCopy(t);
    two.add(copy);
}

with copy like the following:

public Torero deepCopy(Torero input){
    Torero copy = new Torero();
    copy.setValue(input.getValue());//.. copy primitives, deep copy objects again

    return copy;
}

When should you use 'friend' in C++?

When implementing tree algorithms for class, the framework code the prof gave us had the tree class as a friend of the node class.

It doesn't really do any good, other than let you access a member variable without using a setting function.

JVM heap parameters

The JVM will start with memory useage at the initial heap level. If the maxheap is higher, it will grow to the maxheap size as memory requirements exceed it's current memory.

So,

  • -Xms512m -Xmx512m

JVM starts with 512 M, never resizes.

  • -Xms64m -Xmx512m

JVM starts with 64M, grows (up to max ceiling of 512) if mem. requirements exceed 64.

Fatal error: Uncaught Error: Call to undefined function mysql_connect()

mysql_* functions have been removed in PHP 7.

You probably have PHP 7 in XAMPP. You now have two alternatives: MySQLi and PDO.

Additionally, here is a nice wiki page about PDO.