Programs & Examples On #Delete operator

Meaning of = delete after function declaration

Are there any other "modifiers" (other than = 0 and = delete)?

Since it appears no one else answered this question, I should mention that there is also =default.

https://docs.microsoft.com/en-us/cpp/cpp/explicitly-defaulted-and-deleted-functions#explicitly-defaulted-functions

Does delete on a pointer to a subclass call the base class destructor?

When you call delete on a pointer allocated by new, the destructor of the object pointed to will be called.

A * p = new A;

delete p;    // A:~A() called for you on obkect pointed to by p

How does delete[] know it's an array?

just define a destructor inside a class and execute your code with both syntax

delete pointer

delete [] pointer

according to the output u can find the solutions

Is "delete this" allowed in C++?

The C++ FAQ Lite has a entry specifically for this

I think this quote sums it up nicely

As long as you're careful, it's OK for an object to commit suicide (delete this).

Deleting a pointer in C++

1 & 2

myVar = 8; //not dynamically allocated. Can't call delete on it.
myPointer = new int; //dynamically allocated, can call delete on it.

The first variable was allocated on the stack. You can call delete only on memory you allocated dynamically (on the heap) using the new operator.

3.

  myPointer = NULL;
  delete myPointer;

The above did nothing at all. You didn't free anything, as the pointer pointed at NULL.


The following shouldn't be done:

myPointer = new int;
myPointer = NULL; //leaked memory, no pointer to above int
delete myPointer; //no point at all

You pointed it at NULL, leaving behind leaked memory (the new int you allocated). You should free the memory you were pointing at. There is no way to access that allocated new int anymore, hence memory leak.


The correct way:

myPointer = new int;
delete myPointer; //freed memory
myPointer = NULL; //pointed dangling ptr to NULL

The better way:

If you're using C++, do not use raw pointers. Use smart pointers instead which can handle these things for you with little overhead. C++11 comes with several.

delete vs delete[] operators in C++

When I asked this question, my real question was, "is there a difference between the two? Doesn't the runtime have to keep information about the array size, and so will it not be able to tell which one we mean?" This question does not appear in "related questions", so just to help out those like me, here is the answer to that: "why do we even need the delete[] operator?"

C++ delete vector, objects, free memory

vector::clear() does not free memory allocated by the vector to store objects; it calls destructors for the objects it holds.

For example, if the vector uses an array as a backing store and currently contains 10 elements, then calling clear() will call the destructor of each object in the array, but the backing array will not be deallocated, so there is still sizeof(T) * 10 bytes allocated to the vector (at least). size() will be 0, but size() returns the number of elements in the vector, not necessarily the size of the backing store.

As for your second question, anything you allocate with new you must deallocate with delete. You typically do not maintain a pointer to a vector for this reason. There is rarely (if ever) a good reason to do this and you prevent the vector from being cleaned up when it leaves scope. However, calling clear() will still act the same way regardless of how it was allocated.

C++ Array of pointers: delete or delete []?

You delete each pointer individually, and then you delete the entire array. Make sure you've defined a proper destructor for the classes being stored in the array, otherwise you cannot be sure that the objects are cleaned up properly. Be sure that all your destructors are virtual so that they behave properly when used with inheritance.

Is it safe to delete a NULL pointer?

delete performs the check anyway, so checking it on your side adds overhead and looks uglier. A very good practice is setting the pointer to NULL after delete (helps avoiding double deletion and other similar memory corruption problems).

I'd also love if delete by default was setting the parameter to NULL like in

#define my_delete(x) {delete x; x = NULL;}

(I know about R and L values, but wouldn't it be nice?)

Deleting array elements in JavaScript - delete vs splice

delete will delete the object property, but will not reindex the array or update its length. This makes it appears as if it is undefined:

> myArray = ['a', 'b', 'c', 'd']
  ["a", "b", "c", "d"]
> delete myArray[0]
  true
> myArray[0]
  undefined

Note that it is not in fact set to the value undefined, rather the property is removed from the array, making it appear undefined. The Chrome dev tools make this distinction clear by printing empty when logging the array.

> myArray[0]
  undefined
> myArray
  [empty, "b", "c", "d"]

myArray.splice(start, deleteCount) actually removes the element, reindexes the array, and changes its length.

> myArray = ['a', 'b', 'c', 'd']
  ["a", "b", "c", "d"]
> myArray.splice(0, 2)
  ["a", "b"]
> myArray
  ["c", "d"]

Double free or corruption after queue::push

The problem is that your class contains a managed RAW pointer but does not implement the rule of three (five in C++11). As a result you are getting (expectedly) a double delete because of copying.

If you are learning you should learn how to implement the rule of three (five). But that is not the correct solution to this problem. You should be using standard container objects rather than try to manage your own internal container. The exact container will depend on what you are trying to do but std::vector is a good default (and you can change afterwords if it is not opimal).

#include <queue>
#include <vector>

class Test{
    std::vector<int> myArray;

    public:
    Test(): myArray(10){
    }    
};

int main(){
    queue<Test> q
    Test t;
    q.push(t);
}

The reason you should use a standard container is the separation of concerns. Your class should be concerned with either business logic or resource management (not both). Assuming Test is some class you are using to maintain some state about your program then it is business logic and it should not be doing resource management. If on the other hand Test is supposed to manage an array then you probably need to learn more about what is available inside the standard library.

How to declare a type as nullable in TypeScript?

All fields in JavaScript (and in TypeScript) can have the value null or undefined.

You can make the field optional which is different from nullable.

interface Employee1 {
    name: string;
    salary: number;
}

var a: Employee1 = { name: 'Bob', salary: 40000 }; // OK
var b: Employee1 = { name: 'Bob' }; // Not OK, you must have 'salary'
var c: Employee1 = { name: 'Bob', salary: undefined }; // OK
var d: Employee1 = { name: null, salary: undefined }; // OK

// OK
class SomeEmployeeA implements Employee1 {
    public name = 'Bob';
    public salary = 40000;
}

// Not OK: Must have 'salary'
class SomeEmployeeB implements Employee1 {
    public name: string;
}

Compare with:

interface Employee2 {
    name: string;
    salary?: number;
}

var a: Employee2 = { name: 'Bob', salary: 40000 }; // OK
var b: Employee2 = { name: 'Bob' }; // OK
var c: Employee2 = { name: 'Bob', salary: undefined }; // OK
var d: Employee2 = { name: null, salary: 'bob' }; // Not OK, salary must be a number

// OK, but doesn't make too much sense
class SomeEmployeeA implements Employee2 {
    public name = 'Bob';
}

ASP.NET MVC on IIS 7.5

Yet another reason this can happen - your RouteConfig.cs or WebApiConfig.cs are invalid.

In my case, I had a route defined as such (note the parenthesis instead of curly brace):

...
routeTemplate: "api/(something}"
...

How can I see if a Perl hash already has a certain key?

I guess that this code should answer your question:

use strict;
use warnings;

my @keys = qw/one two three two/;
my %hash;
for my $key (@keys)
{
    $hash{$key}++;
}

for my $key (keys %hash)
{
   print "$key: ", $hash{$key}, "\n";
}

Output:

three: 1
one: 1
two: 2

The iteration can be simplified to:

$hash{$_}++ for (@keys);

(See $_ in perlvar.) And you can even write something like this:

$hash{$_}++ or print "Found new value: $_.\n" for (@keys);

Which reports each key the first time it’s found.

How to generate different random numbers in a loop in C++?

You need to extract the initilization of time() out of the for loop.

Here is an example that will output in the windows console expected (ahah) random number.

#include <iostream>
#include <windows.h>
#include "time.h"
int main(int argc, char*argv[])
{
    srand ( time(NULL) );
    for (int t = 0; t < 10; t++)
    {
        int random_x;

        random_x = rand() % 100;
        std::cout << "\nRandom X = " << random_x << std::endl;
    }
    Sleep(50000);
    return 0;
}

Printing column separated by comma using Awk command line

If your only requirement is to print the third field of every line, with each field delimited by a comma, you can use cut:

cut -d, -f3 file
  • -d, sets the delimiter to a comma
  • -f3 specifies that only the third field is to be printed

How to convert TimeStamp to Date in Java?

Just make a new Date object with the stamp's getTime() value as a parameter.

Here's an example (I use an example timestamp of the current time):

Timestamp stamp = new Timestamp(System.currentTimeMillis());
Date date = new Date(stamp.getTime());
System.out.println(date);

How can I determine if a date is between two dates in Java?

import java.util.Date;

public class IsDateBetween {

public static void main (String[] args) {

          IsDateBetween idb=new IsDateBetween("12/05/2010"); // passing your Date
 }
 public IsDateBetween(String dd) {

       long  from=Date.parse("01/01/2000");  // From some date

       long to=Date.parse("12/12/2010");     // To Some Date

       long check=Date.parse(dd);

       int x=0;

      if((check-from)>0 && (to-check)>0)
      {
             x=1;
      }

 System.out.println ("From Date is greater Than  ToDate : "+x);
}   

}

Setting up connection string in ASP.NET to SQL SERVER

You can also use this, it's simpler. The only thing you need to set is "YourDataBaseName".

  <connectionStrings>
    <add name="ConnStringDb1" connectionString="Data Source=localhost;Initial Catalog=YourDataBaseName;Integrated Security=True;" providerName="System.Data.SqlClient" />
  </connectionStrings>

Where to place the connection string

<?xml version='1.0' encoding='utf-8'?>  
  <configuration>  
    <connectionStrings>  
      <clear />  
      <add name="Name"   
       providerName="System.Data.ProviderName"   
       connectionString="Valid Connection String;" />  
    </connectionStrings>  
  </configuration>  

How to deal with missing src/test/java source folder in Android/Maven project?

Select project -> New -> Folder (not source folder) -> Select the project again -> Enter the folder name as (src/test/java) -> finish. That's it.

If the test source is missing, it would link it automatically. If not, then require to link it manually.

What is the difference between parseInt(string) and Number(string) in JavaScript?

Addendum to @sjngm's answer:

They both also ignore whitespace:

var foo = " 3 "; console.log(parseInt(foo)); // 3 console.log(Number(foo)); // 3

It is not exactly correct. As sjngm wrote parseInt parses string to first number. It is true. But the problem is when you want to parse number separated with whitespace ie. "12 345". In that case
parseInt("12 345") will return 12 instead of 12345. So to avoid that situation you must trim whitespaces before parsing to number. My solution would be:

     var number=parseInt("12 345".replace(/\s+/g, ''),10);

Notice one extra thing I used in parseInt() function. parseInt("string",10) will set the number to decimal format. If you would parse string like "08" you would get 0 because 8 is not a octal number.Explanation is here

How to run DOS/CMD/Command Prompt commands from VB.NET?

You Can try This To Run Command Then cmd Exits

Process.Start("cmd", "/c YourCode")

You Can try This To Run The Command And Let cmd Wait For More Commands

Process.Start("cmd", "/k YourCode")

Javascript Uncaught Reference error Function is not defined

If you are using Angular.js then functions imbedded into HTML, such as onclick="function()" or onchange="function()". They will not register. You need to make the change events in the javascript. Such as:

$('#exampleBtn').click(function() {
  function();
});

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

This can occur when you are showing the dialog for a context that no longer exists. A common case - if the 'show dialog' operation is after an asynchronous operation, and during that operation the original activity (that is to be the parent of your dialog) is destroyed. For a good description, see this blog post and comments:

http://dimitar.me/android-displaying-dialogs-from-background-threads/

From the stack trace above, it appears that the facebook library spins off the auth operation asynchronously, and you have a Handler - Callback mechanism (onComplete called on a listener) that could easily create this scenario.

When I've seen this reported in my app, its pretty rare and matches the experience in the blog post. Something went wrong for the activity/it was destroyed during the work of the the AsyncTask. I don't know how your modification could result in this every time, but perhaps you are referencing an Activity as the context for the dialog that is always destroyed by the time your code executes?

Also, while I'm not sure if this is the best way to tell if your activity is running, see this answer for one method of doing so:

Check whether activity is active

Adding minutes to date time in PHP

$minutes_to_add = 5;

$time = new DateTime('2011-11-17 05:05');
$time->add(new DateInterval('PT' . $minutes_to_add . 'M'));

$stamp = $time->format('Y-m-d H:i');

The ISO 8601 standard for duration is a string in the form of P{y}Y{m1}M{d}DT{h}H{m2}M{s}S where the {*} parts are replaced by a number value indicating how long the duration is.

For example, P1Y2DT5S means 1 year, 2 days, and 5 seconds.

In the example above, we are providing PT5M (or 5 minutes) to the DateInterval constructor.

Using dig to search for SPF records

The dig utility is pretty convenient to use. The order of the arguments don't really matter.I'll show you some easy examples.
To get all root name servers use

# dig

To get a TXT record of a specific host use

# dig example.com txt
# dig host.example.com txt

To query a specific name server just add @nameserver.tld

# dig host.example.com txt @a.iana-servers.net

The SPF RFC4408 says that SPF records can be stored as SPF or TXT. However nearly all use only TXT records at the moment. So you are pretty safe if you only fetch TXT records.

I made a SPF checker for visualising the SPF records of a domain. It might help you to understand SPF records better. You can find it here: http://spf.myisp.ch

Git blame -- prior commits?

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

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

git bh path/to/myfile myWord

Script:

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

jquery getting post action url

Try this ocde;;

var formAction = $("#signup").attr('action');

Java sending and receiving file (byte[]) over sockets

Here is the server Open a stream to the file and send it overnetwork

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class SimpleFileServer {

  public final static int SOCKET_PORT = 5501;
  public final static String FILE_TO_SEND = "file.txt";

  public static void main (String [] args ) throws IOException {
    FileInputStream fis = null;
    BufferedInputStream bis = null;
    OutputStream os = null;
    ServerSocket servsock = null;
    Socket sock = null;
    try {
      servsock = new ServerSocket(SOCKET_PORT);
      while (true) {
        System.out.println("Waiting...");
        try {
          sock = servsock.accept();
          System.out.println("Accepted connection : " + sock);
          // send file
          File myFile = new File (FILE_TO_SEND);
          byte [] mybytearray  = new byte [(int)myFile.length()];
          fis = new FileInputStream(myFile);
          bis = new BufferedInputStream(fis);
          bis.read(mybytearray,0,mybytearray.length);
          os = sock.getOutputStream();
          System.out.println("Sending " + FILE_TO_SEND + "(" + mybytearray.length + " bytes)");
          os.write(mybytearray,0,mybytearray.length);
          os.flush();
          System.out.println("Done.");
        } catch (IOException ex) {
          System.out.println(ex.getMessage()+": An Inbound Connection Was Not Resolved");
        }
        }finally {
          if (bis != null) bis.close();
          if (os != null) os.close();
          if (sock!=null) sock.close();
        }
      }
    }
    finally {
      if (servsock != null)
        servsock.close();
    }
  }
}

Here is the client Recive the file being sent overnetwork

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;

public class SimpleFileClient {

  public final static int SOCKET_PORT = 5501;
  public final static String SERVER = "127.0.0.1";
  public final static String
       FILE_TO_RECEIVED = "file-rec.txt";

  public final static int FILE_SIZE = Integer.MAX_VALUE;

  public static void main (String [] args ) throws IOException {
    int bytesRead;
    int current = 0;
    FileOutputStream fos = null;
    BufferedOutputStream bos = null;
    Socket sock = null;
    try {
      sock = new Socket(SERVER, SOCKET_PORT);
      System.out.println("Connecting...");

      // receive file
      byte [] mybytearray  = new byte [FILE_SIZE];
      InputStream is = sock.getInputStream();
      fos = new FileOutputStream(FILE_TO_RECEIVED);
      bos = new BufferedOutputStream(fos);
      bytesRead = is.read(mybytearray,0,mybytearray.length);
      current = bytesRead;

      do {
         bytesRead =
            is.read(mybytearray, current, (mybytearray.length-current));
         if(bytesRead >= 0) current += bytesRead;
      } while(bytesRead > -1);

      bos.write(mybytearray, 0 , current);
      bos.flush();
      System.out.println("File " + FILE_TO_RECEIVED
          + " downloaded (" + current + " bytes read)");
    }
    finally {
      if (fos != null) fos.close();
      if (bos != null) bos.close();
      if (sock != null) sock.close();
    }
  }    
}

How can I calculate the difference between two dates?

NSTimeInterval diff = [date2 timeIntervalSinceDate:date1]; // in seconds

where date1 and date2 are NSDate's.

Also, note the definition of NSTimeInterval:

typedef double NSTimeInterval;

How to create an empty R vector to add new items

I pre-allocate a vector with

> (a <- rep(NA, 10))
 [1] NA NA NA NA NA NA NA NA NA NA

You can then use [] to insert values into it.

How to round a numpy array?

If you want the output to be

array([1.6e-01, 9.9e-01, 3.6e-04])

the problem is not really a missing feature of NumPy, but rather that this sort of rounding is not a standard thing to do. You can make your own rounding function which achieves this like so:

def my_round(value, N):
    exponent = np.ceil(np.log10(value))
    return 10**exponent*np.round(value*10**(-exponent), N)

For a general solution handling 0 and negative values as well, you can do something like this:

def my_round(value, N):
    value = np.asarray(value).copy()
    zero_mask = (value == 0)
    value[zero_mask] = 1.0
    sign_mask = (value < 0)
    value[sign_mask] *= -1
    exponent = np.ceil(np.log10(value))
    result = 10**exponent*np.round(value*10**(-exponent), N)
    result[sign_mask] *= -1
    result[zero_mask] = 0.0
    return result

Quickly getting to YYYY-mm-dd HH:MM:SS in Perl

Use strftime in the standard POSIX module. The arguments to strftime in Perl’s binding were designed to align with the return values from localtime and gmtime. Compare

strftime(fmt, sec, min, hour, mday, mon, year, wday = -1, yday = -1, isdst = -1)

with

my          ($sec,$min,$hour,$mday,$mon,$year,$wday,     $yday,     $isdst) = gmtime(time);

Example command-line use is

$ perl -MPOSIX -le 'print strftime "%F %T", localtime $^T'

or from a source file as in

use POSIX;

print strftime "%F %T", localtime time;

Some systems do not support the %F and %T shorthands, so you will have to be explicit with

print strftime "%Y-%m-%d %H:%M:%S", localtime time;

or

print strftime "%Y-%m-%d %H:%M:%S", gmtime time;

Note that time returns the current time when called whereas $^T is fixed to the time when your program started. With gmtime, the return value is the current time in GMT. Retrieve time in your local timezone with localtime.

Cheap way to search a large text file for a string

You could do a simple find:

f = open('file.txt', 'r')
lines = f.read()
answer = lines.find('string')

A simple find will be quite a bit quicker than regex if you can get away with it.

Python - How to convert JSON File to Dataframe

Creating dataframe from dictionary object.

import pandas as pd
data = [{'name': 'vikash', 'age': 27}, {'name': 'Satyam', 'age': 14}]
df = pd.DataFrame.from_dict(data, orient='columns')

df
Out[4]:
   age  name
0   27  vikash
1   14  Satyam

If you have nested columns then you first need to normalize the data:

data = [
  {
    'name': {
      'first': 'vikash',
      'last': 'singh'
    },
    'age': 27
  },
  {
    'name': {
      'first': 'satyam',
      'last': 'singh'
    },
    'age': 14
  }
]

df = pd.DataFrame.from_dict(pd.json_normalize(data), orient='columns')

df    
Out[8]:
age name.first  name.last
0   27  vikash  singh
1   14  satyam  singh

Source:

Import/Index a JSON file into Elasticsearch

if you are using VirtualBox and UBUNTU in it or you are simply using UBUNTU then it can be useful

wget https://github.com/andrewvc/ee-datasets/archive/master.zip
sudo apt-get install unzip (only if unzip module is not installed)
unzip master.zip
cd ee-datasets
java -jar elastic-loader.jar http://localhost:9200 datasets/movie_db.eloader

Twitter Bootstrap Responsive Background-Image inside Div

Don't use fixed:

.myimage {
   background:url(admin-user-bg.png) no-repeat top center;
   background: transparent url("yourimage.png") no-repeat top center fixed;
   -webkit-background-size: cover;
   -moz-background-size: cover;
   -o-background-size: cover;
   background-size: 100%;
   height: 500px;
}

List all employee's names and their managers by manager name using an inner join

SELECT DISTINCT e.Ename AS Employee, 
    m.mgr AS reports_to, 
    m.Ename AS manager 
FROM Employees e, Employees m 
WHERE e.mgr=m.EmpID;

How to kill a nodejs process in Linux?

In order to kill use: killall -9 /usr/bin/node

To reload use: killall -12 /usr/bin/node

Simulator or Emulator? What is the difference?

Both are models of an object that you have some means of controlling inputs to and observing outputs from.

The key difference is that:

  • With an emulator, you want the output exactly match what the object you are emulating would produce.
  • With a simulator, you want certain properties of your output to be similar to what the object would produce.

Let me give an example -- suppose you want to do some system testing to see how adding a new sensor (like a thermometer) to a system would affect the system. You know that the thermometer sends a message 8 time a second containing its measurement.

Simulation -- if you do not have the thermometer yet, but you want to test that this message rate will not overload you system, you can simulate the sensor by attaching a unit that sends a random number 8 times a second. You can run any test that does not rely on the actual value the sensor sends.

Emulation -- suppose you have a very expensive thermometer that measures to 0.001 C, and you want to see if you can get by with a cheaper thermometer that only measures to the nearest 0.5 C. You can emulate the cheaper thermometer using an expensive thermometer and then rounding the reading to the nearest 0.5 C and running tests that rely on the temperature values.

Note that simulations can also be used for forecasting or predicting behavior. Finite element analysis simulations are used in many applications, including weather prediction and virtual wind tunnels.

The definitions of the terms:

  • emulation -- surpass or exactly match
  • simulate -- imitate in appearance or character

How to git-cherry-pick only changes to certain files?

I would just cherry-pick everything, then do this:

git reset --soft HEAD^

Then I would revert the changes I don't want, then make a new commit.

jquery : focus to div is not working

you can use the below code to bring focus to a div, in this example the page scrolls to the <div id="navigation">

$('html, body').animate({ scrollTop: $('#navigation').offset().top }, 'slow');

AngularJS + JQuery : How to get dynamic content working in angularjs

You need to call $compile on the HTML string before inserting it into the DOM so that angular gets a chance to perform the binding.

In your fiddle, it would look something like this.

$("#dynamicContent").html(
  $compile(
    "<button ng-click='count = count + 1' ng-init='count=0'>Increment</button><span>count: {{count}} </span>"
  )(scope)
);

Obviously, $compile must be injected into your controller for this to work.

Read more in the $compile documentation.

How to compare two JSON objects with the same elements in a different order equal?

For the following two dicts 'dictWithListsInValue' and 'reorderedDictWithReorderedListsInValue' which are simply reordered versions of each other

dictObj = {"foo": "bar", "john": "doe"}
reorderedDictObj = {"john": "doe", "foo": "bar"}
dictObj2 = {"abc": "def"}
dictWithListsInValue = {'A': [{'X': [dictObj2, dictObj]}, {'Y': 2}], 'B': dictObj2}
reorderedDictWithReorderedListsInValue = {'B': dictObj2, 'A': [{'Y': 2}, {'X': [reorderedDictObj, dictObj2]}]}
a = {"L": "M", "N": dictWithListsInValue}
b = {"L": "M", "N": reorderedDictWithReorderedListsInValue}

print(sorted(a.items()) == sorted(b.items()))  # gives false

gave me wrong result i.e. false .

So I created my own cutstom ObjectComparator like this:

def my_list_cmp(list1, list2):
    if (list1.__len__() != list2.__len__()):
        return False

    for l in list1:
        found = False
        for m in list2:
            res = my_obj_cmp(l, m)
            if (res):
                found = True
                break

        if (not found):
            return False

    return True


def my_obj_cmp(obj1, obj2):
    if isinstance(obj1, list):
        if (not isinstance(obj2, list)):
            return False
        return my_list_cmp(obj1, obj2)
    elif (isinstance(obj1, dict)):
        if (not isinstance(obj2, dict)):
            return False
        exp = set(obj2.keys()) == set(obj1.keys())
        if (not exp):
            # print(obj1.keys(), obj2.keys())
            return False
        for k in obj1.keys():
            val1 = obj1.get(k)
            val2 = obj2.get(k)
            if isinstance(val1, list):
                if (not my_list_cmp(val1, val2)):
                    return False
            elif isinstance(val1, dict):
                if (not my_obj_cmp(val1, val2)):
                    return False
            else:
                if val2 != val1:
                    return False
    else:
        return obj1 == obj2

    return True


dictObj = {"foo": "bar", "john": "doe"}
reorderedDictObj = {"john": "doe", "foo": "bar"}
dictObj2 = {"abc": "def"}
dictWithListsInValue = {'A': [{'X': [dictObj2, dictObj]}, {'Y': 2}], 'B': dictObj2}
reorderedDictWithReorderedListsInValue = {'B': dictObj2, 'A': [{'Y': 2}, {'X': [reorderedDictObj, dictObj2]}]}
a = {"L": "M", "N": dictWithListsInValue}
b = {"L": "M", "N": reorderedDictWithReorderedListsInValue}

print(my_obj_cmp(a, b))  # gives true

which gave me the correct expected output!

Logic is pretty simple:

If the objects are of type 'list' then compare each item of the first list with the items of the second list until found , and if the item is not found after going through the second list , then 'found' would be = false. 'found' value is returned

Else if the objects to be compared are of type 'dict' then compare the values present for all the respective keys in both the objects. (Recursive comparison is performed)

Else simply call obj1 == obj2 . It by default works fine for the object of strings and numbers and for those eq() is defined appropriately .

(Note that the algorithm can further be improved by removing the items found in object2, so that the next item of object1 would not compare itself with the items already found in the object2)

Synchronization vs Lock

Many answers here recommend using synchronized.

However, it depends on the usecase.

The synchronized keyword has naturally built in language support. This can mean the JIT can optimise synchronised blocks in ways it cannot with Locks. e.g. it can combine synchronized blocks. Only one thread is allowed to access only one method at any given point of time using a synchronized block. This is a very expensive operation.

Locks avoid this by allowing configuration of various locks for different purpose. One can have couple of methods synchronized under one lock and other methods under a different lock. This allows more concurrency and also increases overall performance.

So, for a smaller system which can do without concurrency and allowing one thread to execute an operation, synchronized can work. Otherwise, lock can be taken on the key.

Git Extensions: Win32 error 487: Couldn't reserve space for cygwin's heap, Win32 error 0

Very simple verison of the rebase solution:

Go to the folder where git is installed, such as:

C:\Program Files (x86)\Git\bin

By holding shift and right clicking in the folder, you should be able to open a command prompt as administrator from there (thanks to https://stackoverflow.com/users/355389/darren-lewis for that comment),

Then run:

rebase.exe -b 0x50000000 msys-1.0.dll

This fixed it for me when the restart approach didn't work.

Hope it helps.

String comparison - Android

Try it:

if (Objects.equals(gender, "Male")) {
    salutation ="Mr.";
} else if (Objects.equals(gender, "Female")) {
    salutation ="Ms.";
}

Quoting backslashes in Python string literals

Use a raw string:

>>> foo = r'baz "\"'
>>> foo
'baz "\\"'

Note that although it looks wrong, it's actually right. There is only one backslash in the string foo.

This happens because when you just type foo at the prompt, python displays the result of __repr__() on the string. This leads to the following (notice only one backslash and no quotes around the printed string):

>>> foo = r'baz "\"'
>>> foo
'baz "\\"'
>>> print(foo)
baz "\"

And let's keep going because there's more backslash tricks. If you want to have a backslash at the end of the string and use the method above you'll come across a problem:

>>> foo = r'baz \'
  File "<stdin>", line 1
    foo = r'baz \'
                 ^  
SyntaxError: EOL while scanning single-quoted string

Raw strings don't work properly when you do that. You have to use a regular string and escape your backslashes:

>>> foo = 'baz \\'
>>> print(foo)
baz \

However, if you're working with Windows file names, you're in for some pain. What you want to do is use forward slashes and the os.path.normpath() function:

myfile = os.path.normpath('c:/folder/subfolder/file.txt')
open(myfile)

This will save a lot of escaping and hair-tearing. This page was handy when going through this a while ago.

Using "label for" on radio buttons

Either structure is valid and accessible, but the for attribute should be equal to the id of the input element:

<input type="radio" ... id="r1" /><label for="r1">button text</label>

or

<label for="r1"><input type="radio" ... id="r1" />button text</label>

The for attribute is optional in the second version (label containing input), but IIRC there were some older browsers that didn't make the label text clickable unless you included it. The first version (label after input) is easier to style with CSS using the adjacent sibling selector +:

input[type="radio"]:checked+label {font-weight:bold;}

Python: SyntaxError: keyword can't be an expression

Using the Elastic search DSL API, you may hit the same error with

s = Search(using=client, index="my-index") \
    .query("match", category.keyword="Musician")

You can solve it by doing:

s = Search(using=client, index="my-index") \
    .query({"match": {"category.keyword":"Musician/Band"}})

Add some word to all or some rows in Excel?

  • Select All cells that want to change.
  • right click and select Format cell.
  • In category select Custom.
  • In Type select General and insert this formol ----> "k"@

could not access the package manager. is the system running while installing android application

You need to wait for the emulator to full start - takes a few minutes. Once it is fully started (UI on the emulator will change), it should work.

You will need to restart the app after the emulator is running and choose the running emulator when prompted.

Input and output numpy arrays to h5py

A cleaner way to handle file open/close and avoid memory leaks:

Prep:

import numpy as np
import h5py

data_to_write = np.random.random(size=(100,20)) # or some such

Write:

with h5py.File('name-of-file.h5', 'w') as hf:
    hf.create_dataset("name-of-dataset",  data=data_to_write)

Read:

with h5py.File('name-of-file.h5', 'r') as hf:
    data = hf['name-of-dataset'][:]

System.Timers.Timer vs System.Threading.Timer

This article offers a fairly comprehensive explanation:

"Comparing the Timer Classes in the .NET Framework Class Library" - also available as a .chm file

The specific difference appears to be that System.Timers.Timer is geared towards multithreaded applications and is therefore thread-safe via its SynchronizationObject property, whereas System.Threading.Timer is ironically not thread-safe out-of-the-box.

I don't believe that there is a difference between the two as it pertains to how small your intervals can be.

How to remove anaconda from windows completely?

For windows-

  1. In the Control Panel, choose Add or Remove Programs or Uninstall a program, and then select Python 3.6 (Anaconda) or your version of Python.
  2. Use Windows Explorer to delete the envs and pkgs folders prior to Running the uninstall in the root of your installation.

PHP Fatal error: Using $this when not in object context

When you call the function in a static context, $this simply doesn't exist.

You would have to use this::xyz() instead.

To find out what context you're in when a function can be called both statically and in an object instance, a good approach is outlined in this question: How to tell whether I’m static or an object?

Retrieving data from a POST method in ASP.NET

You need to examine (put a breakpoint on / Quick Watch) the Request object in the Page_Load method of your Test.aspx.cs file.

HTML/Javascript change div content

Get the id of the div whose content you want to change then assign the text as below:

  var myDiv = document.getElementById("divId");
  myDiv.innerHTML = "Content To Show";

Check if element found in array c++

Here is a simple generic C++11 function contains which works for both arrays and containers:

using namespace std;

template<class C, typename T>
bool contains(C&& c, T e) { return find(begin(c), end(c), e) != end(c); };

Simple usage contains(arr, el) is somewhat similar to in keyword semantics in Python.

Here is a complete demo:

#include <algorithm>
#include <array>
#include <string>
#include <vector>
#include <iostream>

template<typename C, typename T>
bool contains(C&& c, T e) { 
    return std::find(std::begin(c), std::end(c), e) != std::end(c);
};

template<typename C, typename T>
void check(C&& c, T e) {
    std::cout << e << (contains(c,e) ? "" : " not") <<  " found\n";
}

int main() {
    int a[] = { 10, 15, 20 };
    std::array<int, 3> b { 10, 10, 10 };
    std::vector<int> v { 10, 20, 30 };
    std::string s { "Hello, Stack Overflow" };
    
    check(a, 10);
    check(b, 15);
    check(v, 20);
    check(s, 'Z');

    return 0;
}

Output:

10 found
15 not found
20 found
Z not found

Create Elasticsearch curl query for not null and not empty("")

Wrap a Missing Filter in the Must-Not section of a Bool Filter. It will only return documents where the field exists, and if you set the "null_value" property to true, values that are explicitly not null.

{
  "query":{
     "filtered":{
        "query":{
           "match_all":{}
        },
        "filter":{
            "bool":{
              "must":{},
              "should":{},
              "must_not":{
                 "missing":{
                    "field":"field1",
                    "existence":true,
                    "null_value":true
                 }
              }
           }
        }
     }
  }
}

Detecting installed programs via registry

User-specific settings should be written to HKCU\Software, machine-specific settings to HKLM\Software. Under these keys, structure [software vendor name]\[application name] (e.g. HKLM\Software\Microsoft\Internet Explorer) may be the most common, but that's just a convention, not a law of nature.

Many (most?) applications also add their uninstall entries to HKLM\Software\Microsoft\Windows\CurrentVersion\Uninstall\[app name], but again, not all applications do this.

These are the most important keys; however, contents of the registry do not have to represent the installed software exactly - maybe the application was installed once, but then was manually deleted, or maybe the uninstaller didn't remove all traces of it. If you want to be sure, check the filesystem to see if the application still exists where its registry entries say it is.

Edit:

If you're a member of the group Administrators, you can check the HKEY_USERS hive - each user's HKCU actually resides there (you'll need to know the user SID, or go through all of them).

Note: As @Brian Ensink says, "installed" is a bit of a vague concept - are we trying to find what the user could run? Some software doesn't even write to the Registry at all: search for "portable apps" to see apps that have been specifically modified to run directly from media (CD/USB) and not to leave any traces on the computer. We may also have to scan the disks, and network disks, and anything the user downloads, and world-accessible Windows shares in the Internet (yes, such things exist legitimately - \\live.sysinternals.com\tools comes to mind). In this direction, there's no real limit of what the user can run, unless prevented by system policies.

Why powershell does not run Angular commands?

I solved my problem by running below command

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser

Rails 4 Authenticity Token

Adding the following line into the form worked for me:

<%= hidden_field_tag :authenticity_token, form_authenticity_token %>

Import pandas dataframe column as string not int

Since pandas 1.0 it became much more straightforward. This will read column 'ID' as dtype 'string':

pd.read_csv('sample.csv',dtype={'ID':'string'})

As we can see in this Getting started guide, 'string' dtype has been introduced (before strings were treated as dtype 'object').

How to use global variable in node.js?

May be following is better to avoid the if statement:

global.logger || (global.logger = require('my_logger'));

Can I do Android Programming in C++, C?

You can take a look also at C++ Builder XE6, and XE7 supports android in c++ code, and with Firemonkey library.

http://www.embarcadero.com/products/cbuilder

Pretty easy way to start, and native code. But the binaries have a big size.

Retrieving Dictionary Value Best Practices

TryGetValue is slightly faster, because FindEntry will only be called once.

How much faster? It depends on the dataset at hand. When you call the Contains method, Dictionary does an internal search to find its index. If it returns true, you need another index search to get the actual value. When you use TryGetValue, it searches only once for the index and if found, it assigns the value to your variable.

FYI: It's not actually catching an error.

It's calling:

public bool TryGetValue(TKey key, out TValue value)
{
    int index = this.FindEntry(key);
    if (index >= 0)
    {
        value = this.entries[index].value;
        return true;
    }
    value = default(TValue);
    return false;
}

ContainsKey is this:

public bool ContainsKey(TKey key)
{
    return (this.FindEntry(key) >= 0);
}

Qt: How do I handle the event of the user pressing the 'X' (close) button?

also you can reimplement protected member QWidget::closeEvent()

void YourWidgetWithXButton::closeEvent(QCloseEvent *event)
{
    // do what you need here
    // then call parent's procedure
    QWidget::closeEvent(event);
}

MyISAM versus InnoDB

bottomline: if you are working offline with selects on large chunks of data, MyISAM will probably give you better (much better) speeds.

there are some situations when MyISAM is infinitely more efficient than InnoDB: when manipulating large data dumps offline (because of table lock).

example: I was converting a csv file (15M records) from NOAA which uses VARCHAR fields as keys. InnoDB was taking forever, even with large chunks of memory available.

this an example of the csv (first and third fields are keys).

USC00178998,20130101,TMAX,-22,,,7,0700
USC00178998,20130101,TMIN,-117,,,7,0700
USC00178998,20130101,TOBS,-28,,,7,0700
USC00178998,20130101,PRCP,0,T,,7,0700
USC00178998,20130101,SNOW,0,T,,7,

since what i need to do is run a batch offline update of observed weather phenomena, i use MyISAM table for receiving data and run JOINS on the keys so that i can clean the incoming file and replace VARCHAR fields with INT keys (which are related to external tables where the original VARCHAR values are stored).

How to make an Asynchronous Method return a value?

Probably the simplest way to do it is to create a delegate and then BeginInvoke, followed by a wait at some time in the future, and an EndInvoke.

public bool Foo(){
    Thread.Sleep(100000); // Do work
    return true;
}

public SomeMethod()
{
    var fooCaller = new Func<bool>(Foo);
    // Call the method asynchronously
    var asyncResult = fooCaller.BeginInvoke(null, null);

    // Potentially do other work while the asynchronous method is executing.

    // Finally, wait for result
    asyncResult.AsyncWaitHandle.WaitOne();
    bool fooResult = fooCaller.EndInvoke(asyncResult);

    Console.WriteLine("Foo returned {0}", fooResult);
}

How to set maximum fullscreen in vmware?

Change the resolution of your operating system running in VMware and hope it will stretch the screen when chosen the correct values

How do I remove the blue styling of telephone numbers on iPhone/iOS?

<meta name="format-detection" content="telephone=no">. This metatag works in the default Safari browser on iOS devices and will only work for telephone numbers that are not wrapped in a telephone link so

1-800-123-4567
<a href="tel:18001234567">1-800-123-4567</a>

the first line will not be formatted as a link if you specify the metatag but the second line will because it's wrapped in a telephone anchor.


You can forego the metatag all-together and use a mixin such as

a[href^=tel]{
    color:inherit;
    text-decoration:inherit;
    font-size:inherit;
    font-style:inherit;
    font-weight:inherit;
}

to maintain intended styling of your telephone numbers, but you must make sure you wrap them in a telephone anchor.

If you want to be extra cautious and protect against the event of a telephone number which is not properly formatted with a wrapping anchor tag you can drill through the DOM and adjust with this script. Adjust the replacement pattern as desired.

$('body').html($('body').html().replace(/^\D?(\d{3})\D?\D?(\d{3})\D?(\d{4})/g, '<a href="tel:+1$1$2$3">($1) $2-$3</a>'));

or even better without jQuery

document.body.innerHTML = document.body.innerHTML.replace(/^\D?(\d{3})\D?\D?(\d{3})\D?(\d{4})/g,'<a href="tel:+1$1$2$3">($1) $2-$3</a>');

How do I convert a Django QuerySet into list of dicts?

You can use the values() method on the dict you got from the Django model field you make the queries on and then you can easily access each field by a index value.

Call it like this -

myList = dictOfSomeData.values()
itemNumberThree = myList[2] #If there's a value in that index off course...

Enums in Javascript with ES6

Here is an Enum factory that avoids realm issues by using a namespace and Symbol.for:

_x000D_
_x000D_
const Enum = (n, ...v) => Object.freeze(v.reduce((o, v) => (o[v] = Symbol.for(`${n}.${v}`), o), {}));

const COLOR = Enum("ACME.Color", "Blue", "Red");
console.log(COLOR.Red.toString());
console.log(COLOR.Red === Symbol.for("ACME.Color.Red"));
_x000D_
_x000D_
_x000D_

What's the difference between "Request Payload" vs "Form Data" as seen in Chrome dev tools Network tab

In Chrome, request with 'Content-Type:application/json' shows as Request PayedLoad and sends data as json object.

But request with 'Content-Type:application/x-www-form-urlencoded' shows Form Data and sends data as Key:Value Pair, so if you have array of object in one key it flats that key's value:

{ Id: 1, 
name:'john', 
phones:[{title:'home',number:111111,...},
        {title:'office',number:22222,...}]
}

sends

{ Id: 1, 
name:'john', 
phones:[object object]
phones:[object object]
}

How to insert close button in popover for Bootstrap

Just wanted to update the answer. As per Swashata Ghosh, the following is a simpler way that worked for moi:

HTML:

<button type="button" class="btn btn-primary example">Example</button>

JS:

$('.example').popover({
   title: function() {
      return 'Popup title' +
             '<button class="close">&times</button>';
   },
   content: 'Popup content',
   trigger: 'hover',
   html: true
});

$('.popover button.close').click(function() {
   $(this).popover('toggle');
});

Write to custom log file from a Bash script

I did it by using a filter. Most linux systems use rsyslog these days. The config files are located at /etc/rsyslog.conf and /etc/rsyslog.d.

Whenever I run the command logger -t SRI some message, I want "some message" to only show up in /var/log/sri.log.

To do this I added the file /etc/rsyslog.d/00-sri.conf with the following content.

# Filter all messages whose tag starts with SRI
# Note that 'isequal, "SRI:"' or 'isequal "SRI"' will not work.
#
:syslogtag, startswith, "SRI" /var/log/sri.log

# The stop command prevents this message from getting processed any further.
# Thus the message will not show up in /var/log/messages.
#
& stop

Then restart the rsyslogd service:

systemctl restart rsyslog.service

Here is a shell session showing the results:

[root@rpm-server html]# logger -t SRI Hello World!
[root@rpm-server html]# cat /var/log/sri.log
Jun  5 10:33:01 rpm-server SRI[11785]: Hello World!
[root@rpm-server html]#
[root@rpm-server html]# # see that nothing shows up in /var/log/messages
[root@rpm-server html]# tail -10 /var/log/messages | grep SRI
[root@rpm-server html]#

LINQ Joining in C# with multiple conditions

Your and should be a && in the where clause.

where epl.DepartAirportAfter >  sd.UTCDepartureTime 
and epl.ArriveAirportBy > sd.UTCArrivalTime

should be

where epl.DepartAirportAfter >  sd.UTCDepartureTime 
&& epl.ArriveAirportBy > sd.UTCArrivalTime

List comprehension vs map

I tried the code by @alex-martelli but found some discrepancies

python -mtimeit -s "xs=range(123456)" "map(hex, xs)"
1000000 loops, best of 5: 218 nsec per loop
python -mtimeit -s "xs=range(123456)" "[hex(x) for x in xs]"
10 loops, best of 5: 19.4 msec per loop

map takes the same amount of time even for very large ranges while using list comprehension takes a lot of time as is evident from my code. So apart from being considered "unpythonic", I have not faced any performance issues relating to usage of map.

Is there a JavaScript strcmp()?

var strcmp = new Intl.Collator(undefined, {numeric:true, sensitivity:'base'}).compare;

Usage: strcmp(string1, string2)

Result: 1 means string1 is bigger, 0 means equal, -1 means string2 is bigger.

This has higher performance than String.prototype.localeCompare

Also, numeric:true makes it do logical number comparison

Wait .5 seconds before continuing code VB.net

Another way is to use System.Threading.ManualResetEvent

dim SecondsToWait as integer = 5
Dim Waiter As New ManualResetEvent(False)
Waiter.WaitOne(SecondsToWait * 1000) 'to get it into milliseconds

C# Passing Function as Argument

There are a couple generic types in .Net (v2 and later) that make passing functions around as delegates very easy.

For functions with return types, there is Func<> and for functions without return types there is Action<>.

Both Func and Action can be declared to take from 0 to 4 parameters. For example, Func < double, int > takes one double as a parameter and returns an int. Action < double, double, double > takes three doubles as parameters and returns nothing (void).

So you can declare your Diff function to take a Func:

public double Diff(double x, Func<double, double> f) {
    double h = 0.0000001;

    return (f(x + h) - f(x)) / h;
}

And then you call it as so, simply giving it the name of the function that fits the signature of your Func or Action:

double result = Diff(myValue, Function);

You can even write the function in-line with lambda syntax:

double result = Diff(myValue, d => Math.Sqrt(d * 3.14));

Required request body content is missing: org.springframework.web.method.HandlerMethod$HandlerMethodParameter

In my side, it is because POSTMAN setting issue, but I don't know why, maybe I copy a query from other. I simply create a new request in POSTMAN and run it, it works.

blur() vs. onblur()

This:

document.getElementById('myField').onblur();

works because your element (the <input>) has an attribute called "onblur" whose value is a function. Thus, you can call it. You're not telling the browser to simulate the actual "blur" event, however; there's no event object created, for example.

Elements do not have a "blur" attribute (or "method" or whatever), so that's why the first thing doesn't work.

How can I reset eclipse to default settings?

All the setting are stored in .metadata file in your workspace delete this and you are good to go

Multiplication on command line terminal

If you like python and have an option to install a package, you can use this utility that I made.

# install pythonp
python -m pip install pythonp

pythonp "5*5"
25

pythonp "1 / (1+math.exp(0.5))"
0.3775406687981454

# define a custom function and pass it to another higher-order function
pythonp "n=10;functools.reduce(lambda x,y:x*y, range(1,n+1))"     
3628800

Post Build exited with code 1

I had this same issue and it turned out that it was because I had renamed the project. I went into the project properties and changed the Assembly Name and Root Namespace to the project name and it worked great after that!

Is there any way to change input type="date" format?

Browsers obtain the date-input format from user's system date format.

(Tested in supported browsers, Chrome, Edge.)

As there is no standard defined by specs as of now to change the style of date control, its not possible to implement the same in browsers.

Users can type a date value into the text field of an input[type=date] with the date format shown in the box as gray text. This format is obtained from the operating system's setting. Web authors have no way to change the date format because there currently is no standards to specify the format.

So no need to change it, if we don't change anything, users will see the date-input's format same as they have configured in the system/device settings and which they are comfortable with or matches with their locale.

Remember, this is just the UI format on the screen which users see, in your JavaScript/backend you can always keep your desired format to work with.

Refer google developers page on same.

@font-face not working

You need to put the font file name / path in quotes.
Eg.

url("../fonts/Gotham-Medium.ttf")

or

url('../fonts/Gotham-Medium.ttf')

and not

url(../fonts/Gotham-Medium.ttf)

Also @FONT-FACE only works with some font files. :o(

All the sites where you can download fonts, never say which fonts work and which ones don't.

Convert URL to File or Blob for FileReader.readAsDataURL

This information is outdated as of now, but cannot be deleted.

  1. You can create File instances just by specifying a path when your code is chrome-privileged:

    new File("/path/to/file");
    

    File is a sub-class of Blob, so all File instances are also valid Blobs. Please note that this requires a platform path, and not a file URL.

  2. Yes, FileReader is available to addons.

File and FileReader are available in all windows. If you want to use them in a non-window scope (like bootstrap.js or a code module), you may use nsIDOMFile/nsIDOMFileReader.

Python - TypeError: 'int' object is not iterable

Your problem is with this line:

number4 = list(cow[n])

It tries to take cow[n], which returns an integer, and make it a list. This doesn't work, as demonstrated below:

>>> a = 1
>>> list(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
>>>

Perhaps you meant to put cow[n] inside a list:

number4 = [cow[n]]

See a demonstration below:

>>> a = 1
>>> [a]
[1]
>>>

Also, I wanted to address two things:

  1. Your while-statement is missing a : at the end.
  2. It is considered very dangerous to use input like that, since it evaluates its input as real Python code. It would be better here to use raw_input and then convert the input to an integer with int.

To split up the digits and then add them like you want, I would first make the number a string. Then, since strings are iterable, you can use sum:

>>> a = 137
>>> a = str(a)
>>> # This way is more common and preferred
>>> sum(int(x) for x in a)
11
>>> # But this also works
>>> sum(map(int, a))
11
>>>

Passing data to components in vue.js

The above-mentioned responses work well but if you want to pass data between 2 sibling components, then the event bus can also be used. Check out this blog which would help you understand better.

supppose for 2 components : CompA & CompB having same parent and main.js for setting up main vue app. For passing data from CompA to CompB without involving parent component you can do the following.

in main.js file, declare a separate global Vue instance, that will be event bus.

export const bus = new Vue();

In CompA, where the event is generated : you have to emit the event to bus.

methods: {
      somethingHappened (){
          bus.$emit('changedSomething', 'new data');
      }
  }

Now the task is to listen the emitted event, so, in CompB, you can listen like.

created (){
    bus.$on('changedSomething', (newData) => {
      console.log(newData);
    })
  }

Advantages:

  • Less & Clean code.
  • Parent should not involve in passing down data from 1 child comp to another ( as the number of children grows, it will become hard to maintain )
  • Follows pub-sub approach.

Count occurrences of a char in a string using Bash

Building on everyone's great answers and comments, this is the shortest and sweetest version:

grep -o "$needle" <<< "$haystack" | wc -l

Does mobile Google Chrome support browser extensions?

I imagine that there are not many browsers supporting extension. Indeed, I have been interested in this question for the last year and I only found Dolphin supporting add-ons and other cool features announced few days ago. I want to test it soon.

How can I match on an attribute that contains a certain string?

I came here searching solution for Ranorex Studio 9.0.1. There is no contains() there yet. Instead we can use regex like:

div[@class~'atag']

How to import data from text file to mysql database

You should set the option:

local-infile=1

into your [mysql] entry of my.cnf file or call mysql client with the --local-infile option:

mysql --local-infile -uroot -pyourpwd yourdbname

You have to be sure that the same parameter is defined into your [mysqld] section too to enable the "local infile" feature server side.

It's a security restriction.

LOAD DATA LOCAL INFILE '/softwares/data/data.csv' INTO TABLE tableName;

Number of times a particular character appears in a string

Use this function begining from SQL SERVER 2016

Select Count(value) From STRING_SPLIT('AAA AAA AAA',' ');

-- Output : 3 

When This function used with count function it gives you how many character exists in string

Grunt watch error - Waiting...Fatal error: watch ENOSPC

To find out who's making inotify instances, try this command (source):

for foo in /proc/*/fd/*; do readlink -f $foo; done | grep inotify | sort | uniq -c | sort -nr

Mine looked like this:

 25 /proc/2857/fd/anon_inode:inotify
  9 /proc/2880/fd/anon_inode:inotify
  4 /proc/1375/fd/anon_inode:inotify
  3 /proc/1851/fd/anon_inode:inotify
  2 /proc/2611/fd/anon_inode:inotify
  2 /proc/2414/fd/anon_inode:inotify
  1 /proc/2992/fd/anon_inode:inotify

Using ps -p 2857, I was able to identify process 2857 as sublime_text. Only after closing all sublime windows was I able to run my node script.

How to parse a CSV file using PHP

A bit shorter answer since PHP >= 5.3.0:

    $csvFile = file('../somefile.csv');
    $data = [];
    foreach ($csvFile as $line) {
        $data[] = str_getcsv($line);
    }

Spring Boot - How to log all requests and responses with exceptions in single place?

Spring already provides a filter that does this job. Add following bean to your config

@Bean
public CommonsRequestLoggingFilter requestLoggingFilter() {
    CommonsRequestLoggingFilter loggingFilter = new CommonsRequestLoggingFilter();
    loggingFilter.setIncludeClientInfo(true);
    loggingFilter.setIncludeQueryString(true);
    loggingFilter.setIncludePayload(true);
    loggingFilter.setMaxPayloadLength(64000);
    return loggingFilter;
}

Don't forget to change log level of org.springframework.web.filter.CommonsRequestLoggingFilter to DEBUG.

Is there a way to make AngularJS load partials in the beginning and not at when needed?

If you wrap each template in a script tag, eg:

<script id="about.html" type="text/ng-template">
<div>
    <h3>About</h3>
    This is the About page
    Its cool!
</div>
</script>

Concatenate all templates into 1 big file. If using Visual Studio 2013, download Web essentials - it adds a right click menu to create an HTML Bundle.

Add the code that this guy wrote to change the angular $templatecache service - its only a small piece of code and it works: Vojta Jina's Gist

Its the $http.get that should be changed to use your bundle file:

allTplPromise = $http.get('templates/templateBundle.min.html').then(

Your routes templateUrl should look like this:

        $routeProvider.when(
            "/about", {
                controller: "",
                templateUrl: "about.html"
            }
        );

Copying Code from Inspect Element in Google Chrome

you dont have to do that in the Google chrome. Use the Internet explorer it offers the option to copy the css associated and after you copy and paste select the style and put that into another file .css to call into that html which you have created. Hope this will solve you problem than anything else:)

How to calculate probability in a normal distribution given mean & standard deviation?

Here is more info. First you are dealing with a frozen distribution (frozen in this case means its parameters are set to specific values). To create a frozen distribution:

import scipy.stats
scipy.stats.norm(loc=100, scale=12)
#where loc is the mean and scale is the std dev
#if you wish to pull out a random number from your distribution
scipy.stats.norm.rvs(loc=100, scale=12)

#To find the probability that the variable has a value LESS than or equal
#let's say 113, you'd use CDF cumulative Density Function
scipy.stats.norm.cdf(113,100,12)
Output: 0.86066975255037792
#or 86.07% probability

#To find the probability that the variable has a value GREATER than or
#equal to let's say 125, you'd use SF Survival Function 
scipy.stats.norm.sf(125,100,12)
Output: 0.018610425189886332
#or 1.86%

#To find the variate for which the probability is given, let's say the 
#value which needed to provide a 98% probability, you'd use the 
#PPF Percent Point Function
scipy.stats.norm.ppf(.98,100,12)
Output: 124.64498692758187

ExecuteReader requires an open and available Connection. The connection's current state is Connecting

I caught this error a few days ago.

IN my case it was because I was using a Transaction on a Singleton.

.Net does not work well with Singleton as stated above.

My solution was this:

public class DbHelper : DbHelperCore
{
    public DbHelper()
    {
        Connection = null;
        Transaction = null;
    }

    public static DbHelper instance
    {
        get
        {
            if (HttpContext.Current is null)
                return new DbHelper();
            else if (HttpContext.Current.Items["dbh"] == null)
                HttpContext.Current.Items["dbh"] = new DbHelper();

            return (DbHelper)HttpContext.Current.Items["dbh"];
        }
    }

    public override void BeginTransaction()
    {
        Connection = new SqlConnection(Entity.Connection.getCon);
        if (Connection.State == System.Data.ConnectionState.Closed)
            Connection.Open();
        Transaction = Connection.BeginTransaction();
    }
}

I used HttpContext.Current.Items for my instance. This class DbHelper and DbHelperCore is my own class

Positive Number to Negative Number in JavaScript?

It will convert negative array to positive or vice versa

function negateOrPositive(arr) {
    arr.map(res => -res)
};

Script to kill all connections to a database (More than RESTRICTED_USER ROLLBACK)

You can use Cursor like that:

USE master
GO

DECLARE @SQL AS VARCHAR(255)
DECLARE @SPID AS SMALLINT
DECLARE @Database AS VARCHAR(500)
SET @Database = 'AdventureWorks2016CTP3'

DECLARE Murderer CURSOR FOR
SELECT spid FROM sys.sysprocesses WHERE DB_NAME(dbid) = @Database

OPEN Murderer

FETCH NEXT FROM Murderer INTO @SPID
WHILE @@FETCH_STATUS = 0

    BEGIN
    SET @SQL = 'Kill ' + CAST(@SPID AS VARCHAR(10)) + ';'
    EXEC (@SQL)
    PRINT  ' Process ' + CAST(@SPID AS VARCHAR(10)) +' has been killed'
    FETCH NEXT FROM Murderer INTO @SPID
    END 

CLOSE Murderer
DEALLOCATE Murderer

I wrote about that in my blog here: http://www.pigeonsql.com/single-post/2016/12/13/Kill-all-connections-on-DB-by-Cursor

When should I write the keyword 'inline' for a function/method?

In reality, pretty much never. All you're doing is suggesting that the compiler make a given function inline (e.g., replace all calls to this function /w its body). There are no guarantees, of course: the compiler may ignore the directive.

The compiler will generally do a good job of detecting + optimizing things like this.

bash: npm: command not found?

If you have already installed nodejs and still getting this error. npm: command not found..

run this

apt-get install -y npm

Render HTML in React Native

I found this component. https://github.com/jsdf/react-native-htmlview

This component takes HTML content and renders it as native views, with customisable style and handling of links, etc.

default select option as blank

Just a small remark:

some Safari browsers do not seem to respect neither the "hidden" attribute nor the style setting "display:none" (tested with Safari 12.1 under MacOS 10.12.6). Without an explicit placeholder text, these browsers simply show an empty first line in the list of options. It may therefore be useful to always provide some explanatory text for this "dummy" entry:

<option hidden disabled selected value>(select an option)</option>

Thanks to the "disabled" attribute, it won't be actively selected anyway.

How to resolve Nodejs: Error: ENOENT: no such file or directory

Your app is expecting to find a file at /home/embah/node/nodeapp/config/config.json but that file does not exist (which is what ENOENT means). So you either need to create the expected directory structure or else configure your application such that it looks in the correct directory for config.json.

height style property doesn't work in div elements

use the min-height property. min-height:20px;

Not showing placeholder for input type="date" field

I ended up using the following.

Regarding Firefox comment(s): Generally, Firefox will not show any text placeholder for inputs type date. But as this is a Cordova/PhoneGap question this should be of no concern (Unless you want to develop against FirefoxOS).

_x000D_
_x000D_
input[type="date"]:not(.has-value):before{_x000D_
  color: lightgray;_x000D_
  content: attr(placeholder);_x000D_
}
_x000D_
<input type="date" placeholder="MY PLACEHOLDER" onchange="this.className=(this.value!=''?'has-value':'')">
_x000D_
_x000D_
_x000D_

Hexadecimal string to byte array in C

This is a modified function from a similar question, modified as per the suggestion of https://stackoverflow.com/a/18267932/700597.

This function will convert a hexadecimal string - NOT prepended with "0x" - with an even number of characters to the number of bytes specified. It will return -1 if it encounters an invalid character, or if the hex string has an odd length, and 0 on success.

//convert hexstring to len bytes of data
//returns 0 on success, -1 on error
//data is a buffer of at least len bytes
//hexstring is upper or lower case hexadecimal, NOT prepended with "0x"
int hex2data(unsigned char *data, const unsigned char *hexstring, unsigned int len)
{
    unsigned const char *pos = hexstring;
    char *endptr;
    size_t count = 0;

    if ((hexstring[0] == '\0') || (strlen(hexstring) % 2)) {
        //hexstring contains no data
        //or hexstring has an odd length
        return -1;
    }

    for(count = 0; count < len; count++) {
        char buf[5] = {'0', 'x', pos[0], pos[1], 0};
        data[count] = strtol(buf, &endptr, 0);
        pos += 2 * sizeof(char);

        if (endptr[0] != '\0') {
            //non-hexadecimal character encountered
            return -1;
        }
    }

    return 0;
}

How to specify jackson to only use fields - preferably globally

You can configure individual ObjectMappers like this:

ObjectMapper mapper  = new ObjectMapper();
mapper.setVisibility(mapper.getSerializationConfig().getDefaultVisibilityChecker()
                .withFieldVisibility(JsonAutoDetect.Visibility.ANY)
                .withGetterVisibility(JsonAutoDetect.Visibility.NONE)
                .withSetterVisibility(JsonAutoDetect.Visibility.NONE)
                .withCreatorVisibility(JsonAutoDetect.Visibility.NONE));

If you want it set globally, I usually access a configured mapper through a wrapper class.

Iterating through a string word by word

for word in string.split():
    print word

How to extract the decimal part from a floating point number in C?

You use the modf function:

double integral;
double fractional = modf(some_double, &integral);

You can also cast it to an integer, but be warned you may overflow the integer. The result is not predictable then.

How do I reference tables in Excel using VBA?

In addition, it's convenient to define variables referring to objects. For instance,

Sub CreateTable()
    Dim lo as ListObject
    Set lo = ActiveSheet.ListObjects.Add(xlSrcRange, Range("$B$1:$D$16"), , xlYes)
    lo.Name = "Table1"
    lo.TableStyle = "TableStyleLight2"
    ...
End Sub

You will probably find it advantageous at once.

Removing the password from a VBA project

This has a simple method using SendKeys to unprotect the VBA project. This would get you into the project, so you'd have to continue on using SendKeys to figure out a way to remove the password protection: http://www.pcreview.co.uk/forums/thread-989191.php

And here's one that uses a more advanced, somewhat more reliable method for unprotecting. Again, it will only unlock the VB project for you. http://www.ozgrid.com/forum/showthread.php?t=13006&page=2

I haven't tried either method, but this may save you some time if it's what you need to do...

How to vertically align text in input type="text"?

I found this question while looking for a solution to my own problem. The previous answers rely on padding to make the text appear at the top or bottom of the input or use a combination of height and line-height to align the text to the vertical middle.

Here is an alternative solution to making the text appear in the middle using a div and positioning. Check out the jsfiddle.

<style type="text/css">
    div {
        display: inline-block;
        height: 300px;
        position: relative;
        width: 500px;
    }

    input {
        height: 100%;
        position: absolute;
        text-align: center; /* Optional */
        width: 100%;
    }
</style>

<div>
    <input type="text" value="Hello world!" />
</div>

get basic SQL Server table structure information

For total columns information use below syntax : Use "DBName" go Exec SP_Columns "TableName"

For total table information use below syntax : Use "DBName" go Exec SP_help "Table Name"

htons() function in socket programing

It has to do with the order in which bytes are stored in memory. The decimal number 5001 is 0x1389 in hexadecimal, so the bytes involved are 0x13 and 0x89. Many devices store numbers in little-endian format, meaning that the least significant byte comes first. So in this particular example it means that in memory the number 5001 will be stored as

0x89 0x13

The htons() function makes sure that numbers are stored in memory in network byte order, which is with the most significant byte first. It will therefore swap the bytes making up the number so that in memory the bytes will be stored in the order

0x13 0x89

On a little-endian machine, the number with the swapped bytes is 0x8913 in hexadecimal, which is 35091 in decimal notation. Note that if you were working on a big-endian machine, the htons() function would not need to do any swapping since the number would already be stored in the right way in memory.

The underlying reason for all this swapping has to do with the network protocols in use, which require the transmitted packets to use network byte order.

Appending an id to a list if not already present in a string

Your list just contains a string. Convert it to integer IDs:

L = ['350882 348521 350166\r\n']

ids = [int(i) for i in L[0].strip().split()]
print(ids)
id = 348521
if id not in ids:
    ids.append(id)
print(ids)
id = 348522
if id not in ids:
    ids.append(id)
print(ids)
# Turn it back into your odd format
L = [' '.join(str(id) for id in ids) + '\r\n']
print(L)

Output:

[350882, 348521, 350166]
[350882, 348521, 350166]
[350882, 348521, 350166, 348522]
['350882 348521 350166 348522\r\n']

Check for special characters (/*-+_@&$#%) in a string?

The easiest way it to use a regular expression:

Regular Expression for alphanumeric and underscores

Using regular expressions in .net:

http://www.regular-expressions.info/dotnet.html

MSDN Regular Expression

Regex.IsMatch

var regexItem = new Regex("^[a-zA-Z0-9 ]*$");

if(regexItem.IsMatch(YOUR_STRING)){..}

Docker "ERROR: could not find an available, non-overlapping IPv4 address pool among the defaults to assign to the network"

Same error occurred while running VPN connection. Tried to create docker image with docker-compose. Works for me to stop VPN connection for a moment and execute the command.

How do I change the owner of a SQL Server database?

to change the object owner try the following

EXEC sp_changedbowner 'sa'

that however is not your problem, to see diagrams the Da Vinci Tools objects have to be created (you will see tables and procs that start with dt_) after that

WCF gives an unsecured or incorrectly secured fault error

In my case I was using certificates for authentication with certificateValidationMode set to "PeerTrust" and I had forgotten to install the client certificate in windows store (LocalMachine\TrustedPeople) to make it accepted by the server.

Installing MySQL-python

  1. find the folder: sudo find / -name "mysql_config" (assume it's "/opt/local/lib/mysql5/bin")

  2. add it into PATH:export PATH:export PATH=/opt/local/lib/mysql5/bin:$PATH

  3. install it again

import .css file into .less file

You can force a file to be interpreted as a particular type by specifying an option, e.g.:

@import (css) "lib";

will output

@import "lib";

and

@import (less) "lib.css";

will import the lib.css file and treat it as less. If you specify a file is less and do not include an extension, none will be added.

How to do INSERT into a table records extracted from another table

I believe your problem in this instance is the "values" keyword. You use the "values" keyword when you are inserting only one row of data. For inserting the results of a select, you don't need it.

Also, you really don't need the parentheses around the select statement.

From msdn:

Multiple-record append query:

INSERT INTO target [(field1[, field2[, …]])] [IN externaldatabase]
SELECT [source.]field1[, field2[, …]
FROM tableexpression

Single-record append query:

INSERT INTO target [(field1[, field2[, …]])]     
VALUES (value1[, value2[, …])

What are the file limits in Git (number and size)?

I think that it's good to try to avoid large file commits as being part of the repository (e.g. a database dump might be better off elsewhere), but if one considers the size of the kernel in its repository, you can probably expect to work comfortably with anything smaller in size and less complex than that.

How to link to part of the same document in Markdown?

Since MultiMarkdown was mentioned as an option in comments.

In MultiMarkdown the syntax for an internal link is simple.

For any heading in the document simply give the heading name in this format [heading][] to create an internal link.

Read more here: MultiMarkdown-5 Cross-references.

Cross-References

An oft-requested feature was the ability to have Markdown automatically handle within-document links as easily as it handled external links. To this aim, I added the ability to interpret [Some Text][] as a cross-link, if a header named “Some Text” exists.

As an example, [Metadata][] will take you to # Metadata (or any of ## Metadata, ### Metadata, #### Metadata, ##### Metadata, ###### Metadata).

Alternatively, you can include an optional label of your choosing to help disambiguate cases where multiple headers have the same title:

### Overview [MultiMarkdownOverview] ##

This allows you to use [MultiMarkdownOverview] to refer to this section specifically, and not another section named Overview. This works with atx- or settext-style headers.

If you have already defined an anchor using the same id that is used by a header, then the defined anchor takes precedence.

In addition to headers within the document, you can provide labels for images and tables which can then be used for cross-references as well.

Concatenate a NumPy array to another NumPy array

In [1]: import numpy as np

In [2]: a = np.array([[1, 2, 3], [4, 5, 6]])

In [3]: b = np.array([[9, 8, 7], [6, 5, 4]])

In [4]: np.concatenate((a, b))
Out[4]: 
array([[1, 2, 3],
       [4, 5, 6],
       [9, 8, 7],
       [6, 5, 4]])

or this:

In [1]: a = np.array([1, 2, 3])

In [2]: b = np.array([4, 5, 6])

In [3]: np.vstack((a, b))
Out[3]: 
array([[1, 2, 3],
       [4, 5, 6]])

How to solve static declaration follows non-static declaration in GCC C code?

From what the error message complains about, it sounds like you should rather try to fix the source code. The compiler complains about difference in declaration, similar to for instance

void foo(int i);
...
void foo(double d) {
    ...
}

and this is not valid C code, hence the compiler complains.

Maybe your problem is that there is no prototype available when the function is used the first time and the compiler implicitly creates one that will not be static. If so the solution is to add a prototype somewhere before it is first used.

Python 2: AttributeError: 'list' object has no attribute 'strip'

You split the string entry of the list. l[0].strip()

ImportError: No module named 'pygame'

  1. Install and download pygame .whl file.
  2. Move .whl file to your python35/Scripts
  3. Go to cmd
  4. Change directory to python scripts
  5. Type:

    pip install pygame
    

Here is an example:

C:\Users\user\AppData\Local\Programs\Python\Python36-32\Scripts>pip install pygame

How to limit the number of selected checkboxes?

Try like this.

On change event,

$('input[type=checkbox]').on('change', function (e) {
    if ($('input[type=checkbox]:checked').length > 3) {
        $(this).prop('checked', false);
        alert("allowed only 3");
    }
});

Check this in JSFiddle

Putting a password to a user in PhpMyAdmin in Wamp

Search your installation of PhpMyAdmin for a file called Documentation.txt. This describes how to create a file called config.inc.php and how you can configure the username and password.

How to get system time in Java without creating a new Date

You can use System.currentTimeMillis().

At least in OpenJDK, Date uses this under the covers.

The call in System is to a native JVM method, so we can't say for sure there's no allocation happening under the covers, though it seems unlikely here.

How to detect responsive breakpoints of Twitter Bootstrap 3 using JavaScript?

You could use the window size and hard code the breakpoints. Using Angular:

angular
    .module('components.responsiveDetection', [])
    .factory('ResponsiveDetection', function ($window) {
        return {
            getBreakpoint: function () {
                var w = $window.innerWidth;
                if (w < 768) {
                    return 'xs';
                } else if (w < 992) {
                    return 'sm';
                } else if (w < 1200) {
                    return 'md';
                } else {
                    return 'lg';
                }
            }
        };
    });

"The file "MyApp.app" couldn't be opened because you don't have permission to view it" when running app in Xcode 6 Beta 4

Having the problem on DEVICE too (not just simulator)?


The other solutions only fixed it for me on simulator, not device.

For me this problem occurred (in Xcode 6) when I would try to change the main info.plist properties whilst trying to change my app name.

In info.plist I had changed Executable File name to something other than the default ${EXECUTABLE_NAME}...

I had mistaken this field for the field that changes the name of the app under the icon on the springboard.

What's the best way to calculate the size of a directory in .NET?

This it the best way to calculate the size of a directory. Only other way would still use recursion but be a bit easier to use and isn't as flexible.

float folderSize = 0.0f;
FileInfo[] files = Directory.GetFiles(folder, "*", SearchOption.AllDirectories);
foreach(FileInfo file in files) folderSize += file.Length;

How do I install TensorFlow's tensorboard?

If you installed TensorFlow using pip, then the location of TensorBoard can be retrieved by issuing the command which tensorboard on the terminal. You can then edit the TensorBoard file, if necessary.

Excel tab sheet names vs. Visual Basic sheet names

I think I may have an alternative solution. It's a little ugly, but it seems to work.

Function GetAnyNameValue(NameofName) As String
    Dim nm, ws, rng As String
    nm = ActiveWorkbook.Names(NameofName).Value
    ws = CStr(Split(nm, "!")(0))
    ws = Replace(ws, "'", "")
    ws = Replace(ws, "=", "")
    rng = CStr(Split(nm, "!")(1))
    GetAnyNameValue = CStr(Worksheets(ws).Range(rng).Value)
End Function

Blue and Purple Default links, how to remove?

If you wants display anchors in your own choice of colors than you should define the color in anchor tag property in CSS like this:-

a { text-decoration: none; color:red; }
a:visited { text-decoration: none; }
a:hover { text-decoration: none; }
a:focus { text-decoration: none; }
a:hover, a:active { text-decoration: none; }

see the demo:- http://jsfiddle.net/zSWbD/7/

How do I get cURL to not show the progress bar?

In curl version 7.22.0 on Ubuntu and 7.24.0 on OSX the solution to not show progress but to show errors is to use both -s (--silent) and -S (--show-error) like so:

curl -sS http://google.com > temp.html

This works for both redirected output > /some/file, piped output | less and outputting directly to the terminal for me.

Update: Since curl 7.67.0 there is a new option --no-progress-meter which does precisely this and nothing else, see clonejo's answer for more details.

Print to standard printer from Python?

Unfortunately, there is no standard way to print using Python on all platforms. So you'll need to write your own wrapper function to print.

You need to detect the OS your program is running on, then:

For Linux -

import subprocess
lpr =  subprocess.Popen("/usr/bin/lpr", stdin=subprocess.PIPE)
lpr.stdin.write(your_data_here)

For Windows: http://timgolden.me.uk/python/win32_how_do_i/print.html

More resources:

Print PDF document with python's win32print module?

How do I print to the OS's default printer in Python 3 (cross platform)?

How to read an entire file to a string using C#?

you can read a text from a text file in to string as follows also

string str = "";
StreamReader sr = new StreamReader(Application.StartupPath + "\\Sample.txt");
while(sr.Peek() != -1)
{
  str = str + sr.ReadLine();
}

Using Excel as front end to Access database (with VBA)

To connect Excel to Access using VBA is very useful I use it in my profession everyday. The connection string I use is according to the program found in the link below. The program can be automated to do multiple connections or tasks in on shot but the basic connection code looks the same. Good luck!

http://vbaexcel.eu/vba-macro-code/database-connection-retrieve-data-from-database-querying-data-into-excel-using-vba-dao

python - find index position in list based of partial string

spell_list = ["Tuesday", "Wednesday", "February", "November", "Annual", "Calendar", "Solstice"]

index=spell_list.index("Annual")
print(index)

Initialise a list to a specific length in Python

In a talk about core containers internals in Python at PyCon 2012, Raymond Hettinger is suggesting to use [None] * n to pre-allocate the length you want.

Slides available as PPT or via Google

The whole slide deck is quite interesting. The presentation is available on YouTube, but it doesn't add much to the slides.

Server.MapPath - Physical path given, virtual path expected

var files = Directory.GetFiles(@"E:\ftproot\sales");

How to emulate GPS location in the Android Emulator?

For a project of my own, I developed an online service which can provide simulated location to the Android emulator.

It uses geo nmea rather than geo fix which allows it to set speed, course, precise time etc. in addition to just lat/lon.

The service requires the nc (netcat) command line utility and nothing else.

http://www.kisstech.ch/nmea/

How to shift a block of code left/right by one space in VSCode?

Have a look at File > Preferences > Keyboard Shortcuts (or Ctrl+K Ctrl+S)

Search for cursorColumnSelectDown or cursorColumnSelectUp which will give you the relevent keyboard shortcut. For me it is Shift+Alt+Down/Up Arrow

Spring security CORS Filter

I had a similar problem but with the specific requirement to have the CORS header set from decorators in our endpoints, like this:

@CrossOrigin(origins = "*", allowCredentials = "true")
@PostMapping(value = "/login")

Or

@CrossOrigin(origins = "*")
@GetMapping(value = "/verificationState")

So simply intercepting the request, setting the CORS header manually and sending 200 back was not an option, because allowCredentials was needed to be true in some cases and wildcards are not allowed then. Sure, a CORS registry would have helped, but since our clients are angular in capacitor on android and iOS, there is no specific domain to register. So the clean way to do - in my opinion - is to pipe preflights directly to the endpoints to let them handle it. I solved it with this:

@Component
public class PreflightFilter extends OncePerRequestFilter {

    private static final Logger logger = LoggerFactory.getLogger(PreflightFilter.class);

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {

        if (CorsUtils.isPreFlightRequest(request)) {
            logger.info("Preflight request accepted");
            SecurityContextHolder.getContext().setAuthentication(createPreflightToken(request));
        }
        chain.doFilter(request, response);
    }

    private UsernamePasswordAuthenticationToken createPreflightToken(HttpServletRequest request) {
        UserDetails userDetails = new User("Preflight", "",
                true, true, true, true,
                Stream.of(new SimpleGrantedAuthority("AppUser")).collect(Collectors.toSet()));
        UsernamePasswordAuthenticationToken preflightToken =
                new UsernamePasswordAuthenticationToken(
                        userDetails, null, userDetails.getAuthorities());
        preflightToken
                .setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
        return preflightToken;
    }
}

Keep in mind that the endpoint decorators don't work like wildcards here as one would expect!

What is the default Jenkins password?

Before installing jenkins, create a user named jenkins and set password there. Then after installing jenkins you can use the password you created.

What is the difference between server side cookie and client side cookie?

  1. Yes you can create cookies that can only be read on the server-side. These are called "HTTP Only" -cookies, as explained in other answers already

  2. No, there is no way (I know of) to create "cookies" that can be read only on the client-side. Cookies are meant to facilitate client-server communication.

  3. BUT, if you want something LIKE "client-only-cookies" there is a simple answer: Use "Local Storage".

Local Storage is actually syntactically simpler to use than cookies. A good simple summary of cookies vs. local storage can be found at:

https://courses.cs.washington.edu/courses/cse154/12au/lectures/slides/lecture21-client-storage.shtml#slide8

A point: You might use cookies created in JavaScript to store GUI-related things you only need on the client-side. BUT the cookie is sent to the server for EVERY request made, it becomes part of the http-request headers thus making the request contain more data and thus slower to send.

If your page has 50 resources like images and css-files and scripts then the cookie is (typically) sent with each request. More on this in Does every web request send the browser cookies?

Local storage does not have those data-transfer related disadvantages, it sends no data. It is great.

How can I pass parameters to a partial view in mvc 4

Here is an extension method that will convert an object to a ViewDataDictionary.

public static ViewDataDictionary ToViewDataDictionary(this object values)
{
    var dictionary = new ViewDataDictionary();
    foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(values))
    {
        dictionary.Add(property.Name, property.GetValue(values));
    }
    return dictionary;
}

You can then use it in your view like so:

@Html.Partial("_MyPartial", new
{
    Property1 = "Value1",
    Property2 = "Value2"
}.ToViewDataDictionary())

Which is much nicer than the new ViewDataDictionary { { "Property1", "Value1" } , { "Property2", "Value2" }} syntax.

Then in your partial view, you can use ViewBag to access the properties from a dynamic object rather than indexed properties, e.g.

<p>@ViewBag.Property1</p>
<p>@ViewBag.Property2</p>

Checking if a double (or float) is NaN in C++

nan prevention

My answer to this question is don't use retroactive checks for nan. Use preventive checks for divisions of the form 0.0/0.0 instead.

#include <float.h>
float x=0.f ;             // I'm gonna divide by x!
if( !x )                  // Wait! Let me check if x is 0
  x = FLT_MIN ;           // oh, since x was 0, i'll just make it really small instead.
float y = 0.f / x ;       // whew, `nan` didn't appear.

nan results from the operation 0.f/0.f, or 0.0/0.0. nan is a terrible nemesis to the stability of your code that must be detected and prevented very carefully1. The properties of nan that are different from normal numbers:

  • nan is toxic, (5*nan=nan)
  • nan is not equal to anything, not even itself (nan != nan)
  • nan not greater than anything (nan !> 0)
  • nan is not less than anything (nan !< 0)

The last 2 properties listed are counter-logical and will result in odd behavior of code that relies on comparisons with a nan number (the 3rd last property is odd too but you're probably not ever going to see x != x ? in your code (unless you are checking for nan (unreliably))).

In my own code, I noticed that nan values tend to produce difficult to find bugs. (Note how this is not the case for inf or -inf. (-inf < 0) returns TRUE, ( 0 < inf ) returns TRUE, and even (-inf < inf) returns TRUE. So, in my experience, the behavior of the code is often still as desired).

what to do under nan

What you want to happen under 0.0/0.0 must be handled as a special case, but what you do must depend on the numbers you expect to come out of the code.

In the example above, the result of (0.f/FLT_MIN) will be 0, basically. You may want 0.0/0.0 to generate HUGE instead. So,

float x=0.f, y=0.f, z;
if( !x && !y )    // 0.f/0.f case
  z = FLT_MAX ;   // biggest float possible
else
  z = y/x ;       // regular division.

So in the above, if x were 0.f, inf would result (which has pretty good/nondestructive behavior as mentioned above actually).

Remember, integer division by 0 causes a runtime exception. So you must always check for integer division by 0. Just because 0.0/0.0 quietly evaluates to nan doesn't mean you can be lazy and not check for 0.0/0.0 before it happens.

1 Checks for nan via x != x are sometimes unreliable (x != x being stripped out by some optimizing compilers that break IEEE compliance, specifically when the -ffast-math switch is enabled).

How do I execute .js files locally in my browser?

If you're using Google Chrome you can use the Chrome Dev Editor: https://github.com/dart-lang/chromedeveditor

Python matplotlib multiple bars

The trouble with using dates as x-values, is that if you want a bar chart like in your second picture, they are going to be wrong. You should either use a stacked bar chart (colours on top of each other) or group by date (a "fake" date on the x-axis, basically just grouping the data points).

import numpy as np
import matplotlib.pyplot as plt

N = 3
ind = np.arange(N)  # the x locations for the groups
width = 0.27       # the width of the bars

fig = plt.figure()
ax = fig.add_subplot(111)

yvals = [4, 9, 2]
rects1 = ax.bar(ind, yvals, width, color='r')
zvals = [1,2,3]
rects2 = ax.bar(ind+width, zvals, width, color='g')
kvals = [11,12,13]
rects3 = ax.bar(ind+width*2, kvals, width, color='b')

ax.set_ylabel('Scores')
ax.set_xticks(ind+width)
ax.set_xticklabels( ('2011-Jan-4', '2011-Jan-5', '2011-Jan-6') )
ax.legend( (rects1[0], rects2[0], rects3[0]), ('y', 'z', 'k') )

def autolabel(rects):
    for rect in rects:
        h = rect.get_height()
        ax.text(rect.get_x()+rect.get_width()/2., 1.05*h, '%d'%int(h),
                ha='center', va='bottom')

autolabel(rects1)
autolabel(rects2)
autolabel(rects3)

plt.show()

enter image description here

Getting the screen resolution using PHP

solution: make scalable web design ... ( our should i say proper web design) formating should be done client side and i did wish the info would be passed down to server but the info is still usefull ( how many object per rows kind of deal ) but still web design should be fluid thus each row elements should not be put into tables unless its an actual table ( and the data will scale to it's individual cells) if you use a div you can stack each elements next to each other and your window should "break" the row at the proper spot. ( just need proper css)

Java : Sort integer array without using Arrays.sort()

Simple sorting algorithm Bubble sort:

public static void main(String[] args) {
    int[] arr = new int[] { 6, 8, 7, 4, 312, 78, 54, 9, 12, 100, 89, 74 };

    for (int i = 0; i < arr.length; i++) {
        for (int j = i + 1; j < arr.length; j++) {
            int tmp = 0;
            if (arr[i] > arr[j]) {
                tmp = arr[i];
                arr[i] = arr[j];
                arr[j] = tmp;
            }
        }
    }
}

Summarizing multiple columns with dplyr?

For completeness: with dplyr v0.2 ddply with colwise will also do this:

> ddply(df, .(grp), colwise(mean))
  grp        a    b        c        d
1   1 4.333333 4.00 1.000000 2.000000
2   2 2.000000 2.75 2.750000 2.750000
3   3 3.000000 4.00 4.333333 3.666667

but it is slower, at least in this case:

> microbenchmark(ddply(df, .(grp), colwise(mean)), 
                  df %>% group_by(grp) %>% summarise_each(funs(mean)))
Unit: milliseconds
                                            expr      min       lq     mean
                ddply(df, .(grp), colwise(mean))     3.278002 3.331744 3.533835
 df %>% group_by(grp) %>% summarise_each(funs(mean)) 1.001789 1.031528 1.109337

   median       uq      max neval
 3.353633 3.378089 7.592209   100
 1.121954 1.133428 2.292216   100

connecting MySQL server to NetBeans

  1. Close NetBeans.

  2. Stop MySQL Server.

  3. Update MySQL (if available)

  4. Start MySQL Server.

  5. Open NetBeans.

If still doesn't connect, download MySQL Connector/J and add mysql-connector-java-[version].jar to your classpath and also to your Webserver's lib directory. For instance, Tomcat lib path in XAMPP is
C:\xampp\tomcat\lib.
Then repeat the steps again.

How to execute .sql file using powershell?

Here is a function that I have in my PowerShell profile for loading SQL snapins:

function Load-SQL-Server-Snap-Ins
{
    try 
    {
        $sqlpsreg="HKLM:\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.SqlServer.Management.PowerShell.sqlps"

        if (!(Test-Path $sqlpsreg -ErrorAction "SilentlyContinue"))
        {
            throw "SQL Server Powershell is not installed yet (part of SQLServer installation)."
        }

        $item = Get-ItemProperty $sqlpsreg
        $sqlpsPath = [System.IO.Path]::GetDirectoryName($item.Path)

        $assemblyList = @(
            "Microsoft.SqlServer.Smo",
            "Microsoft.SqlServer.SmoExtended",
            "Microsoft.SqlServer.Dmf",
            "Microsoft.SqlServer.WmiEnum",
            "Microsoft.SqlServer.SqlWmiManagement",
            "Microsoft.SqlServer.ConnectionInfo ",
            "Microsoft.SqlServer.Management.RegisteredServers",
            "Microsoft.SqlServer.Management.Sdk.Sfc",
            "Microsoft.SqlServer.SqlEnum",
            "Microsoft.SqlServer.RegSvrEnum",
            "Microsoft.SqlServer.ServiceBrokerEnum",
            "Microsoft.SqlServer.ConnectionInfoExtended",
            "Microsoft.SqlServer.Management.Collector",
            "Microsoft.SqlServer.Management.CollectorEnum"
        )

        foreach ($assembly in $assemblyList)
        { 
            $assembly = [System.Reflection.Assembly]::LoadWithPartialName($assembly) 
            if ($assembly -eq $null)
                { Write-Host "`t`t($MyInvocation.InvocationName): Could not load $assembly" }
        }

        Set-Variable -scope Global -name SqlServerMaximumChildItems -Value 0
        Set-Variable -scope Global -name SqlServerConnectionTimeout -Value 30
        Set-Variable -scope Global -name SqlServerIncludeSystemObjects -Value $false
        Set-Variable -scope Global -name SqlServerMaximumTabCompletion -Value 1000

        Push-Location

         if ((Get-PSSnapin -Name SqlServerProviderSnapin100 -ErrorAction SilentlyContinue) -eq $null) 
        { 
            cd $sqlpsPath

            Add-PsSnapin SqlServerProviderSnapin100 -ErrorAction Stop
            Add-PsSnapin SqlServerCmdletSnapin100 -ErrorAction Stop
            Update-TypeData -PrependPath SQLProvider.Types.ps1xml
            Update-FormatData -PrependPath SQLProvider.Format.ps1xml
        }
    } 

    catch 
    {
        Write-Host "`t`t$($MyInvocation.InvocationName): $_" 
    }

    finally
    {
        Pop-Location
    }
}

JQuery Ajax - How to Detect Network Connection error when making Ajax call

USE

xhr.onerror = function(e){
    if (XMLHttpRequest.readyState == 4) {
        // HTTP error (can be checked by XMLHttpRequest.status and XMLHttpRequest.statusText)
        selFoto.erroUploadFoto('Erro HTTP: '+XMLHttpRequest.statusText);
    }
    else if (XMLHttpRequest.readyState == 0) {
        // Network error (i.e. connection refused, access denied due to CORS, etc.)
        selFoto.erroUploadFoto('Erro de rede:'+XMLHttpRequest.statusText);
    }
    else {
        selFoto.erroUploadFoto('Erro desconhecido.');
    }

};

(more code below - UPLOAD IMAGE EXAMPLE)

var selFoto = {
   foto: null,

   upload: function(){
        LoadMod.show();

        var arquivo = document.frmServico.fileupload.files[0];
        var formData = new FormData();

        if (arquivo.type.match('image.*')) {
            formData.append('upload', arquivo, arquivo.name);

            var xhr = new XMLHttpRequest();
            xhr.open('POST', 'FotoViewServlet?acao=uploadFoto', true);
            xhr.responseType = 'blob';

            xhr.onload = function(e){
                if (this.status == 200) {
                    selFoto.foto = this.response;
                    var url = window.URL || window.webkitURL;
                    document.frmServico.fotoid.src = url.createObjectURL(this.response);
                    $('#foto-id').show();
                    $('#div_upload_foto').hide();           
                    $('#div_master_upload_foto').css('background-color','transparent');
                    $('#div_master_upload_foto').css('border','0');

                    Dados.foto = document.frmServico.fotoid;
                    LoadMod.hide();
                }
                else{
                    erroUploadFoto(XMLHttpRequest.statusText);
                }

                if (XMLHttpRequest.readyState == 4) {
                     selFoto.erroUploadFoto('Erro HTTP: '+XMLHttpRequest.statusText);
                }
                else if (XMLHttpRequest.readyState == 0) {
                     selFoto.erroUploadFoto('Erro de rede:'+XMLHttpRequest.statusText);                             
                }

            };

            xhr.onerror = function(e){
            if (XMLHttpRequest.readyState == 4) {
                // HTTP error (can be checked by XMLHttpRequest.status and XMLHttpRequest.statusText)
                selFoto.erroUploadFoto('Erro HTTP: '+XMLHttpRequest.statusText);
            }
            else if (XMLHttpRequest.readyState == 0) {
                 // Network error (i.e. connection refused, access denied due to CORS, etc.)
                 selFoto.erroUploadFoto('Erro de rede:'+XMLHttpRequest.statusText);
            }
            else {
                selFoto.erroUploadFoto('Erro desconhecido.');
            }
        };

        xhr.send(formData);
     }
     else{
        selFoto.erroUploadFoto('');                         
        MyCity.mensagens.push('Selecione uma imagem.');
        MyCity.showMensagensAlerta();
     }
  }, 

  erroUploadFoto : function(mensagem) {
        selFoto.foto = null;
        $('#file-upload').val('');
        LoadMod.hide();
        MyCity.mensagens.push('Erro ao atualizar a foto. '+mensagem);
        MyCity.showMensagensAlerta();
 }
 };

How to get IP address of running docker container

You can not access the docker's IP from outside of that host machine. If your browser is on another machine better to map the host port to container port by passing -p 8080:8080 to run command.

Passing -p you can map host port to container port and a proxy is set to forward all traffix for said host port to designated container port.

Catch an exception thrown by an async void method

It's somewhat weird to read but yes, the exception will bubble up to the calling code - but only if you await or Wait() the call to Foo.

public async Task Foo()
{
    var x = await DoSomethingAsync();
}

public async void DoFoo()
{
    try
    {
        await Foo();
    }
    catch (ProtocolException ex)
    {
          // The exception will be caught because you've awaited
          // the call in an async method.
    }
}

//or//

public void DoFoo()
{
    try
    {
        Foo().Wait();
    }
    catch (ProtocolException ex)
    {
          /* The exception will be caught because you've
             waited for the completion of the call. */
    }
} 

Async void methods have different error-handling semantics. When an exception is thrown out of an async Task or async Task method, that exception is captured and placed on the Task object. With async void methods, there is no Task object, so any exceptions thrown out of an async void method will be raised directly on the SynchronizationContext that was active when the async void method started. - https://msdn.microsoft.com/en-us/magazine/jj991977.aspx

Note that using Wait() may cause your application to block, if .Net decides to execute your method synchronously.

This explanation http://www.interact-sw.co.uk/iangblog/2010/11/01/csharp5-async-exceptions is pretty good - it discusses the steps the compiler takes to achieve this magic.

Which selector do I need to select an option by its text?

I faced the same issue below is the working code :

$("#test option").filter(function() {
    return $(this).text() =='Ford';
}).prop("selected", true);

Demo : http://jsfiddle.net/YRBrp/83/

How to copy part of an array to another array in C#?

See this question. LINQ Take() and Skip() are the most popular answers, as well as Array.CopyTo().

A purportedly faster extension method is described here.

Adding class to element using Angular JS

querySelector is not from Angular but it's in document and it's in all DOM elements (expensive). You can use ng-class or inside directive add addClass on the element:

myApp.directive('yourDirective', [function(){
    return {
        restrict: 'A',
        link: function(scope, elem, attrs) {
            // Remove class
            elem.addClass("my-class"); 
        }
    }
}

Convert Object to JSON string

Convert JavaScript object to json data

$("form").submit(function(event){
  event.preventDefault();
  var formData = $("form").serializeArray(); // Create array of object
  var jsonConvertedData = JSON.stringify(formData);  // Convert to json
  consol.log(jsonConvertedData);
});

You can validate json data using http://jsonlint.com

How can I check the current status of the GPS receiver?

I may be wrong but it seems people seem to be going way off-topic for

i just need to know if the gps icon at the top of the screen is blinking (no actual fix)

That is easily done with

LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean gps_on = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);

To see if you have a solid fix, things get a little trickier:

public class whatever extends Activity {
    LocationManager lm;
    Location loc;
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);        
        lm = (LocationManager) getSystemService(LOCATION_SERVICE);
        loc = null;
        request_updates();        
    }

    private void request_updates() {
        if (lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            // GPS is enabled on device so lets add a loopback for this locationmanager
            lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,0, 0, locationListener);
        }      
    }

    LocationListener locationListener = new LocationListener() {
        public void onLocationChanged(Location location) {
            // Each time the location is changed we assign loc
            loc = location;
        }

         // Need these even if they do nothing. Can't remember why.
         public void onProviderDisabled(String arg0) {}
         public void onProviderEnabled(String provider) {}
         public void onStatusChanged(String provider, int status, Bundle extras) {}
    };

Now whenever you want to see if you have fix?

if (loc != null){
    // Our location has changed at least once
    blah.....
}

If you want to be fancy you can always have a timeout using System.currentTimeMillis() and loc.getTime()

Works reliably, at least on an N1 since 2.1.

Replace deprecated preg_replace /e with preg_replace_callback

You can use an anonymous function to pass the matches to your function:

$result = preg_replace_callback(
    "/\{([<>])([a-zA-Z0-9_]*)(\?{0,1})([a-zA-Z0-9_]*)\}(.*)\{\\1\/\\2\}/isU",
    function($m) { return CallFunction($m[1], $m[2], $m[3], $m[4], $m[5]); },
    $result
);

Apart from being faster, this will also properly handle double quotes in your string. Your current code using /e would convert a double quote " into \".

How to publish a Web Service from Visual Studio into IIS?

If using Visual Studio 2010 you can right-click on the project for the service, and select properties. Then select the Web tab. Under the Servers section you can configure the URL. There is also a button to create the virtual directory.

How can I let a user download multiple files when a button is clicked?

//It is possible when using Tampermonkey (Firefox or Chrome).
//They added the GM_Download command.
//You can use it like this download multiple files One time:


// ==UserScript==
// @name        
// @description 
// @match       
// @grant       
// @grant       GM_download
function setup_reader(file) {
    var name = file.name;
    var reader = new FileReader();
    reader.onload = function (e) {
        var bin = e.target.result; //get file content
        var lines = bin.split('\n');
        for (var line = 0; line < lines.length; line++) {
            console.log(lines[line]);
            GM_download(lines[line], line + '.jpg');
        }
    }
    // reader.readAsBinaryString(file);
    reader.readAsText(file, 'utf-8');//
}

How to split a single column values to multiple column values?

What you need is a split user-defined function. With that, the solution looks like

With SplitValues As
    (
    Select T.Name, Z.Position, Z.Value
        , Row_Number() Over ( Partition By T.Name Order By Z.Position ) As Num
    From Table As T
        Cross Apply dbo.udf_Split( T.Name, ' ' ) As Z
    )
Select Name
    , FirstName.Value
    , Case When ThirdName Is Null Then SecondName Else ThirdName End As LastName
From SplitValues As FirstName
    Left Join SplitValues As SecondName
        On S2.Name = S1.Name
            And S2.Num = 2
    Left Join SplitValues As ThirdName
        On S2.Name = S1.Name
            And S2.Num = 3
Where FirstName.Num = 1

Here's a sample split function:

Create Function [dbo].[udf_Split]
(   
    @DelimitedList nvarchar(max)
    , @Delimiter nvarchar(2) = ','
)
RETURNS TABLE 
AS
RETURN 
    (
    With CorrectedList As
        (
        Select Case When Left(@DelimitedList, Len(@Delimiter)) <> @Delimiter Then @Delimiter Else '' End
            + @DelimitedList
            + Case When Right(@DelimitedList, Len(@Delimiter)) <> @Delimiter Then @Delimiter Else '' End
            As List
            , Len(@Delimiter) As DelimiterLen
        )
        , Numbers As 
        (
        Select TOP( Coalesce(DataLength(@DelimitedList)/2,0) ) Row_Number() Over ( Order By c1.object_id ) As Value
        From sys.columns As c1
            Cross Join sys.columns As c2
        )
    Select CharIndex(@Delimiter, CL.list, N.Value) + CL.DelimiterLen As Position
        , Substring (
                    CL.List
                    , CharIndex(@Delimiter, CL.list, N.Value) + CL.DelimiterLen     
                    , CharIndex(@Delimiter, CL.list, N.Value + 1)                           
                        - ( CharIndex(@Delimiter, CL.list, N.Value) + CL.DelimiterLen ) 
                    ) As Value
    From CorrectedList As CL
        Cross Join Numbers As N
    Where N.Value <= DataLength(CL.List) / 2
        And Substring(CL.List, N.Value, CL.DelimiterLen) = @Delimiter
    )

What values can I pass to the event attribute of the f:ajax tag?

I just input some value that I knew was invalid and here is the output:

'whatToInput' is not a supported event for HtmlPanelGrid. Please specify one of these supported event names: click, dblclick, keydown, keypress, keyup, mousedown, mousemove, mouseout, mouseover, mouseup.

So values you can pass to event are

  • click
  • dblclick
  • keydown
  • mousedown
  • mousemove
  • mouseover
  • mouseup

How to encrypt and decrypt String with my passphrase in Java (Pc not mobile platform)?

Both Encrypt and Decrypt with AES and DES Algoritham ,This worked for me perfectly GithubLink: Java Code For Encryption and Decryption

package decrypt;

import java.security.Key;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
/* Decrypt encrypted string into plain string with aes and Des algoritham*/ 

public class Decrypt {

public String decrypt(String str,String k) throws Exception {
// Decode base64 to get bytes

 Cipher  dcipher = Cipher.getInstance("AES");
 Key aesKey = new SecretKeySpec(k.getBytes(), "AES");
 dcipher.init(dcipher.DECRYPT_MODE, aesKey);
//System.out.println(aesKey);
byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
byte[] utf8 = dcipher.doFinal(dec);
//System.out.println(utf8);
// Decode using utf-8
 return new String(utf8, "UTF8");
 }


  public String encrypt(String str,String k) throws Exception {
 Cipher ecipher = Cipher.getInstance("AES");
 Key aeskey = new SecretKeySpec(k.getBytes(),"AES");
 byte[] utf8 = str.getBytes("UTF8");
 ecipher.init(ecipher.ENCRYPT_MODE, aeskey );

 byte[] enc = ecipher.doFinal(utf8);

 return new sun.misc.BASE64Encoder().encode(enc);

}
 public String encrypt(String str,String k,String Algo) throws Exception {
 Cipher ecipher = Cipher.getInstance(Algo);
 Key aeskey = new SecretKeySpec(k.getBytes(),Algo);
 byte[] utf8 = str.getBytes("UTF8");
 ecipher.init(ecipher.ENCRYPT_MODE, aeskey );

 byte[] enc = ecipher.doFinal(utf8);

 return new sun.misc.BASE64Encoder().encode(enc);

}
public String decrypt(String str,String k,String Algo) throws Exception {
    // Decode base64 to get bytes

     Cipher  dcipher = Cipher.getInstance(Algo);
     Key aesKey = new SecretKeySpec(k.getBytes(), Algo);
     dcipher.init(dcipher.DECRYPT_MODE, aesKey);
    //System.out.println(aesKey);
    byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
    byte[] utf8 = dcipher.doFinal(dec);
    //System.out.println(utf8);
 // Decode using utf-8
     return new String(utf8, "UTF8");
  }

public static void main(String args []) throws Exception
{
    String original = "rakesh";
    String data = "CfPcX0G+e7TLKKMyyvrvrQ==";
    String k = "qertyuiopasdfghw"; //AES key length must be 16
    String k1 = "qertyuio";  // DES key length must be 8 
    String data1 = "rakesh";
    String data2 = "nAtvNq7uHKE=";
    String Algo= "DES";
    String Algo1= "AES";
    Decrypt decrypter = new Decrypt();
     System.out.println("Original String: " + original);

     System.out.println("encrypted String in DES: " + decrypter.encrypt(data1, 
      k1,Algo));
     System.out.println("Decrypted String in DES: " + decrypter.decrypt(data2, 
       k1,Algo));
     System.out.println("encrypted String in AES: " + decrypter.encrypt(data1, 
      k,Algo1));
     System.out.println("Decrypted String in AES: " + decrypter.decrypt(data, 
      k,Algo1));
   }
}

Getting the last element of a list

You can also use the code below, if you do not want to get IndexError when the list is empty.

next(reversed(some_list), None)

Unable to connect to mongodb Error: couldn't connect to server 127.0.0.1:27017 at src/mongo/shell/mongo.js:L112

I had the same issue, In my case there was a mismatch of ipaddress in mongo config

~# mongo
MongoDB shell version: 2.6.7
connecting to: test
2015-02-02T17:48:52.302+0530 warning: Failed to connect to 127.0.0.1:27017, reason: errno:111 Connection refused
2015-02-02T17:48:52.303+0530 Error: couldn't connect to server 127.0.0.1:27017 (127.0.0.1), connection attempt failed at src/mongo/shell/mongo.js:146
exception: connect failed

When I checked my configuration file, I have specified the bind address to eth0 ip(10.8.10.111) not loopback address(127.0.0.1), So I have changed the ip address to loopback as like bind_ip = 127.0.0.1 in /etc/mongod.conf file and restart it with service mongod restart, finally works

# mongo 
MongoDB shell version: 2.6.7
connecting to: test
> 

How do you create a hidden div that doesn't create a line break or horizontal space?

_x000D_
_x000D_
display: none;
_x000D_
_x000D_
_x000D_

This should make the element disappear and not take up any space.

How do I compile the asm generated by GCC?

You can use GAS, which is gcc's backend assembler:

http://linux.die.net/man/1/as

Datatables warning(table id = 'example'): cannot reinitialise data table

Try adding "bDestroy": true to the options object literal, e.g.

$('#dataTable').dataTable({
    ...
    ....
    "bDestroy": true
});

Source: iodocs.com

or Remove the first:

$(document).ready(function() {
    $('#example').dataTable();
} );

In your case is the best option vjk.

How do I split a multi-line string into multiple lines?

inputString.splitlines()

Will give you a list with each item, the splitlines() method is designed to split each line into a list element.

How to convert NSData to byte array in iPhone?

Already answered, but to generalize to help other readers:

    //Here:   NSData * fileData;
    uint8_t * bytePtr = (uint8_t  * )[fileData bytes];

    // Here, For getting individual bytes from fileData, uint8_t is used.
    // You may choose any other data type per your need, eg. uint16, int32, char, uchar, ... .
    // Make sure, fileData has atleast number of bytes that a single byte chunk would need. eg. for int32, fileData length must be > 4 bytes. Makes sense ?

    // Now, if you want to access whole data (fileData) as an array of uint8_t
    NSInteger totalData = [fileData length] / sizeof(uint8_t);

    for (int i = 0 ; i < totalData; i ++)
    {
        NSLog(@"data byte chunk : %x", bytePtr[i]);
    }

Splitting dataframe into multiple dataframes

In addition to Gusev Slava's answer, you might want to use groupby's groups:

{key: df.loc[value] for key, value in df.groupby("name").groups.items()}

This will yield a dictionary with the keys you have grouped by, pointing to the corresponding partitions. The advantage is that the keys are maintained and don't vanish in the list index.

Recommended method for escaping HTML in Java

While @dfa answer of org.apache.commons.lang.StringEscapeUtils.escapeHtml is nice and I have used it in the past it should not be used for escaping HTML (or XML) attributes otherwise the whitespace will be normalized (meaning all adjacent whitespace characters become a single space).

I know this because I have had bugs filed against my library (JATL) for attributes where whitespace was not preserved. Thus I have a drop in (copy n' paste) class (of which I stole some from JDOM) that differentiates the escaping of attributes and element content.

While this may not have mattered as much in the past (proper attribute escaping) it is increasingly become of greater interest given the use use of HTML5's data- attribute usage.

Cannot issue data manipulation statements with executeQuery()

This code works for me: I set values whit an INSERT and get the LAST_INSERT_ID() of this value whit a SELECT; I use java NetBeans 8.1, MySql and java.JDBC.driver

                try {

        String Query = "INSERT INTO `stock`(`stock`, `min_stock`,   
                `id_stock`) VALUES ("

                + "\"" + p.get_Stock().getStock() + "\", "
                + "\"" + p.get_Stock().getStockMinimo() + "\","
                + "" + "null" + ")";

        Statement st = miConexion.createStatement();
        st.executeUpdate(Query);

        java.sql.ResultSet rs;
        rs = st.executeQuery("Select LAST_INSERT_ID() from stock limit 1");                
        rs.next(); //para posicionar el puntero en la primer fila
        ultimo_id = rs.getInt("LAST_INSERT_ID()");
        } catch (SqlException ex) { ex.printTrace;}

How to Change color of Button in Android when Clicked?

If you want to change the backgorund image or color of the button when it is pressed, then just copy this code and paste in your project at exact location described below.

      <!-- Create new xml file like mybtn_layout.xml file in drawable -->
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@drawable/pressed" /> <!--pressed --> 
<item android:drawable="@drawable/normal" /> <!-- Normal -->
</selector>
  <!-- Now this file should be in a drawable folder and use this 
  single line code in    button code to get all the properties of this xml file -->

    <Button
      android:id="@+id/street_btn"
      android:layout_width="wrap_content"
      android:background="@drawable/layout_a" > <!-- your required code -->
    </Button>

Read an Excel file directly from a R script

library(RODBC)
file.name <- "file.xls"
sheet.name <- "Sheet Name"

## Connect to Excel File Pull and Format Data
excel.connect <- odbcConnectExcel(file.name)
dat <- sqlFetch(excel.connect, sheet.name, na.strings=c("","-"))
odbcClose(excel.connect)

Personally, I like RODBC and can recommend it.

Difference between dangling pointer and memory leak

A dangling pointer points to memory that has already been freed. The storage is no longer allocated. Trying to access it might cause a Segmentation fault.

Common way to end up with a dangling pointer:

char *func()
{
   char str[10];
   strcpy(str, "Hello!");
   return str; 
}
//returned pointer points to str which has gone out of scope. 

You are returning an address which was a local variable, which would have gone out of scope by the time control was returned to the calling function. (Undefined behaviour)

Another common dangling pointer example is an access of a memory location via pointer, after free has been explicitly called on that memory.

int *c = malloc(sizeof(int));
free(c);
*c = 3; //writing to freed location!

A memory leak is memory which hasn't been freed, there is no way to access (or free it) now, as there are no ways to get to it anymore. (E.g. a pointer which was the only reference to a memory location dynamically allocated (and not freed) which points somewhere else now.)

void func(){
    char *ch = malloc(10);
}
//ch not valid outside, no way to access malloc-ed memory

Char-ptr ch is a local variable that goes out of scope at the end of the function, leaking the dynamically allocated 10 bytes.

Angular2 router (@angular/router), how to set default route?

Suppose you want to load RegistrationComponent on load and then ConfirmationComponent on some event click on RegistrationComponent.

So in appModule.ts, you can write like this.

RouterModule.forRoot([
      { 
        path: '', 
        redirectTo: 'registration', 
        pathMatch: 'full'
       },
       { 
        path: 'registration', 
        component: RegistrationComponent
       },
      {
        path : 'confirmation',
        component: ConfirmationComponent
      }
    ]) 

OR

RouterModule.forRoot([
       { 
        path: '', 
        component: RegistrationComponent
       },
      {
        path : 'confirmation',
        component: ConfirmationComponent
      }
    ]) 

is also fine. Choose whatever you like.

Jquery: How to check if the element has certain css class/style

if ($("element class or id name").css("property") == "value") {
    your code....
}

Adding elements to a collection during iteration

Given a list List<Object> which you want to iterate over, the easy-peasy way is:

while (!list.isEmpty()){
   Object obj = list.get(0);

   // do whatever you need to
   // possibly list.add(new Object obj1);

   list.remove(0);
}

So, you iterate through a list, always taking the first element and then removing it. This way you can append new elements to the list while iterating.

How can I commit files with git?

The command for commiting all changed files:

git commit -a -m 'My commit comments'

-a = all edited files

-m = following string is a comment.

This will commit to your local drives / folders repo. If you want to push your changes to a git server / remotely hosted server, after the above command type:

git push

GitHub's cheat sheet is quite handy.

Running a script inside a docker container using shell script

If you want to run the same command on multiple instances you can do this :

for i in c1 dm1 dm2 ds1 ds2 gtm_m gtm_sl; do docker exec -it $i /bin/bash -c "service sshd start"; done

SVN Commit failed, access forbidden

Actually, I had this problem same as you. My windows is server 2008 and my subversion info is :

TortoiseSVN 1.7.6, Build 22632 - 64 Bit , 2012/03/08 18:29:39 Subversion 1.7.4, apr 1.4.5 apr-utils 1.3.12 neon 0.29.6 OpenSSL 1.0.0g 18 Jan 2012 zlib 1.2.5

I used this way and I solved this problem. I used [group] option. this option makes problem. I rewrite authz file contents. I remove group option. and I set one by one. I use well.

Thanks for reading.

How do I create a readable diff of two spreadsheets using git diff?

I have found xdocdiff WinMerge Plugin. It is a plugin for WinMerge (both OpenSource and Freeware, you doesn't need to write a VBA nor save an excel to csv or xml). It works just for the celd's contains.

This plugin supports also:

  • .rtf Rich Text
  • .docx/.docm Microsoft WORD 2007(OOXML)
  • .xlsx/.xlsm Microsoft Excel 2007(OOXML)
  • .pptx/.pptm Microsoft PowerPoint 2007(OOXML)
  • .doc Microsoft WORD ver5.0/95/97/2000/XP/2003
  • .xls Microsoft Excel ver5.0/95/97/2000/XP/2003
  • .ppt Microsoft PowerPoint 97/2000/XP/2003
  • .sxw/.sxc/.sxi/.sxd OpenOffice.org
  • .odt/.ods/.odp/.odg Open Document
  • .wj2/wj3/wk3/wk4/123 Lotus 123
  • .wri Windows3.1 Write
  • .pdf Adobe PDF
  • .mht Web Archive
  • .eml Exported files from OutlookExpress

Regard, Andres

How do I fix the indentation of an entire file in Vi?

Before pasting into the terminal, try :set paste and then :set nopaste after you're done. This will turn off the auto-indent, line-wrap and other features that are messing up your paste.

edit: Also, I should point out that a much better result than = indenting can usually be obtained by using an external program. For example, I run :%!perltidy all the time. astyle, cindent, etc. can also be used. And, of course, you can map those to a key stroke, and map different ones to the same keystroke depending on file type.

Apache Tomcat :java.net.ConnectException: Connection refused

I'd like to add another reason that "catalina.sh" won't be able to connect to port 8005, apart from a firewall or a change in "server.xml": It takes Tomcat time to start listening on port 8005.

It's easy to reproduce this scenario If you start Tomcat and try to stop it immediately. Wait a few minutes and you'll see that the problem disappears because the port has opened.

How to get the Facebook user id using the access token

You just have to hit another Graph API:

https://graph.facebook.com/me?access_token={access-token}

It will give your e-mail Id and user Id (for Facebook) also.

How to apply multiple transforms in CSS?

Transform Rotate and Translate in single line css:-How?

_x000D_
_x000D_
div.className{_x000D_
    transform : rotate(270deg) translate(-50%, 0);    _x000D_
    -webkit-transform: rotate(270deg) translate(-50%, -50%);    _x000D_
    -moz-transform: rotate(270deg) translate(-50%, -50%);    _x000D_
    -ms-transform: rotate(270deg) translate(-50%, -50%);    _x000D_
    -o-transform: rotate(270deg) translate(-50%, -50%); _x000D_
    float:left;_x000D_
    position:absolute;_x000D_
    top:50%;_x000D_
    left:50%;_x000D_
    }
_x000D_
<html>_x000D_
<head>_x000D_
</head>_x000D_
<body>_x000D_
<div class="className">_x000D_
  <span style="font-size:50px">A</span>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

What's the difference between a POST and a PUT HTTP REQUEST?

Actually there's no difference other than their title. There's actually a basic difference between GET and the others. With a "GET"-Request method, you send the data in the url-address-line, which are separated first by a question-mark, and then with a & sign.

But with a "POST"-request method, you can't pass data through the url, but you have to pass the data as an object in the so called "body" of the request. On the server side, you have then to read out the body of the received content in order to get the sent data. But there's on the other side no possibility to send content in the body, when you send a "GET"-Request.

The claim, that "GET" is only for getting data and "POST" is for posting data, is absolutely wrong. Noone can prevent you from creating new content, deleting existing content, editing existing content or do whatever in the backend, based on the data, that is sent by the "GET" request or by the "POST" request. And nobody can prevent you to code the backend in a way, that with a "POST"-Request, the client asks for some data.

With a request, no matter which method you use, you call a URL and send or don't send some data to specify, which information you want to pass to the server to deal with your request, and then the client gets an answer from the server. The data can contain whatever you want to send, the backend is allowed to do whatever it wants with the data and the response can contain any information, that you want to put in there.

There are only these two BASIC METHODS. GET and POST. But it's their structure, which makes them different and not what you code in the backend. In the backend you can code whatever you want to, with the received data. But with the "POST"-request you have to send/retrieve the data in the body and not in the url-addressline, and with a "GET" request, you have to send/retrieve data in the url-addressline and not in the body. That's all.

All the other methods, like "PUT", "DELETE" and so on, they have the same structure as "POST".

The POST Method is mainly used, if you want to hide the content somewhat, because whatever you write in the url-addressline, this will be saved in the cache and a GET-Method is the same as writing a url-addressline with data. So if you want to send sensitive data, which is not always necessarily username and password, but for example some ids or hashes, which you don't want to be shown in the url-address-line, then you should use the POST method.

Also the URL-Addressline's length is limited to 1024 symbols, whereas the "POST"-Method is not restricted. So if you have a bigger amount of data, you might not be able to send it with a GET-Request, but you'll need to use the POST-Request. So this is also another plus point for the POST-request.

But dealing with the GET-request is way easier, when you don't have complicated text to send. Otherwise, and this is another plus point for the POST method, is, that with the GET-method you need to url-encode the text, in order to be able to send some symbols within the text or even spaces. But with a POST method you have no restrictions and your content doesn't need to be changed or manipulated in any way.

How can I enter latitude and longitude in Google Maps?

for higher precision. this format:

45 11.735N,004 34.281E

and this

45 23.623, 5 38.77

Font size of TextView in Android application changes on changing font size from native settings

Use the dimension type of resources like you use string resources (DOCS).

In your dimens.xml file, declare your dimension variables:

<?xml version="1.0" encoding="utf-8"?>
<resources>
  <dimen name="textview_height">25dp</dimen>
  <dimen name="textview_width">150dp</dimen>
  <dimen name="ball_radius">30dp</dimen>
  <dimen name="font_size">16sp</dimen>
</resources>

Then you can use these values like this:

<TextView
   android:layout_height="@dimen/textview_height"
   android:layout_width="@dimen/textview_width"
   android:textSize="@dimen/font_size"/>

You can declare different dimens.xml files for different types of screens. Doing this will guarantee the desired look of your app on different devices.

When you don't specify android:textSize the system uses the default values.

Restricting JTextField input to Integers

I can't believe I haven't found this simple solution anywhere on stack overflow yet, it is by far the most useful. Changing the Document or DocumentFilter does not work for JFormattedTextField. Peter Tseng's answer comes very close.

NumberFormat longFormat = NumberFormat.getIntegerInstance();

NumberFormatter numberFormatter = new NumberFormatter(longFormat);
numberFormatter.setValueClass(Long.class); //optional, ensures you will always get a long value
numberFormatter.setAllowsInvalid(false); //this is the key!!
numberFormatter.setMinimum(0l); //Optional

JFormattedTextField field = new JFormattedTextField(numberFormatter);