Programs & Examples On #Webstore

Postman - How to see request with headers and body data with variables substituted

If, like me, you are still using the browser version (which will be deprecated soon), have you tried the "Code" button?

enter image description here

This should generate a snippet which contains the entire request Postman is firing. You can even choose the language for the snippet. I find it quite handy when I need to debug stuff.

Hope this helps.

Why my $.ajax showing "preflight is invalid redirect error"?

The error indicates that the preflight is getting a redirect response. This can happen for a number of reasons. Find out where you are getting redirected to for clues to why it is happening. Check the network tab in Developer Tools.

One reason, as @Peter T mentioned, is that the API likely requires HTTPS connections rather than HTTP and all requests over HTTP get redirected. The Location header returned by the 302 response would say the same url with http changed to https in this case.

Another reason might be that your authentication token is not getting sent, or is not correct. Most servers are set up to redirect all requests that don't include an authentication token to the login page. Again, check your Location header to see if this is where you're getting sent and also take a look to make sure the browser sent your auth token with the request.

Oftentimes, a server will be configured to always redirect requests that don't have auth tokens to the login page - including your preflight/OPTIONS requests. This is a problem. Change the server configuration to permit OPTIONS requests from non-authenticated users.

Using Postman to access OAuth 2.0 Google APIs

  1. go to
  2. create web application credentials.

Postman API Access

  1. use these settings with oauth2 in Postman:

SCOPE = https: //

post https: //

  "fields": [
      "fieldName": "role",
      "fieldType": "STRING",
      "multiValued": true,
      "readAccessType": "ADMINS_AND_SELF"
  "schemaName": "SAML"
  1. to patch user use:


PATCH[email protected]

  "customSchemas": {
     "SAML": {
       "role": [
          "value": "arn:aws:iam::123456789123:role/Admin,arn:aws:iam::123456789123:saml-provider/GoogleApps",
          "customType": "Admin"

How to post object and List using postman

Make sure that you have made the content-type as application/json in header request and Post from body under the raw tab.

  "address": "colombo",
  "username": "hesh",
  "password": "123",
  "registetedDate": "2015-4-3",
  "firstname": "hesh",
  "contactNo": "07762",
  "accountNo": "16161",
  "lastName": "jay",
  "arrayObjectName" : [{
    "Id" : 1,
    "Name": "ABC" },
    "Id" : 2,
    "Name" : "XYZ"
  "intArrayName" : [111,222,333],
  "stringArrayName" : ["a","b","c"]


Why does my JavaScript code receive a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error, while Postman does not?

If I understood it right you are doing an XMLHttpRequest to a different domain than your page is on. So the browser is blocking it as it usually allows a request in the same origin for security reasons. You need to do something different when you want to do a cross-domain request. A tutorial about how to achieve that is Using CORS.

When you are using postman they are not restricted by this policy. Quoted from Cross-Origin XMLHttpRequest:

Regular web pages can use the XMLHttpRequest object to send and receive data from remote servers, but they're limited by the same origin policy. Extensions aren't so limited. An extension can talk to remote servers outside of its origin, as long as it first requests cross-origin permissions.

How to send a correct authorization header for basic authentication

PHP - curl:

$username = 'myusername';
$password = 'mypassword';
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);

PHP - POST in WordPress:

$username = 'myusername';
$password = 'mypassword';
wp_remote_post('https://...some...api...endpoint...', array(
  'headers' => array(
    'Authorization' => 'Basic ' . base64_encode("$username:$password")

Google Chrome default opening position and size

First, close all instances of Google Chrome. There should be no instances of chrome.exe running in the Windows Task Manager. Then

  • Go to %LOCALAPPDATA%\Google\Chrome\User Data\Default\.
  • Open the file "Preferences" in a text editor like Notepad.
  • First, resave the file to something like "Preference - Old" without any extension (i.e. no .txt). This will serve as a backup, should something go wrong.
  • Look for a section called "browser." Inside that section, you should find a subsection called window_placement. Under window_placement you will see things like "bottom", "left", "right", etc. with numbers after them.

You will need to play around with these numbers to get your desired window size and placement. When finished, save this file with the name "Preferences" again with no extension. This will overwrite the existing Preferences file. Open Chrome and see how you did. If you're not satisfied with the size and placement, close Chrome and change the numbers in the Preferences file until you get what you want.

How do I Alter Table Column datatype on more than 1 column?

Use the following syntax:

  ALTER TABLE your_table
  MODIFY COLUMN column1 datatype,
  MODIFY COLUMN column2 datatype,
  ... ... ... ... ... 
  ... ... ... ... ...

Based on that, your ALTER command should be:

  ALTER TABLE webstore.Store

Note that:

  1. There are no second brackets around the MODIFY statements.
  2. I used two separate MODIFY statements for two separate columns.

This is the standard format of the MODIFY statement for an ALTER command on multiple columns in a MySQL table.

Take a look at the following: and Alter multiple columns in a single statement

How do you determine what technology a website is built on?

Most ASP.NET sites are easy to identify from the .aspx in the URLs. There are also telltale signs in the HTML source, like a hidden form field named __VIEWSTATE or the WebResource.axd JavaScript. HTML elements will often have id attributes starting with something like _ctl0.

Rails sites will usually include stylesheets from /stylesheets and JavaScript files from /javascripts and each URL will usually have a query string containing a timestamp to thwart caching. Form fields will often follow the naming convention of model_name[attribute_name].

Android: keeping a background service alive (preventing process death)

I had a similar issue. On some devices after a while Android kills my service and even startForeground() does not help. And my customer does not like this issue. My solution is to use AlarmManager class to make sure that the service is running when it's necessary. I use AlarmManager to create a kind of watchdog timer. It checks from time to time if the service should be running and restart it. Also I use SharedPreferences to keep the flag whether the service should be running.

Creating/dismissing my watchdog timer:

void setServiceWatchdogTimer(boolean set, int timeout)
    Intent intent;
    PendingIntent alarmIntent;
    intent = new Intent(); // forms and creates appropriate Intent and pass it to AlarmManager
    intent.setClass(this, WatchDogServiceReceiver.class);
    alarmIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager am=(AlarmManager)getSystemService(Context.ALARM_SERVICE);
        am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + timeout, alarmIntent);

Receiving and processing the intent from the watchdog timer:

/** this class processes the intent and
 *  checks whether the service should be running
public static class WatchDogServiceReceiver extends BroadcastReceiver
    public void onReceive(Context context, Intent intent)

            // check your flag and 
            // restart your service if it's necessary
            setServiceWatchdogTimer(true, 60000*5); // restart the watchdogtimer

Indeed I use WakefulBroadcastReceiver instead of BroadcastReceiver. I gave you the code with BroadcastReceiver just to simplify it.

How to remove entry from $PATH on mac

Use sudo pico /etc/paths inside the terminal window and change the entries to the one you want to remove, then open a new terminal session.

How to determine if binary tree is balanced?

Post order solution, traverse the tree only once. Time complexity is O(n), space is O(1), it's better than top-down solution. I give you a java version implementation.

public static <T> boolean isBalanced(TreeNode<T> root){
    return checkBalance(root) != -1;

private static <T> int checkBalance(TreeNode<T> node){
    if(node == null) return 0;
    int left = checkBalance(node.getLeft());

    if(left == -1) return -1;

    int right = checkBalance(node.getRight());

    if(right == -1) return -1;

    if(Math.abs(left - right) > 1){
        return -1;
        return 1 + Math.max(left, right);

Pointer to class data member "::*"

You can later access this member, on any instance:

int main()
  int Car::*pSpeed = &Car::speed;    
  Car myCar;
  Car yourCar;

  int mySpeed = myCar.*pSpeed;
  int yourSpeed = yourCar.*pSpeed;

  assert(mySpeed > yourSpeed); // ;-)

  return 0;

Note that you do need an instance to call it on, so it does not work like a delegate.
It is used rarely, I've needed it maybe once or twice in all my years.

Normally using an interface (i.e. a pure base class in C++) is the better design choice.

How do I make Git use the editor of my choice for commits?

For Textmate Users

This opens Textmate editor in when you want to edit your commits. Requires textmate command line tools to be installed.

git config --global core.editor "mate -w"

How to modify existing, unpushed commit messages?

Wow, so there are a lot of ways to do this.

Yet another way to do this is to delete the last commit, but keep its changes so that you won't lose your work. You can then do another commit with the corrected message. This would look something like this:

git reset --soft HEAD~1
git commit -m 'New and corrected commit message'

I always do this if I forget to add a file or do a change.

Remember to specify --soft instead of --hard, otherwise you lose that commit entirely.

Newline character in StringBuilder

I would make use of the Environment.NewLine property.

Something like:

StringBuilder sb = new StringBuilder();
sb.AppendFormat("Foo{0}Bar", Environment.NewLine);
string s = sb.ToString();


StringBuilder sb = new StringBuilder();
string s = sb.ToString();

If you wish to have a new line after each append, you can have a look at Ben Voigt's answer.

CSS-Only Scrollable Table with fixed headers

This answer will be used as a placeholder for the not fully supported position: sticky and will be updated over time. It is currently advised to not use the native implementation of this in a production environment.

See this for the current support:

Use of position: sticky

An alternative answer would be using position: sticky. As described by W3C:

A stickily positioned box is positioned similarly to a relatively positioned box, but the offset is computed with reference to the nearest ancestor with a scrolling box, or the viewport if no ancestor has a scrolling box.

This described exactly the behavior of a relative static header. It would be easy to assign this to the <thead> or the first <tr> HTML-tag, as this should be supported according to W3C. However, both Chrome, IE and Edge have problems assigning a sticky position property to these tags. There also seems to be no priority in solving this at the moment.

What does seem to work for a table element is assigning the sticky property to a table-cell. In this case the <th> cells.

Because a table is not a block-element that respects the static size you assign to it, it is best to use a wrapper element to define the scroll-overflow.

The code

div {_x000D_
  display: inline-block;_x000D_
  height: 150px;_x000D_
  overflow: auto_x000D_
table th {_x000D_
  position: -webkit-sticky;_x000D_
  position: sticky;_x000D_
  top: 0;_x000D_
/* == Just general styling, not relevant :) == */_x000D_
table {_x000D_
  border-collapse: collapse;_x000D_
th {_x000D_
  background-color: #1976D2;_x000D_
  color: #fff;_x000D_
td {_x000D_
  padding: 1em .5em;_x000D_
table tr {_x000D_
  color: #212121;_x000D_
table tr:nth-child(odd) {_x000D_
  background-color: #BBDEFB;_x000D_
  <table border="0">_x000D_
      <td>row 1, cell 1</td>_x000D_
      <td>row 1, cell 2</td>_x000D_
      <td>row 1, cell 2</td>_x000D_
      <td>row 1, cell 2</td>_x000D_
      <td>row 2, cell 1</td>_x000D_
      <td>row 2, cell 2</td>_x000D_
      <td>row 1, cell 2</td>_x000D_
      <td>row 1, cell 2</td>_x000D_
      <td>row 2, cell 1</td>_x000D_
      <td>row 2, cell 2</td>_x000D_
      <td>row 1, cell 2</td>_x000D_
      <td>row 1, cell 2</td>_x000D_
      <td>row 2, cell 1</td>_x000D_
      <td>row 2, cell 2</td>_x000D_
      <td>row 1, cell 2</td>_x000D_
      <td>row 1, cell 2</td>_x000D_
      <td>row 2, cell 1</td>_x000D_
      <td>row 2, cell 2</td>_x000D_
      <td>row 1, cell 2</td>_x000D_
      <td>row 1, cell 2</td>_x000D_

In this example I use a simple <div> wrapper to define the scroll-overflow done with a static height of 150px. This can of course be any size. Now that the scrolling box has been defined, the sticky <th> elements will corespondent "to the nearest ancestor with a scrolling box", which is the div-wrapper.

Use of a position: sticky polyfill

Non-supported devices can make use of a polyfill, which implements the behavior through code. An example is stickybits, which resembles the same behavior as the browser's implemented position: sticky.

Example with polyfill:

How to know Hive and Hadoop versions from command prompt?

You can not get hive version from command line.

You can checkout hadoop version as mentioned by Dave.

Also if you are using cloudera distribution, then look directly at the libs:

ls /usr/lib/hive/lib/ and check for hive library


You can also check the compatible versions here:

How do I remove an array item in TypeScript?

One more solution using Typescript:

let updatedArray = [];
for (let el of this.oldArray) {
    if (el !== elementToRemove) {
this.oldArray = updated;

How to programmatically disable page scrolling with jQuery

I put an answer that might help here: jQuery simplemodal disable scrolling

It shows how to turn off the scroll bars without shifting the text around. You can ignore the parts about simplemodal.

How to declare or mark a Java method as deprecated?

Use @Deprecated on method. Don't forget about clarifying javadoc field:

 * Does some thing in old style.
 * @deprecated use {@link #new()} instead.  
public void old() {
// ...

Git "error: The branch 'x' is not fully merged"

I did not have the upstream branch on my local git. I had created a local branch from master, git checkout -b mybranch . I created a branch with bitbucket GUI on the upstream git and pushed my local branch (mybranch) to that upstream branch. Once I did a git fetch on my local git to retrieve the upstream branch, I could do a git branch -d mybranch.

jQuery return ajax result into outside variable

This is all you need to do:

var myVariable;

    'async': false,
    'type': "POST",
    'global': false,
    'dataType': 'html',
    'url': "ajax.php?first",
    'data': { 'request': "", 'target': 'arrange_url', 'method': 'method_target' },
    'success': function (data) {
        myVariable = data;

NOTE: Use of "async" has been depreciated. See

Allowed memory size of 536870912 bytes exhausted in Laravel

While using Laravel on apache server there is another php.ini


Modify the memory limit value in this file


and restart the apache server

 sudo service apache2 restart

bash script use cut command at variable and store result at another variable

You can avoid the loop and cut etc by using:

awk -F ':' '{system("ping " $1);}' config.txt

However it would be better if you post a snippet of your config.txt

IE8 css selector

Building upon image72's excellent answer, you could actually have advanced CSS selectors like this:

<!--[if lt IE 7]><body class="IE IE7down IE8down IE9down IE10down"><![endif]-->
<!--[if IE 7]><body class="IE IE7 IE7down IE8down IE9down IE10down IE7up"><![endif]-->
<!--[if IE 8]><body class="IE IE8 IE8down IE9down IE10down IE7up IE8up"><![endif]-->
<!--[if IE 9]><body class="IE IE9 IE9down IE10down IE7up IE8up IE9up"><![endif]-->
<!--[if gte IE 10]><body class="IE IE10 IE10down IE7up IE8up IE9up IE10up"><![endif]-->
<!--[if !IE]>--><body class="notIE"><!--<![endif]-->

so that in your css you can do this:

.notIE   .foo { color: blue;   } /* Target all browsers except IE */
.IE9up   .foo { color: green;  } /* Taget IE equal or greater than 9 */
.IE8     .foo { color: orange; } /* Taget IE 8 only */
.IE7down .foo { color: red;    } /* Target IE equal or less than 7 */

.IE8 .foo, .IE9 .foo {
    font-size: 1.2em;            /* Target IE8 & IE9 only */

.bar { background-color: gray; } /* Applies to all browsers, as usual */

/* Maybe show a message only to IE users? */
.notIE #betterBrowser { display: none;  } /* Any browser except IE */
.IE    #betterBrowser { display: block; } /* All versions of IE */

This is great because:

  • It's perfectly standards compliant (no ugly/dangerous css hacks)
  • No need to have separate stylesheets
  • You can easily target any version of IE as well as complex combinations

Limit the size of a file upload (html input element)

var uploadField = document.getElementById("file");

uploadField.onchange = function() {
    if(this.files[0].size > 2097152){
       alert("File is too big!");
       this.value = "";

This example should work fine. I set it up for roughly 2MB, 1MB in Bytes is 1,048,576 so you can multiply it by the limit you need.

Here is the jsfiddle example for more clearence:

List of Stored Procedures/Functions Mysql Command Line

Shows all the stored procedures:


Shows all the functions:


Shows the definition of the specified procedure:


Shows you all the procedures of the given database:


MSBUILD : error MSB1008: Only one project can be specified

You need to put qoutes around the path and file name.
So use MSBuild "C:\Path Name\File Name.Exe" /[Options]

Display a RecyclerView in Fragment

You should retrieve RecyclerView in a Fragment after inflating core View using that View. Perhaps it can't find your recycler because it's not part of Activity

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
    final View view = inflater.inflate(R.layout.fragment_artist_tracks, container, false);
    final FragmentActivity c = getActivity();
    final RecyclerView recyclerView = (RecyclerView) view.findViewById(;
    LinearLayoutManager layoutManager = new LinearLayoutManager(c);

    new Thread(new Runnable() {
        public void run() {
            final RecyclerAdapter adapter = new RecyclerAdapter(c);
            c.runOnUiThread(new Runnable() {
                public void run() {

    return view;

Permanently add a directory to PYTHONPATH?

Adding export PYTHONPATH="${PYTHONPATH}:/my/other/path" to the ~/.bashrc might not work if PYTHONPATH does not currently exist (because of the :).

export PYTHONPATH="/my/other/path1"
export PYTHONPATH="${PYTHONPATH}:/my/other/path2"

Adding the above to my ~/.bashrc did the trick for me on Ubuntu 16.04

JavaScript implementation of Gzip

Here are some other compression algorithms implemented in Javascript:

Two divs side by side - Fluid display

Here's my answer for those that are Googling:


.column {
    float: left;
    width: 50%;

/* Clear floats after the columns */
.container:after {
    content: "";
    display: table;
    clear: both;

Here's the HTML:

<div class="container">
    <div class="column"></div>
    <div class="column"></div>

Center icon in a div - horizontally and vertically

Here is a way to center content both vertically and horizontally in any situation, which is useful when you do not know the width or height or both:


#container {
    display: table;
    width: 300px; /* not required, just for example */
    height: 400px; /* not required, just for example */

#update {
    display: table-cell;
    vertical-align: middle;
    text-align: center;


<div id="container">
    <a id="update" href="#">
        <i class="icon-refresh"></i>


Note that the width and height values are just for demonstration here, you can change them to anything you want (or remove them entirely) and it will still work because the vertical centering here is a product of the way the table-cell display property works.

Restart android machine

Have you tried simply 'reboot' with adb?

  adb reboot

Also you can run complete shell scripts (e.g. to reboot your emulator) via adb:

 adb shell <command>

The official docs can be found here.

How to change values in a tuple?

EDIT: This doesn't work on tuples with duplicate entries yet!!

Based on Pooya's idea:

If you are planning on doing this often (which you shouldn't since tuples are inmutable for a reason) you should do something like this:

def modTupByIndex(tup, index, ins):
    return tuple(tup[0:index]) + (ins,) + tuple(tup[index+1:])

print modTupByIndex((1,2,3),2,"a")

Or based on Jon's idea:

def modTupByIndex(tup, index, ins):
    lst = list(tup)
    lst[index] = ins
    return tuple(lst)

print modTupByIndex((1,2,3),1,"a")

Angular-cli from css to scss

For Angular 6 check the Official documentation

Note: For @angular/cli versions older than 6.0.0-beta.6 use ng set in place of ng config.

For existing projects

In an existing angular-cli project that was set up with the default css styles you will need to do a few things:

  1. Change the default style extension to scss

Manually change in .angular-cli.json (Angular 5.x and older) or angular.json (Angular 6+) or run:

ng config defaults.styleExt=scss

if you get an error: Value cannot be found. use the command:

ng config schematics.@schematics/angular:component.styleext scss

(*source: Angular CLI SASS options)

  1. Rename your existing .css files to .scss (i.e. styles.css and app/app.component.css)

  2. Point the CLI to find styles.scss

Manually change the file extensions in apps[0].styles in angular.json

  1. Point the components to find your new style files

Change the styleUrls in your components to match your new file names

For future projects

As @Serginho mentioned you can set the style extension when running the ng new command

ng new your-project-name --style=scss

If you want to set the default for all projects you create in the future run the following command:

ng config --global defaults.styleExt=scss

How to delete a workspace in Eclipse?

I'm not sure about older versions, but from NEON onward, you can just right click on workspace and select Remove from launcher selection option.

Eclipse Neon - Remove Workspace

of course this won't remove the original files. It simply removes it from the list of suggested workspaces.

Create two blank lines in Markdown

Basically, if the library you are using is CommonMark-compliant, you can add multiple hard line breaks (<br />) easily. Here's a quotation from CommonMark's latest specifications (0.28):

A line break (not in a code span or HTML tag) that is preceded by two or more spaces and does not occur at the end of a block is parsed as a hard line break (rendered in HTML as a

and then...

For a more visible alternative, a backslash before the line ending may be used instead of two spaces

The specification is quite clear. However, the library I have been using MarkDig, doesn't quite work with the two spaces technique (must be a bug), but it works flawlessly with a backlash.

That said, this input...

Line one\
Line two

will produce four hard line breaks after "Line one". You can see it here (using backlash)...

Notice how all CommonMark-compliant implementations will get it right.

Tuning nginx worker_process to obtain 100k hits per min

Config file:

worker_processes  4;  # 2 * Number of CPUs

events {
    worker_connections  19000;  # It's the key to high performance - have a lot of connections available

worker_rlimit_nofile    20000;  # Each connection needs a filehandle (or 2 if you are proxying)

# Total amount of users you can serve = worker_processes * worker_connections

more info: Optimizing nginx for high traffic loads

Concatenating strings doesn't work as expected

std::string a = "Hello ";
std::string b = "World ";
std::string c = a;

wget: unable to resolve host address `http'

I have this issue too. I suspect there is an issue with DigitalOcean’s nameservers, so this will likely affect a lot of other people too. Here’s what I’ve done to temporarily get around it - but someone else might be able to advise on a better long-term fix:

  1. Make sure your DNS Resolver config file is writable:

    sudo chmod o+r /etc/resolv.conf

  2. Temporarily change your DNS to use Google’s nameservers instead of DigitalOcean’s:

    sudo nano /etc/resolv.conf

Change the IP address in the file to:

Press CTRL + X to save the file.

This is only a temporary fix as this file is automatically written/updated by the server, however, I’ve not yet worked out what writes to it so that I can update it permanently.

How do I create a GUI for a windows application using C++?

A simple "window" with some text and a button is just a MessageBox. You can create them with a single function call; you don't need any library whatsoever.

Android Error [Attempt to invoke virtual method 'void' on a null object reference]

In my case is because of styles.xml set the wrong parent theme, i.e. NoActionBar theme of course getSupportActionbar() is null:

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">

Changed it to something else fixed it:

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">

Transition color fade on hover?

What do you want to fade? The background or color attribute?

Currently you're changing the background color, but telling it to transition the color property. You can use all to transition all properties.

.clicker { 
    -moz-transition: all .2s ease-in;
    -o-transition: all .2s ease-in;
    -webkit-transition: all .2s ease-in;
    transition: all .2s ease-in;
    background: #f5f5f5; 
    padding: 20px;

.clicker:hover { 
    background: #eee;

Otherwise just use transition: background .2s ease-in.

Install Visual Studio 2013 on Windows 7

Visual Studio 2013 System Requirements

Supported Operating Systems:

  • Windows 8.1 (x86 and x64)
  • Windows 8 (x86 and x64)
  • Windows 7 SP1 (x86 and x64)
  • Windows Server 2012 R2 (x64)
  • Windows Server 2012 (x64)
  • Windows Server 2008 R2 SP1 (x64)

Hardware requirements:

  • 1.6 GHz or faster processor
  • 1 GB of RAM (1.5 GB if running on a virtual machine)
  • 20 GB of available hard disk space
  • 5400 RPM hard disk drive
  • DirectX 9-capable video card that runs at 1024 x 768 or higher display resolution

Additional Requirements for the laptop:

  • Internet Explorer 10
  • KB2883200 (available through Windows Update) is required

And don't forget to reboot after updating your windows

How to "perfectly" override a dict?

My requirements were a bit stricter:

  • I had to retain case info (the strings are paths to files displayed to the user, but it's a windows app so internally all operations must be case insensitive)
  • I needed keys to be as small as possible (it did make a difference in memory performance, chopped off 110 mb out of 370). This meant that caching lowercase version of keys is not an option.
  • I needed creation of the data structures to be as fast as possible (again made a difference in performance, speed this time). I had to go with a builtin

My initial thought was to substitute our clunky Path class for a case insensitive unicode subclass - but:

  • proved hard to get that right - see: A case insensitive string class in python
  • turns out that explicit dict keys handling makes code verbose and messy - and error prone (structures are passed hither and thither, and it is not clear if they have CIStr instances as keys/elements, easy to forget plus some_dict[CIstr(path)] is ugly)

So I had finally to write down that case insensitive dict. Thanks to code by @AaronHall that was made 10 times easier.

class CIstr(unicode):
    """See, especially for inlines"""
    __slots__ = () # does make a difference in memory performance

    def __hash__(self):
        return hash(self.lower())
    def __eq__(self, other):
        if isinstance(other, CIstr):
            return self.lower() == other.lower()
        return NotImplemented
    def __ne__(self, other):
        if isinstance(other, CIstr):
            return self.lower() != other.lower()
        return NotImplemented
    def __lt__(self, other):
        if isinstance(other, CIstr):
            return self.lower() < other.lower()
        return NotImplemented
    def __ge__(self, other):
        if isinstance(other, CIstr):
            return self.lower() >= other.lower()
        return NotImplemented
    def __gt__(self, other):
        if isinstance(other, CIstr):
            return self.lower() > other.lower()
        return NotImplemented
    def __le__(self, other):
        if isinstance(other, CIstr):
            return self.lower() <= other.lower()
        return NotImplemented
    def __repr__(self):
        return '{0}({1})'.format(type(self).__name__,
                                 super(CIstr, self).__repr__())

def _ci_str(maybe_str):
    """dict keys can be any hashable object - only call CIstr if str"""
    return CIstr(maybe_str) if isinstance(maybe_str, basestring) else maybe_str

class LowerDict(dict):
    """Dictionary that transforms its keys to CIstr instances.
    Adapted from:
    __slots__ = () # no __dict__ - that would be redundant

    @staticmethod # because this doesn't make sense as a global function.
    def _process_args(mapping=(), **kwargs):
        if hasattr(mapping, 'iteritems'):
            mapping = getattr(mapping, 'iteritems')()
        return ((_ci_str(k), v) for k, v in
                chain(mapping, getattr(kwargs, 'iteritems')()))
    def __init__(self, mapping=(), **kwargs):
        # dicts take a mapping or iterable as their optional first argument
        super(LowerDict, self).__init__(self._process_args(mapping, **kwargs))
    def __getitem__(self, k):
        return super(LowerDict, self).__getitem__(_ci_str(k))
    def __setitem__(self, k, v):
        return super(LowerDict, self).__setitem__(_ci_str(k), v)
    def __delitem__(self, k):
        return super(LowerDict, self).__delitem__(_ci_str(k))
    def copy(self): # don't delegate w/ super - dict.copy() -> dict :(
        return type(self)(self)
    def get(self, k, default=None):
        return super(LowerDict, self).get(_ci_str(k), default)
    def setdefault(self, k, default=None):
        return super(LowerDict, self).setdefault(_ci_str(k), default)
    __no_default = object()
    def pop(self, k, v=__no_default):
        if v is LowerDict.__no_default:
            # super will raise KeyError if no default and key does not exist
            return super(LowerDict, self).pop(_ci_str(k))
        return super(LowerDict, self).pop(_ci_str(k), v)
    def update(self, mapping=(), **kwargs):
        super(LowerDict, self).update(self._process_args(mapping, **kwargs))
    def __contains__(self, k):
        return super(LowerDict, self).__contains__(_ci_str(k))
    def fromkeys(cls, keys, v=None):
        return super(LowerDict, cls).fromkeys((_ci_str(k) for k in keys), v)
    def __repr__(self):
        return '{0}({1})'.format(type(self).__name__,
                                 super(LowerDict, self).__repr__())

Implicit vs explicit is still a problem, but once dust settles, renaming of attributes/variables to start with ci (and a big fat doc comment explaining that ci stands for case insensitive) I think is a perfect solution - as readers of the code must be fully aware that we are dealing with case insensitive underlying data structures. This will hopefully fix some hard to reproduce bugs, which I suspect boil down to case sensitivity.

Comments/corrections welcome :)

How to check whether a string contains a substring in Ruby

You can use the String Element Reference method which is []

Inside the [] can either be a literal substring, an index, or a regex:

> s='abcdefg'
=> "abcdefg"
> s['a']
=> "a"
> s['z']
=> nil

Since nil is functionally the same as false and any substring returned from [] is true you can use the logic as if you use the method .include?:

0> if s[sub_s]
1>    puts "\"#{s}\" has \"#{sub_s}\""
1> else 
1*    puts "\"#{s}\" does not have \"#{sub_s}\""
1> end
"abcdefg" has "abc"

0> if s[sub_s]
1>    puts "\"#{s}\" has \"#{sub_s}\""
1> else 
1*    puts "\"#{s}\" does not have \"#{sub_s}\""
1> end
"abcdefg" does not have "xyz" 

Just make sure you don't confuse an index with a sub string:

> '123456790'[8]    # integer is eighth element, or '0'
=> "0"              # would test as 'true' in Ruby
> '123456790'['8']  
=> nil              # correct

You can also use a regex:

> s[/A/i]
=> "a"
> s[/A/]
=> nil

Determine SQL Server Database Size

The best solution is maybe to calculate the size of each database file, using the sys.sysfiles view, considering a size of 8 KB for each page, as follows:

USE [myDatabase]

    [size] * 8
    , [filename]
FROM sysfiles

The [field] column represents the size of the file, in pages (MSDN Reference to sysfiles).

You would see there will be at least two files (MDF and LDF): the sum of these files will give you the correct size of the entire database...

Matplotlib different size subplots

Another way is to use the subplots function and pass the width ratio with gridspec_kw:

import numpy as np
import matplotlib.pyplot as plt 

# generate some data
x = np.arange(0, 10, 0.2)
y = np.sin(x)

# plot it
f, (a0, a1) = plt.subplots(1, 2, gridspec_kw={'width_ratios': [3, 1]})
a0.plot(x, y)
a1.plot(y, x)


What does enumerate() mean?

As other users have mentioned, enumerate is a generator that adds an incremental index next to each item of an iterable.

So if you have a list say l = ["test_1", "test_2", "test_3"], the list(enumerate(l)) will give you something like this: [(0, 'test_1'), (1, 'test_2'), (2, 'test_3')].

Now, when this is useful? A possible use case is when you want to iterate over items, and you want to skip a specific item that you only know its index in the list but not its value (because its value is not known at the time).

for index, value in enumerate(joint_values):
   if index == 3:

   # Do something with the other `value`

So your code reads better because you could also do a regular for loop with range but then to access the items you need to index them (i.e., joint_values[i]).

Although another user mentioned an implementation of enumerate using zip, I think a more pure (but slightly more complex) way without using itertools is the following:

def enumerate(l, start=0):
    return zip(range(start, len(l) + start), l)


l = ["test_1", "test_2", "test_3"]
enumerate(l, 10)


[(0, 'test_1'), (1, 'test_2'), (2, 'test_3')]

[(10, 'test_1'), (11, 'test_2'), (12, 'test_3')]

As mentioned in the comments, this approach with range will not work with arbitrary iterables as the original enumerate function does.

python ignore certificate validation urllib2

For those who uses an opener, you can achieve the same thing based on Enno Gröper's great answer:

import urllib2, ssl

ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

opener = urllib2.build_opener(urllib2.HTTPSHandler(context=ctx), your_first_handler, your_second_handler[...])
opener.addheaders = [('Referer', '')]

content ="https://localhost/").read()

And then use it as before.

According to build_opener and HTTPSHandler, a HTTPSHandler is added if ssl module exists, here we just specify our own instead of the default one.

socket connect() vs bind()

To make understanding better , lets find out where exactly bind and connect comes into picture,

Further to positioning of two calls , as clarified by Sourav,

bind() associates the socket with its local address [that's why server side binds, so that clients can use that address to connect to server.] connect() is used to connect to a remote [server] address, that's why is client side, connect [read as: connect to server] is used.

We cannot use them interchangeably (even when we have client/server on same machine) because of specific roles and corresponding implementation.

I will further recommend to correlate these calls TCP/IP handshake .

enter image description here

So , who will send SYN here , it will be connect() . While bind() is used for defining the communication end point.

Hope this helps!!

Check if xdebug is working

Try as following, should return "exists" or "non exists":

echo (extension_loaded('xdebug') ? '' : 'non '), 'exists';

How to make a boolean variable switch between true and false every time a method is invoked?

Assuming your code above is the actual code, you have two problems:

1) your if statements need to be '==', not '='. You want to do comparison, not assignment.

2) The second if should be an 'else if'. Otherwise when it's false, you will set it to true, then the second if will be evaluated, and you'll set it back to false, as you describe

if (a == false) {
  a = true;
} else if (a == true) {
  a = false;

Another thing that would make it even simpler is the '!' operator:

a = !a;

will switch the value of a.

How to add new contacts in android

These examples are fine, I wanted to point out that you can achieve the same result using an Intent. The intent opens the Contacts app with the fields you provide already filled in.

It's up to the user to save the newly created contact.

You can read about it here:

Intent contactIntent = new Intent(ContactsContract.Intents.Insert.ACTION);

        .putExtra(ContactsContract.Intents.Insert.NAME, "Contact Name")
        .putExtra(ContactsContract.Intents.Insert.PHONE, "5555555555");

startActivityForResult(contactIntent, 1);

startActivityForResult() gives you the opportunity to see the result.

I've noticed the resultCode works on >5.0 devices,

but I have an older Samsung (<5) that always returns RESULT_CANCELLED (0).

Which I understand is the default return if an activity doesn't expect to return anything.

protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);

    if (requestCode == 1)
        if (resultCode == Activity.RESULT_OK) {
            Toast.makeText(this, "Added Contact", Toast.LENGTH_SHORT).show();
        if (resultCode == Activity.RESULT_CANCELED) {
            Toast.makeText(this, "Cancelled Added Contact", Toast.LENGTH_SHORT).show();

Setting state on componentDidMount()

According to the React Documentation it's perfectly OK to call setState() from within the componentDidMount() function.

It will cause render() to be called twice, which is less efficient than only calling it once, but other than that it's perfectly fine.

You can find the documentation here:

Here is the excerpt from the documentation:

You may call setState() immediately in componentDidMount(). It will trigger an extra rendering, but it will happen before the browser updates the screen. This guarantees that even though the render() will be called twice in this case, the user won’t see the intermediate state. Use this pattern with caution because it often causes performance issues...

pythonic way to do something N times without an index variable?

Assume that you've defined do_something as a function, and you'd like to perform it N times. Maybe you can try the following:

todos = [do_something] * N  
for doit in todos:  

How can I disable notices and warnings in PHP within the .htaccess file?

If you are in a shared hosting plan that doesn't have PHP installed as a module you will get a 500 server error when adding those flags to the .htaccess file.

But you can add the line


on top of your .php file and it should work without any errors.

Specifying java version in maven - differences between properties and compiler plugin

Consider the alternative:


It should be the same thing of maven.compiler.source/ but the above solution works for me, otherwise the second one gets the parent specification (I have a matrioska of .pom)

Unit Tests not discovered in Visual Studio 2017

I had trouble with VS 2017 finding my UnitTest as well. It wasn't the exact problem John was asking - but this was the first result in google that I came looking for so I wanted to share my issue.

I had a legacy solution coming back from VS2010 going over VS2013, VS2015. Now in VS2017 it seems namespaces for the [TestMethod] Attribute have changed.

Before it was using

Microsoft.VisualStudio.QualityTools.UnitTestFramework, Version=

I created a new Test.dll in the project and that one used by default

Microsoft.VisualStudio.TestPlatform.TestFramework, Version=

So my solution was to create a new UnitTest project from within VS2017. Maybe changing assembly references for the old test project would have worked as well. With the new reference VS2017 did discover those unit tests.

What is an efficient way to implement a singleton pattern in Java?

Depending on the usage, there are several "correct" answers.

Since Java 5, the best way to do it is to use an enum:

public enum Foo {

Pre Java 5, the most simple case is:

public final class Foo {

    private static final Foo INSTANCE = new Foo();

    private Foo() {
        if (INSTANCE != null) {
            throw new IllegalStateException("Already instantiated");

    public static Foo getInstance() {
        return INSTANCE;

    public Object clone() throws CloneNotSupportedException{
        throw new CloneNotSupportedException("Cannot clone instance of this class");

Let's go over the code. First, you want the class to be final. In this case, I've used the final keyword to let the users know it is final. Then you need to make the constructor private to prevent users to create their own Foo. Throwing an exception from the constructor prevents users to use reflection to create a second Foo. Then you create a private static final Foo field to hold the only instance, and a public static Foo getInstance() method to return it. The Java specification makes sure that the constructor is only called when the class is first used.

When you have a very large object or heavy construction code and also have other accessible static methods or fields that might be used before an instance is needed, then and only then you need to use lazy initialization.

You can use a private static class to load the instance. The code would then look like:

public final class Foo {

    private static class FooLoader {
        private static final Foo INSTANCE = new Foo();

    private Foo() {
        if (FooLoader.INSTANCE != null) {
            throw new IllegalStateException("Already instantiated");

    public static Foo getInstance() {
        return FooLoader.INSTANCE;

Since the line private static final Foo INSTANCE = new Foo(); is only executed when the class FooLoader is actually used, this takes care of the lazy instantiation, and is it guaranteed to be thread safe.

When you also want to be able to serialize your object you need to make sure that deserialization won't create a copy.

public final class Foo implements Serializable {

    private static final long serialVersionUID = 1L;

    private static class FooLoader {
        private static final Foo INSTANCE = new Foo();

    private Foo() {
        if (FooLoader.INSTANCE != null) {
            throw new IllegalStateException("Already instantiated");

    public static Foo getInstance() {
        return FooLoader.INSTANCE;

    private Foo readResolve() {
        return FooLoader.INSTANCE;

The method readResolve() will make sure the only instance will be returned, even when the object was serialized in a previous run of your program.

Spring Boot value not populating

follow these steps. 1:- create your configuration class like below you can see

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.beans.factory.annotation.Value;

public class YourConfiguration{

    // passing the key which you set in
    private String somePro;

   // getting the value from that key which you set in
    public String getsomePro() {
        return somePro;

2:- when you have a configuration class then inject in the variable from a configuration where you need.

public class YourService {

    private String getsomePro;

    // now you have a value in getsomePro variable automatically.

Display only 10 characters of a long string?

Although this won't limit the string to exactly 10 characters, why not let the browser do the work for you with CSS:

.no-overflow {
    white-space: no-wrap;
    text-overflow: ellipsis;
    overflow: hidden;

and then for the table cell that contains the string add the above class and set the maximum permitted width. The result should end up looking better than anything done based on measuring the string length.

Creating a chart in Excel that ignores #N/A or blank cells

This is what I found as I was plotting only 3 cells from each 4 columns lumped together. My chart has a merged cell with the date which is my x axis. The problem: BC26-BE27 are plotting as ZERO on my chart. enter image description here

I click on the filter on the side of the chart and found where it is showing all the columns for which the data points are charted. I unchecked the boxes that do not have values. enter image description here

It worked for me.

new Date() is working in Chrome but not Firefox

Simple Solution, This works with All Browsers,

var StringDate = "24-11-2017"   
var DateVar = StringDate.split("-");
var DateVal = new Date(DateVar[1] + "/" + DateVar[0] + "/" + DateVar[2]);

C++ - Assigning null to a std::string

Literal 0 is of type int and you can't assign int to std::string. Use mValue.clear() or assign an empty string mValue="".

how can I copy a conditional formatting in Excel 2010 to other cells, which is based on a other cells content?

condition: =K21+$F22

That is not a CONDITION. That is a VALUE. A CONDITION, evaluates as a BOOLEAN value (True/False) If True, then the format is applied.

This would be a CONDITION, for instance

condition: =K21+$F22>0

In general, when applying a CF to a range,

1) select the entire range that you want the Conditional FORMAT to be applied to.

2) enter the CONDITION, as it relates to the FIRST ROW of your selection.

The CF accordingly will be applied thru the range.

What browsers support HTML5 WebSocket API?

Client side

  • Hixie-75:
    • Chrome 4.0 + 5.0
    • Safari 5.0.0
  • HyBi-00/Hixie-76:
  • HyBi-07+:
  • HyBi-10:
    • Chrome 14.0 + 15.0
    • Firefox 7.0 + 8.0 + 9.0 + 10.0 - prefixed: MozWebSocket
    • IE 10 (from Windows 8 developer preview)
  • HyBi-17/RFC 6455
    • Chrome 16
    • Firefox 11
    • Opera 12.10 / Opera Mobile 12.1

Any browser with Flash can support WebSocket using the web-socket-js shim/polyfill.

See caniuse for the current status of WebSockets support in desktop and mobile browsers.

See the test reports from the WS testsuite included in Autobahn WebSockets for feature/protocol conformance tests.

Server side

It depends on which language you use.

In Java/Java EE:

Some other Java implementations:

In C#:


In Python:

In C:

In Node.js:

  • : also has serverside ports for Python, Java, Google GO, Rack
  • sockjs : sockjs also has serverside ports for Python, Java, Erlang and Lua
  • WebSocket-Node - Pure JavaScript Client & Server implementation of HyBi-10.

Vert.x (also known as Node.x) : A node like polyglot implementation running on a Java 7 JVM and based on Netty with :

  • Support for Ruby(JRuby), Java, Groovy, Javascript(Rhino/Nashorn), Scala, ...
  • True threading. (unlike Node.js)
  • Understands multiple network protocols out of the box including: TCP, SSL, UDP, HTTP, HTTPS, Websockets, SockJS as fallback for WebSockets is a Websocket cloud service accessible through a REST API.

DotCloud cloud platform supports Websockets, and Java (Jetty Servlet Container), NodeJS, Python, Ruby, PHP and Perl programming languages.

Openshift cloud platform supports websockets, and Java (Jboss, Spring, Tomcat & Vertx), PHP (ZendServer & CodeIgniter), Ruby (ROR), Node.js, Python (Django & Flask) plateforms.

For other language implementations, see the Wikipedia article for more information.

The RFC for Websockets : RFC6455

Does adding a duplicate value to a HashSet/HashMap replace the previous value

Correct me if I'm wrong but what you're getting at is that with strings, "Hi" == "Hi" doesn't always come out true (because they're not necessarily the same object).

The reason you're getting an answer of 1 though is because the JVM will reuse strings objects where possible. In this case the JVM is reusing the string object, and thus overwriting the item in the Hashmap/Hashset.

But you aren't guaranteed this behavior (because it could be a different string object that has the same value "Hi"). The behavior you see is just because of the JVM's optimization.

mySQL convert varchar to date

As gratitude to the timely help I got from here - a minor update to above.

$query = "UPDATE `db`.`table` SET `fieldname`=  str_to_date(  fieldname, '%d/%m/%Y')";

In MS DOS copying several files to one file

filenames must sort correctly to combine correctly!

file1.bin file2.bin ... file10.bin wont work properly

file01.bin file02.bin ... file10.bin will work properly

c:>for %i in (file*.bin) do type %i >> onebinary.bin

Works for ascii or binary files.

XXHDPI and XXXHDPI dimensions in dp for images and icons in android

it is different for different icons.(eg, diff sizes for action bar icons, laucnher icons, etc.) please follow this link icons handbook to learn more.

How to disable action bar permanently

Below are the steps for hiding the action bar permanently:

  1. Open app/res/values/styles.xml.
  2. Look for the style element that is named "apptheme". Should look similar to <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">.
  3. Now replace the parent with any other theme that contains "NoActionBar" in its name.

    a. You can also check how a theme looks by switching to the design tab of activity_main.xml and then trying out each theme provided in the theme drop-down list of the UI.

  4. If your MainActivity extends AppCompatActivity, make sure you use an AppCompat theme.

JavaScript: function returning an object

I would take those directions to mean:

  function makeGamePlayer(name,totalScore,gamesPlayed) {
        //should return an object with three keys:
        // name
        // totalScore
        // gamesPlayed

         var obj = {  //note you don't use = in an object definition
             "name": name,
             "totalScore": totalScore,
             "gamesPlayed": gamesPlayed
         return obj;

no sqljdbc_auth in java.library.path

I've just encountered the same problem but within my own application. I didn't like the solution with copying the dll since it's not very convenient so I did some research and came up with the following programmatic solution.

Basically, before doing any connections to SQL server, you have to add the sqljdbc_auth.dll to path.. which is easy to say:


once you know how to do it:

import java.lang.reflect.Field;

public class PathHelper {
    public static void appendToPath(String dir){

        String path = System.getProperty("java.library.path");
        path = dir + ";" + path;
        System.setProperty("java.library.path", path);

        try {

            final Field sysPathsField = ClassLoader.class.getDeclaredField("sys_paths");
            sysPathsField.set(null, null);

        catch (Exception ex){
            throw new RuntimeException(ex);



Now integration authentication works like a charm :).

Credits to for letting me figure this out.

JsonParseException: Unrecognized token 'http': was expecting ('true', 'false' or 'null')

It might be obvious, but make sure that you are sending to the parser URL object not a String containing www adress. This will not work:

    ObjectMapper mapper = new ObjectMapper();
    String www = "";
    Weather weather = mapper.readValue(www, Weather.class);

But this will:

    ObjectMapper mapper = new ObjectMapper();
    URL www = new URL("");
    Weather weather = mapper.readValue(www, Weather.class);

ReferenceError: event is not defined error in Firefox

You're declaring (some of) your event handlers incorrectly:

$('.menuOption').click(function( event ){ // <---- "event" parameter here

    var categories = $(this).attr('rel');


You need "event" to be a parameter to the handlers. WebKit follows IE's old behavior of using a global symbol for "event", but Firefox doesn't. When you're using jQuery, that library normalizes the behavior and ensures that your event handlers are passed the event parameter.

edit — to clarify: you have to provide some parameter name; using event makes it clear what you intend, but you can call it e or cupcake or anything else.

Note also that the reason you probably should use the parameter passed in from jQuery instead of the "native" one (in Chrome and IE and Safari) is that that one (the parameter) is a jQuery wrapper around the native event object. The wrapper is what normalizes the event behavior across browsers. If you use the global version, you don't get that.

InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately

If you are not able to upgrade your Python version to 2.7.9, and want to suppress warnings,

you can downgrade your 'requests' version to 2.5.3:

pip install requests==2.5.3

Bugfix disclosure / Warning introduced in 2.6.0

img tag displays wrong orientation

It happens since original orientation of image is not as we see in image viewer. In such cases image is displayed vertical to us in image viewer but it is horizontal in actual.

To resolve this do following:

  1. Open image in image editor like paint ( in windows ) or ImageMagick ( in linux).

  2. Rotate image left/right.

  3. Save the image.

This should resolve the issue permanently.

Changing Vim indentation behavior by file type

I usually work with expandtab set, but that's bad for makefiles. I recently added:

:autocmd FileType make set noexpandtab

to the end of my .vimrc file and it recognizes Makefile, makefile, and *.mk as makefiles and does not expand tabs. Presumably, you can extend this.

How to get JSON response from http.Get

You need upper case property names in your structs in order to be used by the json packages.

Upper case property names are exported properties. Lower case property names are not exported.

You also need to pass the your data object by reference (&data).

package main

import "os"
import "fmt"
import "net/http"
import "io/ioutil"
import "encoding/json"

type tracks struct {
    Toptracks []toptracks_info

type toptracks_info struct {
    Track []track_info
    Attr  []attr_info

type track_info struct {
    Name       string
    Duration   string
    Listeners  string
    Mbid       string
    Url        string
    Streamable []streamable_info
    Artist     []artist_info
    Attr       []track_attr_info

type attr_info struct {
    Country    string
    Page       string
    PerPage    string
    TotalPages string
    Total      string

type streamable_info struct {
    Text      string
    Fulltrack string

type artist_info struct {
    Name string
    Mbid string
    Url  string

type track_attr_info struct {
    Rank string

func get_content() {
    // json data
    url := ""

    res, err := http.Get(url)

    if err != nil {

    body, err := ioutil.ReadAll(res.Body)

    if err != nil {

    var data tracks
    json.Unmarshal(body, &data)
    fmt.Printf("Results: %v\n", data)

func main() {

IntelliJ Organize Imports

ALT+ENTER was far from eclipse habit ,in IDEA for me mouse over did not work , so in setting>IDESetting>Keymap>Show intention actions and quick-fixes I changed it to mouse left click , It did not support mouse over! but mouse left click was OK and closest to my intention.

Non-static variable cannot be referenced from a static context

Before you call an instance method or instance variable It needs a object(Instance). When instance variable is called from static method compiler doesn't know which is the object this variable belongs to. Because static methods doesn't have an object (Only one copy always). When you call an instance variable or instance methods from instance method it refer the this object. It means the variable belongs to whatever object created and each object have it's own copy of instance methods and variables.

Static variables are marked as static and instance variables doesn't have specific keyword.

Stop and Start a service via batch or cmd file?

I just used Jonas' example above and created full list of 0 to 24 errorlevels. Other post is correct that net start and net stop only use errorlevel 0 for success and 2 for failure.

But this is what worked for me:

net stop postgresql-9.1
if %errorlevel% == 2 echo Access Denied - Could not stop service
if %errorlevel% == 0 echo Service stopped successfully
echo Errorlevel: %errorlevel%

Change stop to start and works in reverse.

Convert seconds to hh:mm:ss in Python

You can calculate the number of minutes and hours from the number of seconds by simple division:

seconds = 12345
minutes = seconds // 60
hours = minutes // 60

print "%02d:%02d:%02d" % (hours, minutes % 60, seconds % 60)
print "%02d:%02d" % (minutes, seconds % 60)

Here // is Python's integer division.

Ping a site in Python?

See this pure Python ping by Matthew Dixon Cowles and Jens Diemer. Also, remember that Python requires root to spawn ICMP (i.e. ping) sockets in linux.

import ping, socket
    ping.verbose_ping('', count=3)
    delay = ping.Ping('', timeout=2000).do()
except socket.error, e:
    print "Ping Error:", e

The source code itself is easy to read, see the implementations of verbose_ping and of for inspiration.

Difference between scaling horizontally and vertically for databases

Yes scaling horizontally means adding more machines, but it also implies that the machines are equal in the cluster. MySQL can scale horizontally in terms of Reading data, through the use of replicas, but once it reaches capacity of the server mem/disk, you have to begin sharding data across servers. This becomes increasingly more complex. Often keeping data consistent across replicas is a problem as replication rates are often too slow to keep up with data change rates.

Couchbase is also a fantastic NoSQL Horizontal Scaling database, used in many commercial high availability applications and games and arguably the highest performer in the category. It partitions data automatically across cluster, adding nodes is simple, and you can use commodity hardware, cheaper vm instances (using Large instead of High Mem, High Disk machines at AWS for instance). It is built off the Membase (Memcached) but adds persistence. Also, in the case of Couchbase, every node can do reads and writes, and are equals in the cluster, with only failover replication (not full dataset replication across all servers like in mySQL).

Performance-wise, you can see an excellent Cisco benchmark:

Here is a great blog post about Couchbase Architecture:

What does the 'u' symbol mean in front of string values?

This is a feature, not a bug.

See, specifically the 'unicode type' section.

PHP cURL vs file_get_contents

In addition to this, due to some recent website hacks we had to secure our sites more. In doing so, we discovered that file_get_contents failed to work, where curl still would work.

Not 100%, but I believe that this php.ini setting may have been blocking the file_get_contents request.

; Disable allow_url_fopen for security reasons
allow_url_fopen = 0

Either way, our code now works with curl.

Can You Get A Users Local LAN IP Address Via JavaScript?

I cleaned up mido's post and then cleaned up the function that they found. This will either return false or an array. When testing remember that you need to collapse the array in the web developer console otherwise it's nonintuitive default behavior may deceive you in to thinking that it is returning an empty array.

function ip_local()
 var ip = false;
 window.RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection || false;

 if (window.RTCPeerConnection)
  ip = [];
  var pc = new RTCPeerConnection({iceServers:[]}), noop = function(){};
  pc.createOffer(pc.setLocalDescription.bind(pc), noop);

  pc.onicecandidate = function(event)
   if (event && event.candidate && event.candidate.candidate)
    var s = event.candidate.candidate.split('\n');
    ip.push(s[0].split(' ')[4]);

 return ip;

Additionally please keep in mind folks that this isn't something old-new like CSS border-radius though one of those bits that is outright not supported by IE11 and older. Always use object detection, test in reasonably older browsers (e.g. Firefox 4, IE9, Opera 12.1) and make sure your newer scripts aren't breaking your newer bits of code. Additionally always detect standards compliant code first so if there is something with say a CSS prefix detect the standard non-prefixed code first and then fall back as in the long term support will eventually be standardized for the rest of it's existence.

Print a file, skipping the first X lines, in Bash

A less verbose version with AWK:

awk 'NR > 1e6' myfile.txt

But I would recommend using integer numbers.

How can I run Tensorboard on a remote server?

You can port-forward with another ssh command that need not be tied to how you are connecting to the server (as an alternative to the other answer). Thus, the ordering of the below steps is arbitrary.

  1. from your local machine, run

    ssh -N -f -L localhost:16006:localhost:6006 <user@remote>

  2. on the remote machine, run:

    tensorboard --logdir <path> --port 6006

  3. Then, navigate to (in this example) http://localhost:16006 on your local machine.

(explanation of ssh command:

-N : no remote commands

-f : put ssh in the background

-L <machine1>:<portA>:<machine2>:<portB> :

forward <machine1>:<portA> (local scope) to <machine2>:<portB> (remote scope)

apply drop shadow to border-top only?

I find using these interactive tools help visualize what's happening, and whats possible

Edit: Check out the other tools for experimenting with the other generators and combinations. I have to remind myself sometimes that just because you can, doesn't mean you should - its easy to get carried away! has key method?

JObject implements IDictionary<string, JToken>, so you can use:

IDictionary<string, JToken> dictionary = x;
if (dictionary.ContainsKey("error_msg"))

... or you could use TryGetValue. It implements both methods using explicit interface implementation, so you can't use them without first converting to IDictionary<string, JToken> though.

What are all the common ways to read a file in Ruby?

I usually do this:

open(path_in_string, &:read)

This will give you the whole text as a string object. It works only under Ruby 1.9.

Finding all possible combinations of numbers to reach a given sum

PHP Version, as inspired by Keith Beller's C# version.

bala's PHP version did not work for me, because I did not need to group numbers. I wanted a simpler implementation with one target value, and a pool of numbers. This function will also prune any duplicate entries.

 * Calculates a subset sum: finds out which combinations of numbers
 * from the numbers array can be added together to come to the target
 * number.
 * Returns an indexed array with arrays of number combinations.
 * Example: 
 * <pre>
 * $matches = subset_sum(array(5,10,7,3,20), 25);
 * </pre>
 * Returns:
 * <pre>
 * Array
 * (
 *   [0] => Array
 *   (
 *       [0] => 3
 *       [1] => 5
 *       [2] => 7
 *       [3] => 10
 *   )
 *   [1] => Array
 *   (
 *       [0] => 5
 *       [1] => 20
 *   )
 * )
 * </pre>
 * @param number[] $numbers
 * @param number $target
 * @param array $part
 * @return array[number[]]
function subset_sum($numbers, $target, $part=null)
    // we assume that an empty $part variable means this
    // is the top level call.
    $toplevel = false;
    if($part === null) {
        $toplevel = true;
        $part = array();

    $s = 0;
    foreach($part as $x) 
        $s = $s + $x;

    // we have found a match!
    if($s == $target) 
        sort($part); // ensure the numbers are always sorted
        return array(implode('|', $part));

    // gone too far, break off
    if($s >= $target) 
        return null;

    $matches = array();
    $totalNumbers = count($numbers);

    for($i=0; $i < $totalNumbers; $i++) 
        $remaining = array();
        $n = $numbers[$i];

        for($j = $i+1; $j < $totalNumbers; $j++) 
            $remaining[] = $numbers[$j];

        $part_rec = $part;
        $part_rec[] = $n;

        $result = subset_sum($remaining, $target, $part_rec);
            $matches = array_merge($matches, $result);

        return $matches;

    // this is the top level function call: we have to
    // prepare the final result value by stripping any
    // duplicate results.
    $matches = array_unique($matches);
    $result = array();
    foreach($matches as $entry) 
        $result[] = explode('|', $entry);

    return $result;

What is ".NET Core"?

Microsoft recognized the future web open source paradigm and decided to open .NET to other operating systems. .NET Core is a .NET Framework for Mac and Linux. It is a “lightweight” .NET Framework, so some features/libraries are missing.

On Windows, I would still run .NET Framework and Visual Studio 2015. .NET Core is more friendly with the open source world like Node.js, npm, Yeoman, Docker, etc.

You can develop full-fledged web sites and RESTful APIs on Mac or Linux with Visual Studio Code + .NET Core which wasn't possible before. So if you love Mac or Ubuntu and you are a .NET developer then go ahead and set it up.

For Mono vs. .NET Core, Mono was developed as a .NET Framework for Linux which is now acquired by Microsoft (company called Xamarin) and used in mobile development. Eventually, Microsoft may merge/migrate Mono to .NET Core. I would not worry about Mono right now.

What is the difference between .py and .pyc files?

"A program doesn't run any faster when it is read from a ".pyc" or ".pyo" file than when it is read from a ".py" file; the only thing that's faster about ".pyc" or ".pyo" files is the speed with which they are loaded. "

iPhone 6 and 6 Plus Media Queries

You have to target screen size using media query for different screen size.

for iphone:

@media only screen 
    and (min-device-width : 375px) 
    and (max-device-width : 667px) 
    and (orientation : landscape) 
    and (-webkit-min-device-pixel-ratio : 2)
{ }

@media only screen 
    and (min-device-width : 375px) 
    and (max-device-width : 667px) 
    and (orientation : portrait) 
    and (-webkit-min-device-pixel-ratio : 2)
{ }

and for desktop version:

@media only screen (max-width: 1080){


Redirect all output to file using Bash on Linux?

Though not POSIX, bash 4 has the &> operator:

command &> alloutput.txt

Installing OpenCV 2.4.3 in Visual C++ 2010 Express

1. Installing OpenCV 2.4.3

First, get OpenCV 2.4.3 from Its a self-extracting so just double click to start the installation. Install it in a directory, say C:\.

OpenCV self-extractor

Wait until all files get extracted. It will create a new directory C:\opencv which contains OpenCV header files, libraries, code samples, etc.

Now you need to add the directory C:\opencv\build\x86\vc10\bin to your system PATH. This directory contains OpenCV DLLs required for running your code.

Open Control PanelSystemAdvanced system settingsAdvanced Tab → Environment variables...

enter image description here

On the System Variables section, select Path (1), Edit (2), and type C:\opencv\build\x86\vc10\bin; (3), then click Ok.

On some computers, you may need to restart your computer for the system to recognize the environment path variables.

This will completes the OpenCV 2.4.3 installation on your computer.

2. Create a new project and set up Visual C++

Open Visual C++ and select FileNewProject...Visual C++Empty Project. Give a name for your project (e.g: cvtest) and set the project location (e.g: c:\projects).

New project dialog

Click Ok. Visual C++ will create an empty project.

VC++ empty project

Make sure that "Debug" is selected in the solution configuration combobox. Right-click cvtest and select PropertiesVC++ Directories.

Project property dialog

Select Include Directories to add a new entry and type C:\opencv\build\include.

Include directories dialog

Click Ok to close the dialog.

Back to the Property dialog, select Library Directories to add a new entry and type C:\opencv\build\x86\vc10\lib.

Library directories dialog

Click Ok to close the dialog.

Back to the property dialog, select LinkerInputAdditional Dependencies to add new entries. On the popup dialog, type the files below:


Note that the filenames end with "d" (for "debug"). Also note that if you have installed another version of OpenCV (say 2.4.9) these filenames will end with 249d instead of 243d (opencv_core249d.lib..etc).

enter image description here

Click Ok to close the dialog. Click Ok on the project properties dialog to save all settings.


These steps will configure Visual C++ for the "Debug" solution. For "Release" solution (optional), you need to repeat adding the OpenCV directories and in Additional Dependencies section, use:


instead of:


You've done setting up Visual C++, now is the time to write the real code. Right click your project and select AddNew Item...Visual C++C++ File.

Add new source file

Name your file (e.g: loadimg.cpp) and click Ok. Type the code below in the editor:

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

using namespace cv;
using namespace std;

int main()
    Mat im = imread("c:/full/path/to/lena.jpg");
    if (im.empty()) 
        cout << "Cannot load image!" << endl;
        return -1;
    imshow("Image", im);

The code above will load c:\full\path\to\lena.jpg and display the image. You can use any image you like, just make sure the path to the image is correct.

Type F5 to compile the code, and it will display the image in a nice window.

First OpenCV program

And that is your first OpenCV program!

3. Where to go from here?

Now that your OpenCV environment is ready, what's next?

  1. Go to the samples dir → c:\opencv\samples\cpp.
  2. Read and compile some code.
  3. Write your own code.

How to generate .NET 4.0 classes from xsd?

I used xsd.exe in the Windows command prompt.

However, since my xml referenced several online xml's (in my case which references I had to also download those schematics, put them in the same directory as my xsd, and then list those files in the command:

"C:\Program Files (x86)\Microsoft SDKs\Windows\v8.1A\bin\NETFX 4.5.1 Tools\xsd.exe" /classes /language:CS your.xsd xlink.xsd xml.xsd

Excel add one hour

This may help you as well. This is a conditional statement that will fill the cell with a default date if it is empty but will subtract one hour if it is a valid date/time and put it into the cell.


You can also substitute TIME with DATE to add or subtract a date or time.

make script execution to unlimited

Your script could be stopping, not because of the PHP timeout but because of the timeout in the browser you're using to access the script (ie. Firefox, Chrome, etc). Unfortunately there's seldom an easy way to extend this timeout, and in most browsers you simply can't. An option you have here is to access the script over a terminal. For example, on Windows you would make sure the PHP executable is in your path variable and then I think you execute:

C:\path\to\script> php script.php

Or, if you're using the PHP CGI, I think it's:

C:\path\to\script> php-cgi script.php

Plus, you would also set ini_set('max_execution_time', 0); in your script as others have mentioned. When running a PHP script this way, I'm pretty sure you can use buffer flushing to echo out the script's progress to the terminal periodically if you wish. The biggest issue I think with this method is there's really no way of stopping the script once it's started, other than stopping the entire PHP process or service.

Ignoring SSL certificate in Apache HttpClient 4.3

One small addition to the answer by vasekt:

The provided solution with the SocketFactoryRegistry works when using PoolingHttpClientConnectionManager.

However, connections via plain http don't work any longer then. You have to add a PlainConnectionSocketFactory for the http protocol additionally to make them work again:

Registry<ConnectionSocketFactory> socketFactoryRegistry = 
  RegistryBuilder.<ConnectionSocketFactory> create()
  .register("https", sslsf)
  .register("http", new PlainConnectionSocketFactory()).build();

Forbidden You don't have permission to access / on this server

WORKING Method { if there is no problem other than configuration }

By Default Appache is not restricting access from ipv4. (common external ip)

What may restrict is the configurations in 'httpd.conf' (or 'apache2.conf' depending on your apache configuration)


Replace all:

<Directory />
     AllowOverride none
    Require all denied



<Directory />
     AllowOverride none
#    Require all denied


hence removing out all restriction given to Apache

Replace Require local with Require all granted at C:/wamp/www/ directory

<Directory "c:/wamp/www/">
    Options Indexes FollowSymLinks
    AllowOverride all
    Require all granted
#   Require local

How can I remove item from querystring in using c#?


hmemcpy answer was totally for me and thanks to other friends who answered.

I grab the HttpValueCollection using Reflector and wrote the following code

        var hebe = new HttpValueCollection();

        if (!string.IsNullOrEmpty(hebe["Language"]))

        Response.Redirect(Request.Url.AbsolutePath + "?" + hebe );

Displaying output of a remote command with Ansible

Prints pubkey and avoid the changed status by adding changed_when: False to cat task:

- name: Generate SSH keys for vagrant user   
  user: name=vagrant generate_ssh_key=yes ssh_key_bits=2048

- name: Check SSH public key   
  command: /bin/cat $home_directory/.ssh/
  register: cat
  changed_when: False

- name: Print SSH public key
  debug: var=cat.stdout

- name: Wait for user to copy SSH public key   
  pause: prompt="Please add the SSH public key above to your GitHub account"

How to filter array in subdocument with MongoDB

Using aggregate is the right approach, but you need to $unwind the list array before applying the $match so that you can filter individual elements and then use $group to put it back together:

    { $match: {_id: ObjectId("512e28984815cbfcb21646a7")}},
    { $unwind: '$list'},
    { $match: {'list.a': {$gt: 3}}},
    { $group: {_id: '$_id', list: {$push: '$list.a'}}}


  "result": [
      "_id": ObjectId("512e28984815cbfcb21646a7"),
      "list": [
  "ok": 1

MongoDB 3.2 Update

Starting with the 3.2 release, you can use the new $filter aggregation operator to do this more efficiently by only including the list elements you want during a $project:

    { $match: {_id: ObjectId("512e28984815cbfcb21646a7")}},
    { $project: {
        list: {$filter: {
            input: '$list',
            as: 'item',
            cond: {$gt: ['$$item.a', 3]}

In CSS Flexbox, why are there no "justify-items" and "justify-self" properties?

This was asked on the www-style list, and Tab Atkins (spec editor) provided an answer explaining why. I'll elaborate on that a bit here.

To start out, let's initially assume our flex container is single-line (flex-wrap: nowrap). In this case, there's clearly an alignment difference between the main axis and the cross axis -- there are multiple items stacked in the main axis, but only one item stacked in the cross axis. So it makes sense to have a customizeable-per-item "align-self" in the cross axis (since each item is aligned separately, on its own), whereas it doesn't make sense in the main axis (since there, the items are aligned collectively).

For multi-line flexbox, the same logic applies to each "flex line". In a given line, items are aligned individually in the cross axis (since there's only one item per line, in the cross axis), vs. collectively in the main axis.

Here's another way of phrasing it: so, all of the *-self and *-content properties are about how to distribute extra space around things. But the key difference is that the *-self versions are for cases where there's only a single thing in that axis, and the *-content versions are for when there are potentially many things in that axis. The one-thing vs. many-things scenarios are different types of problems, and so they have different types of options available -- for example, the space-around / space-between values make sense for *-content, but not for *-self.

SO: In a flexbox's main axis, there are many things to distribute space around. So a *-content property makes sense there, but not a *-self property.

In contrast, in the cross axis, we have both a *-self and a *-content property. One determines how we'll distribute space around the many flex lines (align-content), whereas the other (align-self) determines how to distribute space around individual flex items in the cross axis, within a given flex line.

(I'm ignoring *-items properties here, since they simply establish defaults for *-self.)

Finish all previous activities

When user click on the logout button then write the following code:

Intent intent = new Intent(this, LoginActivity.class);

And also when after login if you call new activity do not use finish();

No 'Access-Control-Allow-Origin' header is present on the requested resource - Resteasy

Your resource methods won't get hit, so their headers will never get set. The reason is that there is what's called a preflight request before the actual request, which is an OPTIONS request. So the error comes from the fact that the preflight request doesn't produce the necessary headers.

For RESTeasy, you should use CorsFilter. You can see here for some example how to configure it. This filter will handle the preflight request. So you can remove all those headers you have in your resource methods.

See Also:

Datetime current year and month in Python


from datetime import datetime

current_month ='%m') // 02 //This is 0 padded
current_month_text ='%h') // Feb
current_month_text ='%B') // February

current_day ='%d')   // 23 //This is also padded
current_day_text ='%a')  // Fri
current_day_full_text ='%A')  // Friday

current_weekday_day_of_today ='%w') //5  Where 0 is Sunday and 6 is Saturday.

current_year_full ='%Y')  // 2018
current_year_short ='%y')  // 18 without century

current_second='%S') //53
current_minute ='%M') //38
current_hour ='%H') //16 like 4pm
current_hour ='%I') // 04 pm

current_hour_am_pm ='%p') // 4 pm

current_microseconds ='%f') // 623596 Rarely we need.

current_timzone ='%Z') // UTC, EST, CST etc. (empty string if the object is naive).

Reference: 8.1.7. strftime() and strptime() Behavior

Reference: strftime() and strptime() Behavior

The above things are useful for any date parsing, not only now or today. It can be useful for any date parsing.

my_date = "23-02-2018 00:00:00"

datetime.strptime(str(my_date),'%d-%m-%Y %H:%M:%S').strftime('%Y-%m-%d %H:%M:%S+00:00')

datetime.strptime(str(my_date),'%d-%m-%Y %H:%M:%S').strftime('%m')

And so on...

How can I SELECT rows with MAX(Column value), DISTINCT by another column in SQL?

Hope below query will give the desired output:

Select id, home,datetime,player,resource, row_number() over (Partition by home ORDER by datetime desc) as rownum from tablename where rownum=1

When to use IList and when to use List

Microsoft guidelines as checked by FxCop discourage use of List<T> in public APIs - prefer IList<T>.

Incidentally, I now almost always declare one-dimensional arrays as IList<T>, which means I can consistently use the IList<T>.Count property rather than Array.Length. For example:

public interface IMyApi
    IList<int> GetReadOnlyValues();

public class MyApiImplementation : IMyApi
    public IList<int> GetReadOnlyValues()
        List<int> myList = new List<int>();
        ... populate list
        return myList.AsReadOnly();
public class MyMockApiImplementationForUnitTests : IMyApi
    public IList<int> GetReadOnlyValues()
        IList<int> testValues = new int[] { 1, 2, 3 };
        return testValues;

Raise an error manually in T-SQL to jump to BEGIN CATCH block

You're looking for RAISERROR.

From MSDN:

Generates an error message and initiates error processing for the session. RAISERROR can either reference a user-defined message stored in the sys.messages catalog view or build a message dynamically. The message is returned as a server error message to the calling application or to an associated CATCH block of a TRY…CATCH construct.

CodeProject has a good article that also describes in-depth the details of how it works and how to use it.

How do I make a branch point at a specific commit?

git branch -f <branchname> <commit>

I go with Mark Longair's solution and comments and recommend anyone reads those before acting, but I'd suggest the emphasis should be on

git branch -f <branchname> <commit>

Here is a scenario where I have needed to do this.


Develop on the wrong branch and hence need to reset it.

Start Okay

Cleanly develop and release some software.

So far so good

Develop on wrong branch

Mistake: Accidentally stay on the release branch while developing further.

After a mistake

Realize the mistake

"OH NO! I accidentally developed on the release branch." The workspace is maybe cluttered with half changed files that represent work-in-progress and we really don't want to touch and mess with. We'd just like git to flip a few pointers to keep track of the current state and put that release branch back how it should be.

Create a branch for the development that is up to date holding the work committed so far and switch to it.

git branch development
git checkout development 

Changed to another branch

Correct the branch

Now we are in the problem situation and need its solution! Rectify the mistake (of taking the release branch forward with the development) and put the release branch back how it should be.

Correct the release branch to point back to the last real release.

git branch -f release release2

The release branch is now correct again, like this ...


What if I pushed the mistake to a remote?

git push -f <remote> <branch> is well described in another thread, though the word "overwrite" in the title is misleading. Force "git push" to overwrite remote files

Use of *args and **kwargs

Note that *args/**kwargs is part of function-calling syntax, and not really an operator. This has a particular side effect that I ran into, which is that you can't use *args expansion with the print statement, since print is not a function.

This seems reasonable:

def myprint(*args):
    print *args

Unfortunately it doesn't compile (syntax error).

This compiles:

def myprint(*args):
    print args

But prints the arguments as a tuple, which isn't what we want.

This is the solution I settled on:

def myprint(*args):
    for arg in args:
        print arg,

Complex JSON nesting of objects and arrays

Make sure you follow the language definition for JSON. In your second example, the section:


Is invalid since an object must be composed of zero or more key-value pairs "a" : "b", where "b" may be any valid value. Some parsers may automatically interpret { "" } to be { "" : null }, but this is not a clearly defined case.

Also, you are using a nested array of objects [{}] quite a bit. I would only do this if:

  1. There is no good "identifier" string for each object in the array.
  2. There is some clear reason for having an array over a key-value for that entry.

Reset all changes after last commit in git

There are two commands which will work in this situation,

root>git reset --hard HEAD~1

root>git push -f

For more git commands refer this page

How to convert float to int with Java

Use Math.round(value) then after type cast it to integer.

float a = 8.61f;
int b = (int)Math.round(a);

how can select from drop down menu and call javascript function

Greetings if i get you right you need a JavaScript function that doing it

function report(v) {
//To Do
  switch(v) {
    case "daily":
      //Do something
    case "monthly":
      //Do somthing


How do I make a WinForms app go Full Screen

You need to set your window to be topmost.

Hunk #1 FAILED at 1. What's that mean?

In some cases, there is no difference in file versions, but only in indentation, spacing, line ending or line numbers.

To patch despite those differences, it's possible to use the following two arguments :

--ignore-whitespace : It ignores whitespace differences (indentation, etc).

--fuzz 3 : the "--fuzz X" option sets the maximum fuzz factor to lines. This option only applies to context and unified diffs; it ignores up to X lines while looking for the place to install a hunk. Note that a larger fuzz factor increases the odds of making a faulty patch. The default fuzz factor is 2; there is no point to setting it to more than the number of lines of context in the diff, ordinarily 3.

Don't forget to user "--dry-run" : It'll try the patch without applying it.

Example :

patch --verbose --dry-run --ignore-whitespace --fuzz 3 < /path/to/patch.patch

More informations about Fuzz :

How do you implement a re-try-catch?

A simple way to solve the issue would be to wrap the try/catch in a while loop and maintain a count. This way you could prevent an infinite loop by checking a count against some other variable while maintaining a log of your failures. It isn't the most exquisite solution, but it would work.

Get all object attributes in Python?

I use __dict__


class MyObj(object):
  def __init__(self): = 'Chuck Norris' = '+6661'

obj = MyObj()

# Output:  
# {'phone': '+6661', 'name': 'Chuck Norris'}

How to import an Oracle database from dmp file and log file?

How was the database exported?

  • If it was exported using exp and a full schema was exported, then

    1. Create the user:

      create user <username> identified by <password> default tablespace <tablespacename> quota unlimited on <tablespacename>;
    2. Grant the rights:

      grant connect, create session, imp_full_database to <username>;
    3. Start the import with imp:

      imp <username>/<password>@<hostname> file=<filename>.dmp log=<filename>.log full=y;
  • If it was exported using expdp, then start the import with impdp:

    impdp <username>/<password> directory=<directoryname> dumpfile=<filename>.dmp logfile=<filename>.log full=y;

Looking at the error log, it seems you have not specified the directory, so Oracle tries to find the dmp file in the default directory (i.e., E:\app\Vensi\admin\oratest\dpdump\).

Either move the export file to the above path or create a directory object to pointing to the path where the dmp file is present and pass the object name to the impdp command above.

A JNI error has occurred, please check your installation and try again in Eclipse x86 Windows 8.1

In my case, Eclipse was giving me this error but I was getting classnotfoundexception on javax.servlet.http.HttpServletin the logs.

In my case, I was trying to start a spring boot app with exclude module: 'spring-boot-starter-tomcat' in my build.gradle (since I'm deploying on Wildfly).

The solution was to comment this exclude out. The eclipse JNI error was very misleading and I would suggest fixing this.

Failed to connect to mailserver at "localhost" port 25

PHP mail function can send email in 2 scenarios:

a. Try to send email via unix sendmail program At linux it will exec program "sendmail", put all params to sendmail and that all.


b. Connect to mail server (using smtp protocol and host/port/username/pass from php.ini) and try to send email.

If php unable to connect to email server it will give warning (and you see such workning in your logs) To solve it, install smtp server on your local machine or use any available server. How to setup / configure smtp you can find on

What's the Use of '\r' escape sequence?

As amaud576875 said, the \r escape sequence signifies a carriage-return, similar to pressing the Enter key. However, I'm not sure how you get "o world"; you should (and I do) get "my first hello world" and then a new line. Depending on what operating system you're using (I'm using Mac) you might want to use a \n instead of a \r.

How to return multiple values?

You can do something like this:

public class Example
    public String name;
    public String location;

    public String[] getExample()
        String ar[] = new String[2];
        ar[0]= name;
        ar[1] =  location;
        return ar; //returning two values at once

How do I call one constructor from another in Java?

The keyword this can be used to call a constructor from a constructor, when writing several constructor for a class, there are times when you'd like to call one constructor from another to avoid duplicate code.

Bellow is a link that I explain other topic about constructor and getters() and setters() and I used a class with two constructors. I hope the explanations and examples help you.

Setter methods or constructors

"Submit is not a function" error in JavaScript

<form action="product.php" method="post" name="frmProduct" id="frmProduct" enctype="multipart/form-data">

<input id="submit_value" type="button" name="submit_value" value="">


<script type="text/javascript">

document.getElementById("submit_value").onclick = submitAction;

function submitAction()
    return false;

EDIT: I accidentally swapped the id's around

Program to find largest and second largest number in array

Try this:

public static void main(String[] args) throws IndexOutOfBoundsException {

    int[] a = { 12, 19, 10, 3, 9, 8 };
    int n = a.length;
    int larg = a[0];
    int larg2 = a[0];

    for (int i = 0; i < n; i++) {
        if (larg < a[i]) {
            larg = a[i];

        if (a[i] > larg2 && larg < a[i]) {
            larg2 = a[i];


    System.out.println("largest " + larg);
    System.out.println("largest2 " + larg2);


Could not get constructor for org.hibernate.persister.entity.SingleTableEntityPersister

I encountered this error when upgrading from jdk10 to jdk11. Adding the following dependency fixed the problem:


How to get all subsets of a set? (powerset)

There is a refinement of powerset:

def powerset(seq):
    Returns all the subsets of this set. This is a generator.
    if len(seq) <= 0:
        yield []
        for item in powerset(seq[1:]):
            yield [seq[0]]+item
            yield item

C# get and set properties for a List Collection

Your setters are strange, which is why you may be seeing a problem.

First, consider whether you even need these setters - if so, they should take a List<string>, not just a string:

    _subHead = value;

These lines:

newSec.subHead.Add("test string");

Are calling the getter and then call Add on the returned List<string> - the setter is not invoked.

What is the difference between POST and GET?

POST and GET are two HTTP request methods. GET is usually intended to retrieve some data, and is expected to be idempotent (repeating the query does not have any side-effects) and can only send limited amounts of parameter data to the server. GET requests are often cached by default by some browsers if you are not careful.

POST is intended for changing the server state. It carries more data, and repeating the query is allowed (and often expected) to have side-effects such as creating two messages instead of one.

GUI Tool for PostgreSQL

Postgres Enterprise Manager from EnterpriseDB is probably the most advanced you'll find. It includes all the features of pgAdmin, plus monitoring of your hosts and database servers, predictive reporting, alerting and a SQL Profiler.

Ninja edit disclaimer/notice: it seems that this user is affiliated with EnterpriseDB, as the linked Postgres Enterprise Manager website contains a video of one Dave Page.

Locate current file in IntelliJ

Do following will select your file automatically all time.

  1. Right click on Project/Packages area > Autoscroll to Source.
  2. Right click on Project/Packages area > Autoscroll from Source.

Please find image below.

enter image description here

Google Maps: how to get country, state/province/region, city given a lat/long value?

I used this question as a starting point for my own solution. Thought it was appropriate to contribute my code back since its smaller than tabacitu's




    var foundLocation = function(city, state, country, lat, lon){
        //do stuff with your location! any of the first 3 args may be null

    var geocoder = new google.maps.Geocoder(); 
        var findResult = function(results, name){
            var result =  _.find(results, function(obj){
                return obj.types[0] == name && obj.types[1] == "political";
            return result ? result.short_name : null;
        geocoder.geocode({'latLng': new google.maps.LatLng(r.coords.latitude, r.coords.longitude)}, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK && results.length) {
                results = results[0].address_components;
                var city = findResult(results, "locality");
                var state = findResult(results, "administrative_area_level_1");
                var country = findResult(results, "country");
                foundLocation(city, state, country, r.coords.latitude, r.coords.longitude);
            } else {
                foundLocation(null, null, null, r.coords.latitude, r.coords.longitude);
    }, { enableHighAccuracy:false, maximumAge: 1000 * 60 * 1 });

How to implement __iter__(self) for a container object (Python)

If your object contains a set of data you want to bind your object's iter to, you can cheat and do this:

>>> class foo:
    def __init__(self, *params):
  = params
    def __iter__(self):
        if hasattr([0], "__iter__"):
>>> d=foo(6,7,3,8, "ads", 6)
>>> for i in d:
    print i

hasNext in Python iterators?

The way I solved my problem is to keep the count of the number of objects iterated over, so far. I wanted to iterate over a set using calls to an instance method. Since I knew the length of the set, and the number of items counted so far, I effectively had an hasNext method.

A simple version of my code:

class Iterator:
    # s is a string, say
    def __init__(self, s):
        self.s = set(list(s))
        self.done = False
        self.iter = iter(s)
        self.charCount = 0

    def next(self):
        if self.done:
            return None
        self.char = next(self.iter)
        self.charCount += 1
        self.done = (self.charCount < len(self.s))
        return self.char

    def hasMore(self):
        return not self.done

Of course, the example is a toy one, but you get the idea. This won't work in cases where there is no way to get the length of the iterable, like a generator etc.

Referencing Row Number in R

These are present by default as rownames when you create a data.frame.

R> df = data.frame('a' = rnorm(10), 'b' = runif(10), 'c' = letters[1:10])
R> df
            a          b c
1   0.3336944 0.39746731 a
2  -0.2334404 0.12242856 b
3   1.4886706 0.07984085 c
4  -1.4853724 0.83163342 d
5   0.7291344 0.10981827 e
6   0.1786753 0.47401690 f
7  -0.9173701 0.73992239 g
8   0.7805941 0.91925413 h
9   0.2469860 0.87979229 i
10  1.2810961 0.53289335 j

and you can access them via the rownames command.

R> rownames(df)
 [1] "1"  "2"  "3"  "4"  "5"  "6"  "7"  "8"  "9"  "10"

if you need them as numbers, simply coerce to numeric by adding as.numeric, as in as.numeric(rownames(df)).

You don't need to add them, as if you know what you are looking for (say item df$c == 'i', you can use the which command:

R> which(df$c =='i')
[1] 9

or if you don't know the column

R> which(df == 'i', arr.ind=T)
     row col
[1,]   9   3

you may access the element using df[9, 'c'], or df$c[9].

If you wanted to add them you could use df$rownumber <- as.numeric(rownames(df)), though this may be less robust than df$rownumber <- 1:nrow(df) as there are cases when you might have assigned to rownames so they will no longer be the default index numbers (the which command will continue to return index numbers even if you do assign to rownames).

Undo a Git merge that hasn't been pushed yet

Just create new branch, then cherry-pick desired commits to it.

Its saver and simpler then resets described in many answers above

Formatting floats without trailing zeros

>>> str(a if a % 1 else int(a))

How to count the number of occurrences of an element in a List

List<String> lst = new ArrayList<String>();


Map<String, Integer> mp = new HashMap<String, Integer>();

for (String string : lst) {

        mp.put(string, mp.get(string)+1);

        mp.put(string, 1);



=mp= {Ram=2, Boss=1, Shiv=1}

How to flatten only some dimensions of a numpy array

An alternative approach is to use numpy.resize() as in:

In [37]: shp = (50,100,25)
In [38]: arr = np.random.random_sample(shp)
In [45]: resized_arr = np.resize(arr, ([:2]), shp[-1]))
In [46]: resized_arr.shape
Out[46]: (5000, 25)

# sanity check with other solutions
In [47]: resized = np.reshape(arr, (-1, shp[-1]))
In [48]: np.allclose(resized_arr, resized)
Out[48]: True

Multiple "style" attributes in a "span" tag: what's supposed to happen?

Separate your rules with a semi colon in a single declaration:

<span style="color:blue;font-style:italic">Test</span>

Are the shift operators (<<, >>) arithmetic or logical in C?

GCC does

  1. for -ve - > Arithmetic Shift

  2. For +ve -> Logical Shift

What are the differences between a multidimensional array and an array of arrays in C#?

Simply put multidimensional arrays are similar to a table in DBMS.
Array of Array (jagged array) lets you have each element hold another array of the same type of variable length.

So, if you are sure that the structure of data looks like a table (fixed rows/columns), you can use a multi-dimensional array. Jagged array are fixed elements & each element can hold an array of variable length

E.g. Psuedocode:

int[,] data = new int[2,2];
data[0,0] = 1;
data[0,1] = 2;
data[1,0] = 3;
data[1,1] = 4;

Think of the above as a 2x2 table:

1 | 2
3 | 4
int[][] jagged = new int[3][]; 
jagged[0] = new int[4] {  1,  2,  3,  4 }; 
jagged[1] = new int[2] { 11, 12 }; 
jagged[2] = new int[3] { 21, 22, 23 }; 

Think of the above as each row having variable number of columns:

 1 |  2 |  3 | 4
11 | 12
21 | 22 | 23

Add params to given URL in Python

Outsource it to the battle tested requests library.

This is how I will do it:

from requests.models import PreparedRequest
url = ''
params = {'lang':'en','tag':'python'}
req = PreparedRequest()
req.prepare_url(url, params)

.autocomplete is not a function Error

when you see this problem always put your autocomplete function in keyup function and ensure you have added the libraries

$( "#searcharea" ).keyup(function(){
   $( "#searcharea" ).autocomplete({
      source: "suggestions.php"

How to make a DIV always float on the screen in top right corner?

Use position: fixed, and anchor it to the top and right sides of the page:

#fixed-div {
    position: fixed;
    top: 1em;
    right: 1em;

IE6 does not support position: fixed, however. If you need this functionality in IE6, this purely-CSS solution seems to do the trick. You'll need a wrapper <div> to contain some of the styles for it to work, as seen in the stylesheet.

What is the use of verbose in Keras while validating the model?

By default verbose = 1,

verbose = 1, which includes both progress bar and one line per epoch

verbose = 0, means silent

verbose = 2, one line per epoch i.e. epoch no./total no. of epochs

Bootstrap button drop-down inside responsive table not visible because of scroll

I have a solution using only CSS, just use position relative for dropdowns inside the table-responsive:

@media (max-width: 767px) {
  .table-responsive .dropdown-menu {
    position: relative; /* Sometimes needs !important */

Excel formula is only showing the formula rather than the value within the cell in Office 2010

Make sure you include the = sign in addition to passing the arguments to the function. I.E.

=SUM(A1:A3) //this would give you the sum of cells A1, A2, and A3.

Getting a list item by index

.NET List data structure is an Array in a "mutable shell".

So you can use indexes for accessing to it's elements like:

var firstElement = myList[0];
var secondElement = myList[1];

Starting with C# 8.0 you can use Index and Range classes for accessing elements. They provides accessing from the end of sequence or just access a specific part of sequence:

var lastElement = myList[^1]; // Using Index
var fiveElements = myList[2..7]; // Using Range, note that 7 is exclusive

You can combine indexes and ranges together:

var elementsFromThirdToEnd = myList[2..^0]; // Index and Range together

Also you can use LINQ ElementAt method but for 99% of cases this is really not necessary and just slow performance solution.

jQuery equivalent of JavaScript's addEventListener method

As of jQuery 1.7, .on() is now the preferred method of binding events, rather than .bind():


As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document. For earlier versions, the .bind() method is used for attaching an event handler directly to elements. Handlers are attached to the currently selected elements in the jQuery object, so those elements must exist at the point the call to .bind() occurs. For more flexible event binding, see the discussion of event delegation in .on() or .delegate().

The documentation page is located at

Eclipse - Installing a new JRE (Java SE 8 1.8.0)

You can have many java versions in your system.

I think you should add the java 8 in yours JREs installed or edit.

Take a look my screen:

enter image description here

If you click in edit (check your java 8 path):

enter image description here

Node.js Mongoose.js string to ObjectId function

You can use this also

const { ObjectId } = require('mongodb');
const _id = ObjectId("4eb6e7e7e9b7f4194e000001");

it's simplest way to do it

Create a .csv file with values from a Python list

you should use the CSV module for sure , but the chances are , you need to write unicode . For those Who need to write unicode , this is the class from example page , that you can use as a util module:

import csv, codecs, cStringIO

class UTF8Recoder:
    Iterator that reads an encoded stream and reencodes the input to UTF-8
    def __init__(self, f, encoding):
        self.reader = codecs.getreader(encoding)(f)

def __iter__(self):
    return self

def next(self):

class UnicodeReader:
    A CSV reader which will iterate over lines in the CSV file "f",
    which is encoded in the given encoding.

def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
    f = UTF8Recoder(f, encoding)
    self.reader = csv.reader(f, dialect=dialect, **kwds)

def next(self):
    row =
    return [unicode(s, "utf-8") for s in row]

def __iter__(self):
    return self

class UnicodeWriter:
    A CSV writer which will write rows to CSV file "f",
    which is encoded in the given encoding.

def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
    # Redirect output to a queue
    self.queue = cStringIO.StringIO()
    self.writer = csv.writer(self.queue, dialect=dialect, **kwds) = f
    self.encoder = codecs.getincrementalencoder(encoding)()

def writerow(self, row):
    self.writer.writerow([s.encode("utf-8") for s in row])
    # Fetch UTF-8 output from the queue ...
    data = self.queue.getvalue()
    data = data.decode("utf-8")
    # ... and reencode it into the target encoding
    data = self.encoder.encode(data)
    # write to the target stream
    # empty queue

def writerows(self, rows):
    for row in rows:

I'm getting Key error in python

A KeyError generally means the key doesn't exist. So, are you sure the path key exists?

From the official python docs:

exception KeyError

Raised when a mapping (dictionary) key is not found in the set of existing keys.

For example:

>>> mydict = {'a':'1','b':'2'}
>>> mydict['a']
>>> mydict['c']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'c'

So, try to print the content of meta_entry and check whether path exists or not.

>>> mydict = {'a':'1','b':'2'}
>>> print mydict
{'a': '1', 'b': '2'}

Or, you can do:

>>> 'a' in mydict
>>> 'c' in mydict

Failed to execute 'atob' on 'Window'

Here I got the error: Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded.

Because you didn't pass a base64-encoded string. Look at your functions: both download and dataURItoBlob do expect a data URI for some reason; you however are passing a plain html markup string to download in your example.

Not only is HTML invalid as base64, you are calling .split(',')[1] on it which will yield undefined - and "undefined" is not a valid base64-encoded string either.

I don't know, but I read that I need to encode my string to base64

That doesn't make much sense to me. You want to encode it somehow, only to decode it then?

What should I call and how?

Change the interface of your download function back to where it received the filename and text arguments.

Notice that the BlobBuilder does not only support appending whole strings (so you don't need to create those ArrayBuffer things), but also is deprecated in favor of the Blob constructor.

Can I put a name on my saved file?

Yes. Don't use the Blob constructor, but the File constructor.

function download(filename, text) {
    try {
        var file = new File([text], filename, {type:"text/plain"});
    } catch(e) {
        // when File constructor is not supported
        file = new Blob([text], {type:"text/plain"});
    var url  = window.URL.createObjectURL(file);

download('test.html', "<html>" + document.documentElement.innerHTML + "</html>");

See JavaScript blob filename without link on what to do with that object url, just setting the current location to it doesn't work.

How to validate IP address in Python?

From Python 3.4 on, the best way to check if an IPv6 or IPv4 address is correct, is to use the Python Standard Library module ipaddress - IPv4/IPv6 manipulation library s.a. for complete documentation.

Example :

#!/usr/bin/env python

import ipaddress
import sys

    ip = ipaddress.ip_address(sys.argv[1])
    print('%s is a correct IP%s address.' % (ip, ip.version))
except ValueError:
    print('address/netmask is invalid: %s' % sys.argv[1])
    print('Usage : %s  ip' % sys.argv[0])

For other versions: Github, phihag / Philipp Hagemeister,"Python 3.3's ipaddress for older Python versions",

The backport from phihag is available e.g. in Anaconda Python 2.7 & is included in Installer. s.a.

To install with pip:

pip install ipaddress

s.a.: ipaddress 1.0.17, "IPv4/IPv6 manipulation library", "Port of the 3.3+ ipaddress module",

Uninstall all installed gems, in OSX?

You could also build out a new Gemfile and run bundle clean --force. This will remove all other gems that aren't included in the new Gemfile.

Class 'DOMDocument' not found

PHP 7.X Centos 7

I got dependency issues when trying to install module with above suggestions, adding this flag:


Resolved dependencies.


sudo yum --enablerepo=remi-php7X install php-xml


service httpd restart

Ref: Install PHP Modules

Get selected value from combo box in C# WPF

How about these:

string yourstringname = (yourComboBox.SelectedItem as ComboBoxItem).Content.ToString();

How to enable C++11 in Qt Creator?

Add this to your .pro file

QMAKE_CXXFLAGS += -std=c++11


CONFIG += c++11

How do I write a custom init for a UIView subclass in Swift?

The init(frame:) version is the default initializer. You must call it only after initializing your instance variables. If this view is being reconstituted from a Nib then your custom initializer will not be called, and instead the init?(coder:) version will be called. Since Swift now requires an implementation of the required init?(coder:), I have updated the example below and changed the let variable declarations to var and optional. In this case, you would initialize them in awakeFromNib() or at some later time.

class TestView : UIView {
    var s: String?
    var i: Int?
    init(s: String, i: Int) {
        self.s = s
        self.i = i
        super.init(frame: CGRect(x: 0, y: 0, width: 100, height: 100))

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

How to set default Checked in checkbox ReactJS?

To interact with the box you need to update the state for the checkbox once you change it. And to have a default setting you can use defaultChecked.

An example:

<input type="checkbox" defaultChecked={this.state.chkbox} onChange={this.handleChangeChk} />

SelectSingleNode returning null for known good xml node path using XPath

I strongly suspect the problem is to do with namespaces. Try getting rid of the namespace and you'll be fine - but obviously that won't help in your real case, where I'd assume the document is fixed.

I can't remember offhand how to specify a namespace in an XPath expression, but I'm sure that's the problem.

EDIT: Okay, I've remembered how to do it now. It's not terribly pleasant though - you need to create an XmlNamespaceManager for it. Here's some sample code that works with your sample document:

using System;
using System.Xml;

public class Test
    static void Main()
        XmlDocument doc = new XmlDocument();
        XmlNamespaceManager namespaces = new XmlNamespaceManager(doc.NameTable);
        namespaces.AddNamespace("ns", "urn:hl7-org:v3");
        XmlNode idNode = doc.SelectSingleNode("/My_RootNode/ns:id", namespaces);
        string msgID = idNode.Attributes["extension"].Value;

Adding Access-Control-Allow-Origin header response in Laravel 5.3 Passport

You could also use the great laravel-cors package by barryvdh.

After you have the package installed, the easiest way to get CORS support for all your routes is to add the middleware like this in Http/Kernel.php:

protected $middleware = [

If you dont want to have CORS support on all your routes you should make a new OPTIONS route for /oauth/token and add the cors middleware to that route only.

Edit for Laravel 8

Laravel 8 already has CORS Support built in - HandleCors middleware is defined in your global middleware stack by default and can be configured in your application's config/cors.php config file.

If you update your Laravel application be sure to change out barryvdh's package with the supplied middleware: \Fruitcake\Cors\HandleCors::class

Git Bash doesn't see my PATH

For those of you who have tried all the above mentioned methods including Windows system env. variables, .bashrc, .bashprofile, etc. AND can see the correct path in 'echo $PATH' ... I may have a solution for you.

suppress the errors using exec 2> /dev/null

My script runs fine but was throwing 'command not found' or 'No directory found' errors even though, as far as I can tell, the paths were flush. So, if you suppress those errors (might have to also add 'set +e'), than it works properly.

Proper use of mutexes in Python

You have to unlock your Mutex at sometime...

How to use FormData for AJAX file upload?

Better to use the native javascript to find the element by id like: document.getElementById("yourFormElementID").

$.ajax( {
      url: "http://yourlocationtopost/",
      type: 'POST',
      data: new FormData(document.getElementById("yourFormElementID")),
      processData: false,
      contentType: false
    } ).done(function(d) {

Append to string variable

var str1 = "add";
str1 = str1 + " ";

Hope that helps,


Algorithm to return all combinations of k elements from n

Short java solution:

import java.util.Arrays;

public class Combination {
    public static void main(String[] args){
        String[] arr = {"A","B","C","D","E","F"};
        combinations2(arr, 3, 0, new String[3]);

    static void combinations2(String[] arr, int len, int startPosition, String[] result){
        if (len == 0){
        for (int i = startPosition; i <= arr.length-len; i++){
            result[result.length - len] = arr[i];
            combinations2(arr, len-1, i+1, result);

Result will be

[A, B, C]
[A, B, D]
[A, B, E]
[A, B, F]
[A, C, D]
[A, C, E]
[A, C, F]
[A, D, E]
[A, D, F]
[A, E, F]
[B, C, D]
[B, C, E]
[B, C, F]
[B, D, E]
[B, D, F]
[B, E, F]
[C, D, E]
[C, D, F]
[C, E, F]
[D, E, F]

Where is GACUTIL for .net Framework 4.0 in windows 7?

If you've got VS2010 installed, you ought to find a .NET 4.0 gacutil at

C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin\NETFX 4.0 Tools

The 7.0A Windows SDK should have been installed alongside VS2010 - 6.0A will have been installed with VS2008, and hence won't have .NET 4.0 support.

How do I replace text inside a div element?


Convert NSData to String?

A simple way to convert arbitrary NSData to NSString is to base64 encode it.

NSString *base64EncodedKey = [keydata base64EncodedStringWithOptions: NSDataBase64Encoding64CharacterLineLength];

You can then store it into your database for reuse later. Just decode it back to NSData.

Installing Python library from WHL file

First open a console then cd to where you've downloaded your file like some-package.whl and use

pip install some-package.whl

Note: if pip.exe is not recognized, you may find it in the "Scripts" directory from where python has been installed. I have multiple Python installations, and needed to use the pip associated with Python 3 to install a version 3 wheel.

If pip is not installed, and you are using Windows: How to install pip on Windows?

Java constant examples (Create a java file having only constants)

- Create a Class with public static final fields.

- And then you can access these fields from any class using the Class_Name.Field_Name.

- You can declare the class as final, so that the class can't be extended(Inherited) and modify....

Generating a list of pages (not posts) without the index file

I have never used jekyll, but it's main page says that it uses Liquid, and according to their docs, I think the following should work:

<ul> {% for page in site.pages %}     {% if page.title != 'index' %}     <li><div class="drvce"><a href="{{ page.url }}">{{ page.title }}</a></div></li>     {% endif %} {% endfor %} </ul> 

Send password when using scp to copy files from one server to another

// copy /tmp/abc.txt to /tmp/abc.txt (target path)

// username and password of is "username" and "password"

sshpass -p "password" scp /tmp/abc.txt [email protected]:/tmp/abc.txt

// install sshpass (ubuntu)

sudo apt-get install sshpass

Difference between try-catch and throw in java

If you execute the following example, you will know the difference between a Throw and a Catch block.

In general terms:

The catch block will handle the Exception

throws will pass the error to his caller.

In the following example, the error occurs in the throwsMethod() but it is handled in the catchMethod().

public class CatchThrow {

private static void throwsMethod() throws NumberFormatException {
    String  intNumber = "5A";


private static void catchMethod() {
    try {


    } catch (NumberFormatException e) {
        System.out.println("Convertion Error");


public static void main(String[] args) {
    // TODO Auto-generated method stub



Is there any pythonic way to combine two dicts (adding values for keys that appear in both)?

>>> A = {'a':1, 'b':2, 'c':3}
>>> B = {'b':3, 'c':4, 'd':5}
>>> c = {x: A.get(x, 0) + B.get(x, 0) for x in set(A).union(B)}
>>> print(c)

{'a': 1, 'c': 7, 'b': 5, 'd': 5}

Convert A String (like testing123) To Binary In Java

While playing around with the answers I found here to become familiar with it I twisted Nuoji's solution a bit so that I could understand it faster when looking at it in the future.

public static String stringToBinary(String str, boolean pad ) {
    byte[] bytes = str.getBytes();
    StringBuilder binary = new StringBuilder();
    for (byte b : bytes)
       binary.append(Integer.toBinaryString((int) b));
       if(pad) { binary.append(' '); }
    return binary.toString();        

Java Thread Example?

There is no guarantee that your threads are executing simultaneously regardless of any trivial example anyone else posts. If your OS only gives the java process one processor to work on, your java threads will still be scheduled for each time slice in a round robin fashion. Meaning, no two will ever be executing simultaneously, but the work they do will be interleaved. You can use monitoring tools like Java's Visual VM (standard in the JDK) to observe the threads executing in a Java process.

Setting the default ssh key location

man ssh gives me this options would could be useful.

-i identity_file Selects a file from which the identity (private key) for RSA or DSA authentication is read. The default is ~/.ssh/identity for protocol version 1, and ~/.ssh/id_rsa and ~/.ssh/id_dsa for pro- tocol version 2. Identity files may also be specified on a per- host basis in the configuration file. It is possible to have multiple -i options (and multiple identities specified in config- uration files).

So you could create an alias in your bash config with something like

alias ssh="ssh -i /path/to/private_key"

I haven't looked into a ssh configuration file, but like the -i option this too could be aliased

-F configfile Specifies an alternative per-user configuration file. If a configuration file is given on the command line, the system-wide configuration file (/etc/ssh/ssh_config) will be ignored. The default for the per-user configuration file is ~/.ssh/config.

How to get Top 5 records in SqLite?

select * from [Table_Name] limit 5

How to use IntelliJ IDEA to find all unused code?

In latest IntelliJ versions, you should run it from Analyze->Run Inspection By Name:

enter image description here

Than, pick Unused declaration:

enter image description here

And finally, uncheck the Include test sources:

enter image description here

How to declare a global variable in a .js file

Just define your variables in global.js outside a function scope:

// global.js
var global1 = "I'm a global!";
var global2 = "So am I!";

// other js-file
function testGlobal () {

To make sure that this works you have to include/link to global.js before you try to access any variables defined in that file:

        <!-- Include global.js first -->
        <script src="/YOUR_PATH/global.js" type="text/javascript"></script>
        <!-- Now we can reference variables, objects, functions etc. 
             defined in global.js -->
        <script src="/YOUR_PATH/otherJsFile.js" type="text/javascript"></script>

You could, of course, link in the script tags just before the closing <body>-tag if you do not want the load of js-files to interrupt the initial page load.

Adding a Scrollable JTextArea (Java)

  1. Open design view
  2. Right click to textArea
  3. open surround with option
  4. select "...JScrollPane".

Bind TextBox on Enter-key press

Answered here quite elegantly using attached behaviors, my preferred method for almost anything.

WPF how to make textbox lose focus after hitting enter

Download a working local copy of a webpage

wget is capable of doing what you are asking. Just try the following:

wget -p -k

The -p will get you all the required elements to view the site correctly (css, images, etc). The -k will change all links (to include those for CSS & images) to allow you to view the page offline as it appeared online.

From the Wget docs:

After the download is complete, convert the links in the document to make them
suitable for local viewing. This affects not only the visible hyperlinks, but
any part of the document that links to external content, such as embedded images,
links to style sheets, hyperlinks to non-html content, etc.

Each link will be changed in one of the two ways:

    The links to files that have been downloaded by Wget will be changed to refer
    to the file they point to as a relative link.

    Example: if the downloaded file /foo/doc.html links to /bar/img.gif, also
    downloaded, then the link in doc.html will be modified to point to
    ‘../bar/img.gif’. This kind of transformation works reliably for arbitrary
    combinations of directories.

    The links to files that have not been downloaded by Wget will be changed to
    include host name and absolute path of the location they point to.

    Example: if the downloaded file /foo/doc.html links to /bar/img.gif (or to
    ../bar/img.gif), then the link in doc.html will be modified to point to

Because of this, local browsing works reliably: if a linked file was downloaded,
the link will refer to its local name; if it was not downloaded, the link will
refer to its full Internet address rather than presenting a broken link. The fact
that the former links are converted to relative links ensures that you can move
the downloaded hierarchy to another directory.

Note that only at the end of the download can Wget know which links have been
downloaded. Because of that, the work done by ‘-k’ will be performed at the end
of all the downloads. 

Converting an int or String to a char array on Arduino

Just as a reference, here is an example of how to convert between String and char[] with a dynamic length -

// Define 
String str = "This is my string"; 

// Length (with one extra character for the null terminator)
int str_len = str.length() + 1; 

// Prepare the character array (the buffer) 
char char_array[str_len];

// Copy it over 
str.toCharArray(char_array, str_len);

Yes, this is painfully obtuse for something as simple as a type conversion, but sadly it's the easiest way.

How to put data containing double-quotes in string variable?

You can escape (this is how this principle is called) the double quotes by prefixing them with another double quote. You can put them in a string as follows:

Dim MyVar as string = "some text ""hello"" "

This will give the MyVar variable a value of some text "hello".

'invalid value encountered in double_scalars' warning, possibly numpy

I encount this while I was calculating np.var(np.array([])). np.var will divide size of the array which is zero in this case.

Return outside function error in Python

You are not writing your code inside any function, you can return from functions only. Remove return statement and just print the value you want.

How to sort a HashSet?

Use java.util.TreeSet as the actual object. When you iterate over this collection, the values come back in a well-defined order.

If you use java.util.HashSet then the order depends on an internal hash function which is almost certainly not lexicographic (based on content).

Convert this string to datetime

The Problem is with your code formatting,

inorder to use strtotime() You should replace '06/Oct/2011:19:00:02' with 06/10/2011 19:00:02 and date('d/M/Y:H:i:s', $date); with date('d/M/Y H:i:s', $date);. Note the spaces in between.

So the final code looks like this

$s = '06/10/2011 19:00:02';
$date = strtotime($s);
echo date('d/M/Y H:i:s', $date);

How to receive serial data using android bluetooth

The issue with the null connection is related to the findBT() function. you must change the device name from "MattsBlueTooth" to your device name as well as confirm the UUID for your service/device. Use something like BLEScanner app to confrim both on Android.

how to make a whole row in a table clickable as a link?

I know someone has written pretty much the same already, however my way is the correct way (div cannot be child of A) and also it's better to use classes.

You can imitate a table using CSS and make an A element the row

<div class="table" style="width:100%;">
  <a href="#" class="tr">
    <span class="td">
      cell 1
    <span class="td">
      cell 2



Find which rows have different values for a given column in Teradata SQL

This works for PL/SQL:

select count(*), id,address from table group by id,address having count(*)<2

How to remove hashbang from url?

const router = new VueRouter({
  mode: 'history',
  routes: [...]

And if you are using AWS amplify, check this article on how to configure server: Vue router’s history mode and AWS Amplify