Programs & Examples On #Omml

Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0

Somehow I had the wrong versions of the DLLs registered in my project.

  • I removed the three references to the Crystal Report dlls from my project. Crystal DLLs
  • I right click References, and click Add Reference
  • In the popup window, I click the Browse menu on the left and the Browse button Reference Manager
  • In the Directory window where your DLLs reside (perhaps your application's bin directory), select the three Crystal Reports DLLs and then click Add. DLLs
  • Back at the Reference Manager window, click in the first column to the left of the three Crystal dlls, and then click OK enter image description here
  • At this point your Crystal Reports should work again.

Python Math - TypeError: 'NoneType' object is not subscriptable

lista = list.sort(lista)

This should be


The .sort() method is in-place, and returns None. If you want something not in-place, which returns a value, you could use

sorted_list = sorted(lista)

Aside #1: please don't call your lists list. That clobbers the builtin list type.

Aside #2: I'm not sure what this line is meant to do:

print str("value 1a")+str(" + ")+str("value 2")+str(" = ")+str("value 3a ")+str("value 4")+str("\n")

is it simply

print "value 1a + value 2 = value 3a value 4"

? In other words, I don't know why you're calling str on things which are already str.

Aside #3: sometimes you use print("something") (Python 3 syntax) and sometimes you use print "something" (Python 2). The latter would give you a SyntaxError in py3, so you must be running 2.*, in which case you probably don't want to get in the habit or you'll wind up printing tuples, with extra parentheses. I admit that it'll work well enough here, because if there's only one element in the parentheses it's not interpreted as a tuple, but it looks strange to the pythonic eye..

The exception TypeError: 'NoneType' object is not subscriptable happens because the value of lista is actually None. You can reproduce TypeError that you get in your code if you try this at the Python command line:


The reason that lista gets set to None is because the return value of list.sort() is None... it does not return a sorted copy of the original list. Instead, as the documentation points out, the list gets sorted in-place instead of a copy being made (this is for efficiency reasons).

If you do not want to alter the original version you can use

other_list = sorted(lista)

localhost refused to connect Error in visual studio

I was having this issue and solved it by closing all open instances of Visual Studio.

Static class initializer in PHP

If you don't like public static initializer, reflection can be a workaround.


class LanguageUtility
    public static function initializeClass($class)
            // Get a static method named 'initialize'. If not found,
            // ReflectionMethod() will throw a ReflectionException.
            $ref = new \ReflectionMethod($class, 'initialize');

            // The 'initialize' method is probably 'private'.
            // Make it accessible before calling 'invoke'.
            // Note that 'setAccessible' is not available
            // before PHP version 5.3.2.

            // Execute the 'initialize' method.
        catch (Exception $e)

class MyClass
    private static function initialize()



Running windows shell commands with python

Simple Import os package and run below command.

import os

Binding an Image in WPF MVVM

Displaying an Image in WPF is much easier than that. Try this:

<Image Source="{Binding DisplayedImagePath}" HorizontalAlignment="Left" 
    Margin="0,0,0,0" Name="image1" Stretch="Fill" VerticalAlignment="Bottom" 
    Grid.Row="8" Width="200"  Grid.ColumnSpan="2" />

And the property can just be a string:

public string DisplayedImage 
    get { return @"C:\Users\Public\Pictures\Sample Pictures\Chrysanthemum.jpg"; }

Although you really should add your images to a folder named Images in the root of your project and set their Build Action to Resource in the Properties Window in Visual Studio... you could then access them using this format:

public string DisplayedImage 
    get { return "/AssemblyName;component/Images/ImageName.jpg"; }


As a final tip... if you ever have a problem with a control not working as expected, simply type 'WPF', the name of that control and then the word 'class' into a search engine. In this case, you would have typed 'WPF Image Class'. The top result will always be MSDN and if you click on the link, you'll find out all about that control and most pages have code examples as well.

UPDATE 2 >>>

If you followed the examples from the link to MSDN and it's not working, then your problem is not the Image control. Using the string property that I suggested, try this:

    <Image Source="{Binding DisplayedImagePath}" />
    <TextBlock Text="{Binding DisplayedImagePath}" />

If you can't see the file path in the TextBlock, then you probably haven't set your DataContext to the instance of your view model. If you can see the text, then the problem is with your file path.

UPDATE 3 >>>

In .NET 4, the above Image.Source values would work. However, Microsoft made some horrible changes in .NET 4.5 that broke many different things and so in .NET 4.5, you'd need to use the full pack path like this:

<Image Source="pack://application:,,,/AssemblyName;component/Images/image_to_use.png">

For further information on pack URIs, please see the Pack URIs in WPF page on Microsoft Docs.

Append same text to every cell in a column in Excel

Type it in one cell, copy that cell, select all the cells you want to fill, and paste.

Alternatively, type it in one cell, select the black square in the bottom-right of that cell, and drag down.

how can I check if a file exists?

Start with this:

Set fso = CreateObject("Scripting.FileSystemObject")
If (fso.FileExists(path)) Then
   msg = path & " exists."
   msg = path & " doesn't exist."
End If

Taken from the documentation.

What is the proper way to check if a string is empty in Perl?

  1. Due to the way that strings are stored in Perl, getting the length of a string is optimized.
    if (length $str) is a good way of checking that a string is non-empty.

  2. If you're in a situation where you haven't already guarded against undef, then the catch-all for "non-empty" that won't warn is if (defined $str and length $str).

How to have Java method return generic list of any type?

Another option is doing the following:

public class UserList extends List<User>{


public <T> T magicalListGetter(Class<T> clazz) {
    List<?> list = doMagicalVooDooHere();
    return (T)list;

List<User> users = magicalListGetter(UserList.class);


How to make a UILabel clickable?

Have you tried to set isUserInteractionEnabled to true on the tripDetails label? This should work.

When and Why to use abstract classes/methods?

read the following article

Abstract Classes

–> When you have a requirement where your base class should provide default implementation of certain methods whereas other methods should be open to being overridden by child classes use abstract classes.

For e.g. again take the example of the Vehicle class above. If we want all classes deriving from Vehicle to implement the Drive() method in a fixed way whereas the other methods can be overridden by child classes. In such a scenario we implement the Vehicle class as an abstract class with an implementation of Drive while leave the other methods / properties as abstract so they could be overridden by child classes.

–> The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share.

For example a class library may define an abstract class that is used as a parameter to many of its functions and require programmers using that library to provide their own implementation of the class by creating a derived class.

Use an abstract class

When creating a class library which will be widely distributed or reused—especially to clients, use an abstract class in preference to an interface; because, it simplifies versioning. This is the practice used by the Microsoft team which developed the Base Class Library. ( COM was designed around interfaces.) Use an abstract class to define a common base class for a family of types. Use an abstract class to provide default behavior. Subclass only a base class in a hierarchy to which the class logically belongs.

How to get only numeric column values?

SELECT column1 FROM table WHERE column1 not like '%[0-9]%'

Removing the '^' did it for me. I'm looking at a varchar field and when I included the ^ it excluded all of my non-numerics which is exactly what I didn't want. So, by removing ^ I only got non-numeric values back.

How to hide a navigation bar from first ViewController in Swift?

Swift 3

override func viewWillAppear(_ animated: Bool) {

    // Hide the navigation bar on the this view controller
    self.navigationController?.setNavigationBarHidden(true, animated: animated)

override func viewWillDisappear(_ animated: Bool) {

    // Show the navigation bar on other view controllers
    self.navigationController?.setNavigationBarHidden(false, animated: animated)

How to split a delimited string into an array in awk?

Have you tried:

echo "12|23|11" | awk '{split($0,a,"|"); print a[3],a[2],a[1]}'

How do I uniquely identify computers visiting my web site?

You may want to try setting a unique ID in an evercookie (it will work cross browser, see their FAQs):

There is also a company called ThreatMetrix that is used by a lot of big companies to solve this problem: They are quite expensive and some of their other products aren't very good, but their device id works well.

Finally, there is this open source jquery implementation of the panopticlick idea: It looks pretty half baked right now but could be expanded upon.

Hope it helps!

How to add number of days to today's date?

you can try this and don't need JQuery: timeSolver.js

For example, add 5 day on today:

var newDay = timeSolver.add(new Date(),5,"day");

You also can add by hour, month...etc. please see for more infomation.

How to run a single test with Mocha?

run single test –by filename–

Actually, one can also run a single mocha test by filename (not just by „it()-string-grepping“) if you remove the glob pattern (e.g. ./test/**/*.spec.js) from your mocha.opts, respectively create a copy, without:

node_modules/.bin/mocha --opts test/mocha.single.opts test/self-test.spec.js

Here's my mocha.single.opts (it's only different in missing the aforementioned glob line)

--require ./test/common.js
--compilers js:babel-core/register
--reporter list

Background: While you can override the various switches from the opts-File (starting with --) you can't override the glob. That link also has some explanations.

Hint: if node_modules/.bin/mocha confuses you, to use the local package mocha. You can also write just mocha, if you have it installed globally.

And if you want the comforts of package.json: Still: remove the **/*-ish glob from your mocha.opts, insert them here, for the all-testing, leave them away for the single testing:

"test": "mocha ./test/**/*.spec.js",
"test-watch": "mocha -R list -w ./test/**/*.spec.js",
"test-single": "mocha $1",
"test-single-watch": "mocha -R list -w $1",


> npm run test


> npm run test-single -- test/ES6.self-test.spec.js 

(mind the --!)

When should we use intern method of String on String literals

    public static void main(String[] args) {
    // TODO Auto-generated method stub
    String s1 = "test";
    String s2 = new String("test");
    System.out.println(s1==s2);              //false
    System.out.println(s1==s2.intern());    //true --> because this time compiler is checking from string constant pool.

PyTorch: How to get the shape of a Tensor as a list of int

Previous answers got you list of torch.Size Here is how to get list of ints

listofints = [int(x) for x in tensor.shape]

Doctrine and LIKE query

You can use the createQuery method (direct in the controller) :

$query = $em->createQuery("SELECT o FROM AcmeCodeBundle:Orders o WHERE o.OrderMail =  :ordermail and o.Product like :searchterm")
->setParameter('searchterm', '%'.$searchterm.'%')
->setParameter('ordermail', '[email protected]');

You need to change AcmeCodeBundle to match your bundle name

Or even better - create a repository class for the entity and create a method in there - this will make it reusable

In MySQL, how to copy the content of one table to another table within the same database?

If table1 is large and you don't want to lock it for the duration of the copy process, you can do a dump-and-load instead:

CREATE TABLE table2 LIKE table1;

SELECT * INTO OUTFILE '/tmp/table1.txt' FROM table1;
LOAD DATA INFILE '/tmp/table1.txt' INTO TABLE table2;

ASP.NET MVC Custom Error Handling Application_Error Global.asax?

I have problem with this error handling approach: In case of web.config:

<customErrors mode="On"/>

The error handler is searching view Error.shtml and the control flow step in to Application_Error global.asax only after exception

System.InvalidOperationException: The view 'Error' or its master was not found or no view engine supports the searched locations. The following locations were searched: ~/Views/home/Error.aspx ~/Views/home/Error.ascx ~/Views/Shared/Error.aspx ~/Views/Shared/Error.ascx ~/Views/home/Error.cshtml ~/Views/home/Error.vbhtml ~/Views/Shared/Error.cshtml ~/Views/Shared/Error.vbhtml at System.Web.Mvc.ViewResult.FindView(ControllerContext context) ....................


 Exception exception = Server.GetLastError();
  HttpException httpException = exception as HttpException;

httpException is always null then customErrors mode="On" :( It is misleading Then <customErrors mode="Off"/> or <customErrors mode="RemoteOnly"/> the users see customErrors html, Then customErrors mode="On" this code is wrong too

Another problem of this code that

Response.Redirect(String.Format("~/Error/{0}/?message={1}", action, exception.Message));

Return page with code 302 instead real error code(402,403 etc)

Populate nested array in mongoose

You can do this using $lookup aggregation as well and probably the best way as now populate is becoming extinct from the mongo

  { "$match": { "_id": mongoose.Types.ObjectId(id) } },
  { "$lookup": {
    "let": { "pages": "$pages" },
    "pipeline": [
      { "$match": { "$expr": { "$in": [ "$_id", "$$pages" ] } } },
      { "$lookup": {
        "let": { "components": "$components" },
        "pipeline": [
          { "$match": { "$expr": { "$in": [ "$_id", "$$components" ] } } },
        "as": "components"
    "as": "pages"

How do I delete an exported environment variable?

Because the original question doesn't mention how the variable was set, and because I got to this page looking for this specific answer, I'm adding the following:

In C shell (csh/tcsh) there are two ways to set an environment variable:

  1. set x = "something"
  2. setenv x "something"

The difference in the behaviour is that variables set with setenv command are automatically exported to subshell while variable set with set aren't.

To unset a variable set with set, use

unset x

To unset a variable set with setenv, use

unsetenv x

Note: in all the above, I assume that the variable name is 'x'.


Android Studio marks R in red with error message "cannot resolve symbol R", but build succeeds

  • Android studio-> Build -> Make Project Or Make Module 'xxx' fix the problem.
  • Yes, run app can not fix the problem...
  • Yes, clean can not fix the problem...
  • Yes, File -> Invalidate cache can not fix the problem...
  • by the way, should I use yes? or may be no is right in English?

How can I center a div within another div?

You need to set the width of the container (auto won't work):

#container {
    width: 640px; /* Can be in percentage also. */
    height: auto;
    margin: 0 auto;
    padding: 10px;
    position: relative;

The CSS reference by MDN explains it all.

Check out these links:

In action at jsFiddle.

Why does ++[[]][+[]]+[+[]] return the string "10"?

Let’s make it simple:

++[[]][+[]]+[+[]] = "10"

var a = [[]][+[]];
var b = [+[]];

// so a == [] and b == [0]


// then a == 1 and b is still that array [0]
// when you sum the var a and an array, it will sum b as a string just like that:

1 + "0" = "10"

Storing images in SQL Server?

Why it can be good to store pictures in the database an not in a catalog on the web server.

You have made an application with lots of pictures stored in a folder on the server, that the client has used for years.

Now they come to you. They server has been destroyed and they need to restore it on a new server. They have no access to the old server anymore. The only backup they have is the database backup.

You have of course the source and can simple deploy it to the new server, install SqlServer and restore the database. But now all the pictures are gone.

If you have saved the pictures in SqlServer everything will work as before.

Just my 2 cents.

Pycharm: run only part of my Python file

You can set a breakpoint, and then just open the debug console. So, the first thing you need to turn on your debug console:

enter image description here

After you've enabled, set a break-point to where you want it to:

enter image description here

After you're done setting the break-point:

enter image description here

Once that has been completed:

enter image description here

Understanding offsetWidth, clientWidth, scrollWidth and -Height, respectively

If you want to use scrollWidth to get the "REAL" CONTENT WIDTH/HEIGHT (as content can be BIGGER than the css-defined width/height-Box) the scrollWidth/Height is very UNRELIABLE as some browser seem to "MOVE" the paddingRIGHT & paddingBOTTOM if the content is to big. They then place the paddings at the RIGHT/BOTTOM of the "too broad/high content" (see picture below).

==> Therefore to get the REAL CONTENT WIDTH in some browsers you have to substract BOTH paddings from the scrollwidth and in some browsers you only have to substract the LEFT Padding.

I found a solution for this and wanted to add this as a comment, but was not allowed. So I took the picture and made it a bit clearer in the regard of the "moved paddings" and the "unreliable scrollWidth". In the BLUE AREA you find my solution on how to get the "REAL" CONTENT WIDTH!

Hope this helps to make things even clearer!

enter image description here

How can I change Mac OS's default Java VM returned from /usr/libexec/java_home

I've been there too and searched everywhere how /usr/libexec/java_home works but I couldn't find any information on how it determines the available Java Virtual Machines it lists.

I've experimented a bit and I think it simply executes a ls /Library/Java/JavaVirtualMachines and then inspects the ./<version>/Contents/Info.plist of all runtimes it finds there.

It then sorts them descending by the key JVMVersion contained in the Info.plist and by default it uses the first entry as its default JVM.

I think the only thing we might do is to change the plist: sudo vi /Library/Java/JavaVirtualMachines/jdk1.8.0.jdk/Contents/Info.plist and then modify the JVMVersion from 1.8.0 to something else that makes it sort it to the bottom instead of the top, like !1.8.0.

Something like:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "">
<plist version="1.0">
            <string>!1.8.0</string>   <!-- changed from '1.8.0' to '!1.8.0' -->`

and then it magically disappears from the top of the list:

/usr/libexec/java_home -verbose
Matching Java Virtual Machines (3):
    1.7.0_45, x86_64:   "Java SE 7" /Library/Java/JavaVirtualMachines/jdk1.7.0_45.jdk/Contents/Home
    1.7.0_09, x86_64:   "Java SE 7" /Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home
    !1.8.0, x86_64: "Java SE 8" /Library/Java/JavaVirtualMachines/jdk1.8.0.jdk/Contents/Home

Now you will need to logout/login and then:

java -version
java version "1.7.0_45"


Of course I have no idea if something else breaks now or if the 1.8.0-ea version of java still works correctly.

You probably should not do any of this but instead simply deinstall 1.8.0.

However so far this has worked for me.

how to save DOMPDF generated content to file?

I did test your code and the only problem I could see was the lack of permission given to the directory you try to write the file in to.

Give "write" permission to the directory you need to put the file. In your case it is the current directory.

Use "chmod" in linux.

Add "Everyone" with "write" enabled to the security tab of the directory if you are in Windows.

How to create unit tests easily in eclipse

You can use my plug-in to create tests easily:

  1. highlight the method
  2. press Ctrl+Alt+Shift+U
  3. it will create the unit test for it.

The plug-in is available here. Hope this helps.

How to change color of Android ListView separator line?

Or you can code it:

int[] colors = {0, 0xFFFF0000, 0}; // red for the example
myList.setDivider(new GradientDrawable(Orientation.RIGHT_LEFT, colors));

Hope it helps

How do I make an HTML text box show a hint when empty?

Use a background image to render the text: { }
 input.fooempty { background-image: url("blah.png"); }

Then all you have to do is detect value == 0 and apply the right class:

 <input class="foo fooempty" value="" type="text" name="bar" />

And the jQuery JavaScript code looks like this:

    var target = $("");
    target.bind("change", function()
        if( target.val().length > 1 )

How can I display two div in one line via css inline property

You don't need to use display:inline to achieve this:

.inline { 
    border: 1px solid red;
    float:left;/*Add float left*/
    margin :10px;

You can use float-left.

Using float:left is best way to place multiple div elements in one line. Why? Because inline-block does have some problem when is viewed in IE older versions.


How to check if command line tools is installed

To check if command line tools are installed run:

xcode-select --version

// if installed you will see the below with the version found in your system
// xcode-select version 1234.

If command line tools are not installed run:

xcode-select --install

Saving timestamp in mysql table using php

Hey there, use the FROM_UNIXTIME() function for this.

Like this:

INSERT INTO table_name


This may happen due to the following reasons -

  1. In your manifest file check the "<uses", like wearable, TV, tablet, etc.
  2. there is a need for some code implementation in BUILD.GRADLE which you may have deleted mistakenly

So by removing the implementation or adding them can remove this error. You can remove the "uses" code in the android manifest file.


  1. this wasted my 1 hour, cause I mistakenly added a class of wearable type, of course, I safe deleted that using refractor but it Didi not made changes to manifest file.

  2. I used the firebase crashlytics code in my java project but I mistakenly deleted that in buld.gradle. Here below: implementation ''

The solution is in either BUILD>GRADLE or in AndroidManifest.xml, mostly.

Could not connect to Redis at Connection refused with homebrew

If after install you need to run redis on all time, just type in terminal:

redis-server &

Running redis using upstart on Ubuntu

I've been trying to understand how to setup systems from the ground up on Ubuntu. I just installed redis onto the box and here's how I did it and some things to look out for.

To install:

sudo apt-get install redis-server

That will create a redis user and install the init.d script for it. Since upstart is now the replacement for using init.d, I figure I should convert it to run using upstart.

To disable the default init.d script for redis:

sudo update-rc.d redis-server disable

Then create /etc/init/redis-server.conf with the following script:

description "redis server"

start on runlevel [23]
stop on shutdown

exec sudo -u redis /usr/bin/redis-server /etc/redis/redis.conf


What this is the script for upstart to know what command to run to start the process. The last line also tells upstart to keep trying to respawn if it dies.

One thing I had to change in /etc/redis/redis.conf is daemonize yes to daemonize no. What happens if you don't change it then redis-server will fork and daemonize itself, and the parent process goes away. When this happens, upstart thinks that the process has died/stopped and you won't have control over the process from within upstart.

Now you can use the following commands to control your redis-server:

sudo start redis-server
sudo restart redis-server
sudo stop redis-server

Hope this was helpful!

What is the difference between aggregation, composition and dependency?

Aggregation and composition are almost completely identical except that composition is used when the life of the child is completely controlled by the parent.


Car -> Tires

The Tires can be taken off of the Car object and installed on a different one. Also, if the car gets totaled, the tires do not necessarily have to be destroyed.


Body -> Blood Cell

When the Body object is destroyed the BloodCells get destroyed with it.


A relationship between two objects where changing one may affect the other.

How to convert a String into an array of Strings containing one character each

You mean you want to do "aabbab".toCharArray(); ? Which will return an array of chars. Or do you actually want the resulting array to contain single character string objects?

How to generate the whole database script in MySQL Workbench?

None of these worked for me. I'm using Mac OS 10.10.5 and Workbench 6.3. What worked for me is Database->Migration Wizard... Flow the steps very carefully

Solving Quadratic Equation

# syntaxis:2.7
# solution for quadratic equation
# a*x**2 + b*x + c = 0

d = b**2-4*a*c # discriminant

if d < 0:
    print 'No solutions'
elif d == 0:
    x1 = -b / (2*a)
    print 'The sole solution is',x1
else: # if d > 0
    x1 = (-b + math.sqrt(d)) / (2*a)
    x2 = (-b - math.sqrt(d)) / (2*a)
    print 'Solutions are',x1,'and',x2

Display a RecyclerView in Fragment

Make sure that you have the correct layout, and that the RecyclerView id is inside the layout. Otherwise, you will be getting this error. I had the same problem, then I noticed the layout was wrong.

    public class ColorsFragment extends Fragment {

         public ColorsFragment() {}

         public View onCreateView(LayoutInflater inflater, ViewGroup container,
             Bundle savedInstanceState) {

==> make sure you are getting the correct layout here. R.layout...

             View rootView = inflater.inflate(R.layout.fragment_colors, container, false); 

How to get the size of a file in MB (Megabytes)?

     String FILE_NAME = "C:\\Ajay\\TEST\\data_996KB.json";
     File file = new File(FILE_NAME);

    if((file.length()) <= (1048576)) {      
        System.out.println("file size is less than 1 mb");
        }else {
            System.out.println("file size is More  than 1 mb");             

Note: 1048576= (1024*1024)=1MB output : file size is less than 1 mb

Comparing two maps

Quick Answer

You should use the equals method since this is implemented to perform the comparison you want. toString() itself uses an iterator just like equals but it is a more inefficient approach. Additionally, as @Teepeemm pointed out, toString is affected by order of elements (basically iterator return order) hence is not guaranteed to provide the same output for 2 different maps (especially if we compare two different maps).

Note/Warning: Your question and my answer assume that classes implementing the map interface respect expected toString and equals behavior. The default java classes do so, but a custom map class needs to be examined to verify expected behavior.


boolean equals(Object o)

Compares the specified object with this map for equality. Returns true if the given object is also a map and the two maps represent the same mappings. More formally, two maps m1 and m2 represent the same mappings if m1.entrySet().equals(m2.entrySet()). This ensures that the equals method works properly across different implementations of the Map interface.

Implementation in Java Source (java.util.AbstractMap)

Additionally, java itself takes care of iterating through all elements and making the comparison so you don't have to. Have a look at the implementation of AbstractMap which is used by classes such as HashMap:

 // Comparison and hashing

     * Compares the specified object with this map for equality.  Returns
     * <tt>true</tt> if the given object is also a map and the two maps
     * represent the same mappings.  More formally, two maps <tt>m1</tt> and
     * <tt>m2</tt> represent the same mappings if
     * <tt>m1.entrySet().equals(m2.entrySet())</tt>.  This ensures that the
     * <tt>equals</tt> method works properly across different implementations
     * of the <tt>Map</tt> interface.
     * <p>This implementation first checks if the specified object is this map;
     * if so it returns <tt>true</tt>.  Then, it checks if the specified
     * object is a map whose size is identical to the size of this map; if
     * not, it returns <tt>false</tt>.  If so, it iterates over this map's
     * <tt>entrySet</tt> collection, and checks that the specified map
     * contains each mapping that this map contains.  If the specified map
     * fails to contain such a mapping, <tt>false</tt> is returned.  If the
     * iteration completes, <tt>true</tt> is returned.
     * @param o object to be compared for equality with this map
     * @return <tt>true</tt> if the specified object is equal to this map
    public boolean equals(Object o) {
        if (o == this)
            return true;

        if (!(o instanceof Map))
            return false;
        Map<K,V> m = (Map<K,V>) o;
        if (m.size() != size())
            return false;

        try {
            Iterator<Entry<K,V>> i = entrySet().iterator();
            while (i.hasNext()) {
                Entry<K,V> e =;
                K key = e.getKey();
                V value = e.getValue();
                if (value == null) {
                    if (!(m.get(key)==null && m.containsKey(key)))
                        return false;
                } else {
                    if (!value.equals(m.get(key)))
                        return false;
        } catch (ClassCastException unused) {
            return false;
        } catch (NullPointerException unused) {
            return false;

        return true;

Comparing two different types of Maps

toString fails miserably when comparing a TreeMap and HashMap though equals does compare contents correctly.


public static void main(String args[]) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("2", "whatever2");
map.put("1", "whatever1");
TreeMap<String, Object> map2 = new TreeMap<String, Object>();
map2.put("2", "whatever2");
map2.put("1", "whatever1");

System.out.println("Are maps equal (using equals):" + map.equals(map2));
System.out.println("Are maps equal (using toString().equals()):"
        + map.toString().equals(map2.toString()));



Are maps equal (using equals):true
Are maps equal (using toString().equals()):false
Map1:{2=whatever2, 1=whatever1}
Map2:{1=whatever1, 2=whatever2}

Sleep function in Windows, using C

SleepEx function (see is the best choise if your program directly or indirectly creates windows (for example use some COM objects). In the simples cases you can also use Sleep.

Generating unique random numbers (integers) between 0 and 'x'

Here’s another algorithm for ensuring the numbers are unique:

  1. generate an array of all the numbers from 0 to x
  2. shuffle the array so the elements are in random order
  3. pick the first n

Compared to the method of generating random numbers until you get a unique one, this method uses more memory, but it has a more stable running time – the results are guaranteed to be found in finite time. This method works better if the upper limit is relatively low or if the amount to take is relatively high.

My answer uses the Lodash library for simplicity, but you could also implement the algorithm described above without that library.

// assuming _ is the Lodash library

// generates `amount` numbers from 0 to `upperLimit` inclusive
function uniqueRandomInts(upperLimit, amount) {
    var possibleNumbers = _.range(upperLimit + 1);
    var shuffled = _.shuffle(possibleNumbers);
    return shuffled.slice(0, amount);

Content Type text/xml; charset=utf-8 was not supported by service

Do not forget check the bindings-related code too. So if you wrote:

BasicHttpBinding binding = new BasicHttpBinding();

Be sure that all your app.config files contains

<endpoint address="..."
          binding="basicHttpBinding" ...

not the

<endpoint address="..."
          binding="wsHttpBinding" ...

or so.

How to add a response header on nginx when using proxy_pass?

There is a module called HttpHeadersMoreModule that gives you more control over headers. It does not come with Nginx and requires additional installation. With it, you can do something like this:

location ... {
  more_set_headers "Server: my_server";

That will "set the Server output header to the custom value for any status code and any content type". It will replace headers that are already set or add them if unset.

How to get last key in an array?

$array = array(
    'something' => array(1,2,3),
    'somethingelse' => array(1,2,3,4)

$last_value = end($array);
$last_key = key($array); // 'somethingelse'

This works because PHP moves it's array pointer internally for $array

Fetch API with Cookie

This works for me:

import Cookies from 'universal-cookie';
const cookies = new Cookies();

function headers(set_cookie=false) {
  let headers = {
    'Accept':       'application/json',
    'Content-Type': 'application/json',
    'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
if (set_cookie) {
    headers['Authorization'] = "Bearer " + cookies.get('remember_user_token');
return headers;

Then build your call:

export function fetchTests(user_id) {
  return function (dispatch) {
   let data = {
    method:      'POST',
    credentials: 'same-origin',
    mode:        'same-origin',
    body:        JSON.stringify({
                     user_id: user_id
    headers:     headers(true)
   return fetch('/api/v1/tests/listing/', data)
      .then(response => response.json())
      .then(json => dispatch(receiveTests(json)));

How can I check if string contains characters & whitespace, not just whitespace?

if (!myString.replace(/^\s+|\s+$/g,""))
  alert('string is only whitespace');

ProgressDialog is deprecated.What is the alternate one to use?

In the progress dialog, user cannot do any kind of work. All the background processes are stopped during progress dialog. So, It is advisable to user progress-bar instead of progress dialog.

What is a segmentation fault?

Segmentation fault occurs when a process (running instance of a program) is trying to access read-only memory address or memory range which is being used by other process or access the non-existent (invalid) memory address. Dangling Reference (pointer) problem means that trying to access an object or variable whose contents have already been deleted from memory, e.g:

int *arr = new int[20];
delete arr;
cout<<arr[1];  //dangling problem occurs here

How can I disable a button on a jQuery UI dialog?

function getDialogButton( jqUIdialog, button_names )
    if (typeof button_names == 'string')
        button_names = [button_names];
    var buttons = jqUIdialog.parent().find('.ui-dialog-buttonpane button');
    for (var i = 0; i < buttons.length; i++)
        var jButton = $( buttons[i] );
        for (var j = 0; j < button_names.length; j++)
            if ( jButton.text() == button_names[j] )
                return jButton;

    return null;

function enableDialogButton( jqUIdialog, button_names, enable )
    var button = getDialogButton( jqUIdialog, button_names );
    if (button == null)
        alert('button not found: '+button_names);
        if (enable)
            button.removeAttr('disabled').removeClass( 'ui-state-disabled' );
            button.attr('disabled', 'disabled').addClass( 'ui-state-disabled' );

How to move text up using CSS when nothing is working

you can try

position: relative;
bottom: 20px;

but I don't see a problem on my browser (Google Chrome)

How to get an enum value from a string value in Java?

Here's a nifty utility I use:

 * A common method for all enums since they can't have another base class
 * @param <T> Enum type
 * @param c enum type. All enums must be all caps.
 * @param string case insensitive
 * @return corresponding enum, or null
public static <T extends Enum<T>> T getEnumFromString(Class<T> c, String string) {
    if( c != null && string != null ) {
        try {
            return Enum.valueOf(c, string.trim().toUpperCase());
        } catch(IllegalArgumentException ex) {
    return null;

Then in my enum class I usually have this to save some typing:

public static MyEnum fromString(String name) {
    return getEnumFromString(MyEnum.class, name);

If your enums are not all caps, just change the Enum.valueOf line.

Too bad I can't use T.class for Enum.valueOf as T is erased.

What does $(function() {} ); do?

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

is just jQuery short-hand for

$(document).ready(function() { ... });

What it's designed to do (amongst other things) is ensure that your function is called once all the DOM elements of the page are ready to be used.

However, I don't think that's the problem you're having - can you clarify what you mean by 'Somehow, some functions are cannot be called and I have to call those function inside' ? Maybe post some code to show what's not working as expected ?

Edit: Re-reading your question, it could be that your function is running before the page has finished loaded, and therefore won't execute properly; putting it in $(function) would indeed fix that!

Javascript String to int conversion

If you are sure id.substring(indexPos) is a number, you can do it like so:

var number = Number(id.substring(indexPos)) + 1;

Otherwise I suggest checking if the Number function evaluates correctly.

Asserting successive calls to a mock method

Usually, I don't care about the order of the calls, only that they happened. In that case, I combine assert_any_call with an assertion about call_count.

>>> import mock
>>> m = mock.Mock()
>>> m(1)
<Mock name='mock()' id='37578160'>
>>> m(2)
<Mock name='mock()' id='37578160'>
>>> m(3)
<Mock name='mock()' id='37578160'>
>>> m.assert_any_call(1)
>>> m.assert_any_call(2)
>>> m.assert_any_call(3)
>>> assert 3 == m.call_count
>>> m.assert_any_call(4)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "[python path]\lib\site-packages\", line 891, in assert_any_call
    '%s call not found' % expected_string
AssertionError: mock(4) call not found

I find doing it this way to be easier to read and understand than a large list of calls passed into a single method.

If you do care about order or you expect multiple identical calls, assert_has_calls might be more appropriate.


Since I posted this answer, I've rethought my approach to testing in general. I think it's worth mentioning that if your test is getting this complicated, you may be testing inappropriately or have a design problem. Mocks are designed for testing inter-object communication in an object oriented design. If your design is not objected oriented (as in more procedural or functional), the mock may be totally inappropriate. You may also have too much going on inside the method, or you might be testing internal details that are best left unmocked. I developed the strategy mentioned in this method when my code was not very object oriented, and I believe I was also testing internal details that would have been best left unmocked.

jQuery disable a link

html link example:

        <!-- boostrap button + fontawesome icon -->
        <a class="btn btn-primary" id="BT_Download" target="_blank" href="DownloadDoc?Id=32">
        <i class="icon-file-text icon-large"></i>
        Download Document

use this in jQuery


add this to css :

    a[disabled="disabled"] {
        pointer-events: none;

How do I get row id of a row in sql server

There is a pseudocolumn called %%physloc%% that shows the physical address of the row.

See Equivalent of Oracle's RowID in SQL Server

merge one local branch into another local branch

To merge one branch into another, such as merging "feature_x" branch into "master" branch:

git checkout master

git merge feature_x

This page is the first result for several search engines when looking for "git merge one branch into another". However, the original question is more specific and special case than the title would suggest.
It is also more complex than both the subject and the search expression. As such, this is a minimal but explanatory answer for the benefit of most visitors.

Pass multiple arguments into std::thread

You literally just pass them in std::thread(func1,a,b,c,d); that should have compiled if the objects existed, but it is wrong for another reason. Since there is no object created you cannot join or detach the thread and the program will not work correctly. Since it is a temporary the destructor is immediately called, since the thread is not joined or detached yet std::terminate is called. You could std::join or std::detach it before the temp is destroyed, like std::thread(func1,a,b,c,d).join();//or detach .

This is how it should be done.

std::thread t(func1,a,b,c,d);

You could also detach the thread, read-up on threads if you don't know the difference between joining and detaching.

Maven- No plugin found for prefix 'spring-boot' in the current project and in the plugin groups

Make sure pom.xml exist in the directory, when using the mvn spring-boot:run command. No need to add any thing in the pom.xml file.

Detect the Internet connection is offline?

I was looking for a client-side solution to detect if the internet was down or my server was down. The other solutions I found always seemed to be dependent on a 3rd party script file or image, which to me didn't seem like it would stand the test of time. An external hosted script or image could change in the future and cause the detection code to fail.

I've found a way to detect it by looking for an xhrStatus with a 404 code. In addition, I use JSONP to bypass the CORS restriction. A status code other than 404 shows the internet connection isn't working.

    url:      '' + new Date().getTime() + '.html',
    dataType: 'jsonp',
    timeout:  5000,

    error: function(xhr) {
        if (xhr.status == 404) {
            //internet connection working
        else {
            //internet is down (xhr.status == 0)

Advantages of SQL Server 2008 over SQL Server 2005?

SQL 2008 also allows you to disable lock escalation on specific tables. I have found this very useful on small frequently updated tables where locks can escalate causing concurrency issues. In SQL 2005, even with the ROWLOCK hint on delete statements locks can be escalated which can lead to deadlocks. In my testing, an application which I have developed had concurrency issues during small table manipulation due to lock escalation on SQL 2005. In SQL 2008 this problem went away.

It is still important to bear in mind the potential overhead of handling large numbers of row locks, but having the option to stop escalation when you want to is very useful.

Where can I find my Facebook application id and secret key?

You should use the Developer App.

On the right is a section titled "My Applications" from which you can select an application to see its information.

You can also go straight here as well, which will list your apps on the left.

How to call webmethod in C#

Necro'ing this Question ;)

You need to change the data being sent as Stringified JSON, that way you can modularize the Ajax call into a single supportable function.

First Step: Extract data construction

 * This helper is used to call WebMethods from the page WebMethods.aspx
 * @method - String value; the name of the Web Method to execute
 * @data - JSON Object; the JSON structure data to pass, it will be Stringified
 *      before sending
 * @beforeSend - Function(xhr, sett)
 * @success - Function(data, status, xhr)
 * @error - Function(xhr, status, err)
function AddToCartAjax(method, data, beforeSend, success, error) {
        url: 'AddToCart.aspx/', + method,
        data: JSON.stringify(data),
        type: "POST",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        beforeSend: beforeSend,
        success: success,
        error: error

Second Step: Generalize WebMethod

public static string AddTo_Cart ( object items ) {
    var js = new JavaScriptSerializer();
    var json = js.ConvertToType<Dictionary<string , int>>( items );

    SpiritsShared.ShoppingCart.AddItem(json["itemId"], json["quantity"]);      
    return "Add";

Third Step: Call it where you need it

This can be called just about anywhere, JS-file, HTML-file, or Server-side construction.

var items = { "quantity": total_qty, "itemId": itemId };

AddToCartAjax("AddTo_Cart", items,
    function (xhr, sett) {  // @beforeSend
    }, function (data, status, xhr) {   // @success
    }, function(xhr, status, err){  // @error

Add zero-padding to a string

"1".PadLeft(4, '0');

What is the Swift equivalent of isEqualToString in Objective-C?

Use == operator instead of isEqual

Comparing Strings

Swift provides three ways to compare String values: string equality, prefix equality, and suffix equality.

String Equality

Two String values are considered equal if they contain exactly the same characters in the same order:

let quotation = "We're a lot alike, you and I."
let sameQuotation = "We're a lot alike, you and I."
if quotation == sameQuotation {
    println("These two strings are considered equal")
// prints "These two strings are considered equal"

For more read official documentation of Swift (search Comparing Strings).

Swift - iOS - Dates and times in different format

let dateString = "1970-01-01T13:30:00.000Z"
let formatter = DateFormatter()

formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
let date = String(dateString.dropLast(5)))!
formatter.dateFormat = ""
print(formatter.string(from: date))

if You notice I have set .dateFormat = ""by this you will get time only. Result:01.30PM

Magento - Retrieve products with a specific attribute value

$attribute = Mage::getModel('eav/entity_attribute')
                ->loadByCode('catalog_product', 'manufacturer');

$valuesCollection = Mage::getResourceModel('eav/entity_attribute_option_collection')
            ->setStoreFilter(0, false);

$preparedManufacturers = array();            
foreach($valuesCollection as $value) {
    $preparedManufacturers[$value->getOptionId()] = $value->getValue();

if (count($preparedManufacturers)) {
    echo "<h2>Manufacturers</h2><ul>";
    foreach($preparedManufacturers as $optionId => $value) {
        $products = Mage::getModel('catalog/product')->getCollection();
            array('attribute'=>'manufacturer', 'eq'=> $optionId,          

        echo "<li>" . $value . " - (" . $optionId . ") - (Products: ".count($products).")</li>";
    echo "</ul>";

Why does checking a variable against multiple values with `OR` only check the first value?

if name in ("Jesse", "jesse"):

would be the correct way to do it.

Although, if you want to use or, the statement would be

if name == 'Jesse' or name == 'jesse':

>>> ("Jesse" or "jesse")

evaluates to 'Jesse', so you're essentially not testing for 'jesse' when you do if name == ("Jesse" or "jesse"), since it only tests for equality to 'Jesse' and does not test for 'jesse', as you observed.

Array of Matrices in MATLAB

Use cell arrays. This has an advantage over 3D arrays in that it does not require a contiguous memory space to store all the matrices. In fact, each matrix can be stored in a different space in memory, which will save you from Out-of-Memory errors if your free memory is fragmented. Here is a sample function to create your matrices in a cell array:

function result = createArrays(nArrays, arraySize)
    result = cell(1, nArrays);
    for i = 1 : nArrays
        result{i} = zeros(arraySize);

To use it:

myArray = createArrays(requiredNumberOfArrays, [500 800]);

And to access your elements:

myArray{1}(2,3) = 10;

If you can't know the number of matrices in advance, you could simply use MATLAB's dynamic indexing to make the array as large as you need. The performance overhead will be proportional to the size of the cell array, and is not affected by the size of the matrices themselves. For example:

myArray{1} = zeros(500, 800);
if twoRequired, myArray{2} = zeros(500, 800); end

Differences between .NET 4.0 and .NET 4.5 in High level in .NET

You can find the latest features of the .NET Framework 4.5 beta here

It breaks down the changes to the framework in the following categories:

  • .NET for Metro style Apps
  • Portable Class Libraries
  • Core New Features and Improvements
  • Parallel Computing
  • Web
  • Networking
  • Windows Presentation Foundation (WPF)
  • Windows Communication Foundation (WCF)
  • Windows Workflow Foundation (WF)

You sound like you are more interested in the Web section as this shows the changes to ASP.NET 4.5. The rest of the changes can be found under the other headings.

You can also see some of the features that were new when the .NET Framework 4.0 was shipped here.

How to call external url in jquery?

I think the only way is by using internel PHP code like MANOJ and Fernando suggest.

curl post/get in php file on your server --> call this php file with ajax

The PHP file let say (fb.php):

curl_setopt($ch, CURLOPT_URL,$fbUrl);
curl_setopt($ch, CURLOPT_POST, 1);
// POST data here
curl_setopt($ch, CURLOPT_POSTFIELDS,

// receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$server_output = curl_exec ($ch);
echo $server_output;
curl_close ($ch);

Than use AJAX GET to

fb.php?commentmeta=your comment goes here

from your server.

Or do this with simple HTML and JavaScript from externel server:

Message: <input type="text" id="message">
<input type="submit" onclick='PostMessage()'>
function PostMessage() {
var comment = document.getElementById('message').value;

Onclick javascript to make browser go back to previous page?

Shortest Yet!

<button onclick="history.go(-1);">Go back</button>

I prefer the .go(-number) method as then, for 1 or many 'backs' there's only 1 method to use/remember/update/search for, etc.

Also, using a tag for a back button seems more appropriate than tags with names and types...

how to define variable in jquery

You can also use text() to set or get the text content of selected elements

var text1 = $("#idName").text();

How to remove item from a python list in a loop?

The already-mentioned list comprehension approach is probably your best bet. But if you absolutely want to do it in-place (for example if x is really large), here's one way:

x = ["ok", "jj", "uy", "poooo", "fren"]
while index < len(x):
    if len(x[index]) != 2:
        print "length of %s is: %s" %(x[index], len(x[index]))
        del x[index]

Correct way to use get_or_create?

Following @Tobu answer and @mipadi comment, in a more pythonic way, if not interested in the created flag, I would use:

customer.source, _ = Source.objects.get_or_create(name="Website")

How to pass macro definition from "make" command line arguments (-D) to C source code?

Call make this way

make CFLAGS=-Dvar=42

because you do want to override your Makefile's CFLAGS, and not just the environment (which has a lower priority with regard to Makefile variables).

Capturing standard out and error with Start-Process

I really had troubles with those examples from Andy Arismendi and from LPG. You should always use:

$stdout = $p.StandardOutput.ReadToEnd()

before calling


A full example is:

$pinfo = New-Object System.Diagnostics.ProcessStartInfo
$pinfo.FileName = "ping.exe"
$pinfo.RedirectStandardError = $true
$pinfo.RedirectStandardOutput = $true
$pinfo.UseShellExecute = $false
$pinfo.Arguments = "localhost"
$p = New-Object System.Diagnostics.Process
$p.StartInfo = $pinfo
$p.Start() | Out-Null
$stdout = $p.StandardOutput.ReadToEnd()
$stderr = $p.StandardError.ReadToEnd()
Write-Host "stdout: $stdout"
Write-Host "stderr: $stderr"
Write-Host "exit code: " + $p.ExitCode

Select All Rows Using Entity Framework

I used the entitydatasource and it provide everything I needed for what I wanted to do.


String to object in JS

string = "firstName:name1, lastName:last1";

This will work:

var fields = string.split(', '),
    fieldObject = {};

if( typeof fields === 'object') ){
   fields.each(function(field) {
      var c = property.split(':');
      fieldObject[c[0]] = c[1];

However it's not efficient. What happens when you have something like this:

string = "firstName:name1, lastName:last1, profileUrl:http://localhost/site/profile/1";

split() will split 'http'. So i suggest you use a special delimiter like pipe

 string = "firstName|name1, lastName|last1";

   var fields = string.split(', '),
        fieldObject = {};

    if( typeof fields === 'object') ){
       fields.each(function(field) {
          var c = property.split('|');
          fieldObject[c[0]] = c[1];

Git Pull is Not Possible, Unmerged Files

Solved, using the following command set:

git reset --hard
git pull --rebase
git rebase --skip
git pull

The trick is to rebase the changes... We had some trouble rebasing one trivial commit, and so we simply skipped it using git rebase --skip (after having copied the files).

TypeError: Object of type 'bytes' is not JSON serializable

You are creating those bytes objects yourself:

item['title'] = [t.encode('utf-8') for t in title]
item['link'] = [l.encode('utf-8') for l in link]
item['desc'] = [d.encode('utf-8') for d in desc]

Each of those t.encode(), l.encode() and d.encode() calls creates a bytes string. Do not do this, leave it to the JSON format to serialise these.

Next, you are making several other errors; you are encoding too much where there is no need to. Leave it to the json module and the standard file object returned by the open() call to handle encoding.

You also don't need to convert your items list to a dictionary; it'll already be an object that can be JSON encoded directly:

class W3SchoolPipeline(object):    
    def __init__(self):
        self.file = open('w3school_data_utf8.json', 'w', encoding='utf-8')

    def process_item(self, item, spider):
        line = json.dumps(item) + '\n'
        return item

I'm guessing you followed a tutorial that assumed Python 2, you are using Python 3 instead. I strongly suggest you find a different tutorial; not only is it written for an outdated version of Python, if it is advocating line.decode('unicode_escape') it is teaching some extremely bad habits that'll lead to hard-to-track bugs. I can recommend you look at Think Python, 2nd edition for a good, free, book on learning Python 3.

How can I uninstall an application using PowerShell?

I will make my own little contribution. I needed to remove a list of packages from the same computer. This is the script I came up with.

$packages = @("package1", "package2", "package3")
foreach($package in $packages){
  $app = Get-WmiObject -Class Win32_Product | Where-Object {
    $_.Name -match "$package"

I hope this proves to be useful.

Note that I owe David Stetler the credit for this script since it is based on his.

Changing project port number in Visual Studio 2013

Well, I simply could not find this (for me) mythical "Use dynamic ports" option. I have post screenshots.

enter image description here

On a more constructive note, I believe that the port numbers are to be found in the solution file AND CRUCIALLY cross referenced against the IIS Express config file


I tried editing the port number in just the solution file but strange things happened. I propose (no time yet) that it needs a consistent edit across both the solution file and the config file.

Including external jar-files in a new jar-file build with Ant

With the helpful advice from people who have answered here I started digging into One-Jar. After some dead-ends (and some results that were exactly like my previous results I managed to get it working. For other peoples reference I'm listing the build.xml that worked for me.

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<project basedir="." default="build" name="<INSERT_PROJECT_NAME_HERE>">
    <property environment="env"/>
    <property name="debuglevel" value="source,lines,vars"/>
    <property name="target" value="1.6"/>
    <property name="source" value="1.6"/>

    <property name="one-jar.dist.dir" value="../onejar"/>
    <import file="${one-jar.dist.dir}/one-jar-ant-task.xml" optional="true" />

    <property name="src.dir"          value="src"/>
    <property name="bin.dir"          value="bin"/>
    <property name="build.dir"        value="build"/>
    <property name="classes.dir"      value="${build.dir}/classes"/>
    <property name=""   value="${build.dir}/jars"/>
    <property name="external.lib.dir" value="../jars"/>
    <property name="final.jar"        value="${bin.dir}/<INSERT_NAME_OF_FINAL_JAR_HERE>"/>

    <property name="main.class"       value="<INSERT_MAIN_CLASS_HERE>"/>

    <path id="project.classpath">
        <fileset dir="${external.lib.dir}">
            <include name="*.jar"/>

    <target name="init">
        <mkdir dir="${bin.dir}"/>
        <mkdir dir="${build.dir}"/>
        <mkdir dir="${classes.dir}"/>
        <mkdir dir="${}"/>
        <copy includeemptydirs="false" todir="${classes.dir}">
            <fileset dir="${src.dir}">
                <exclude name="**/*.launch"/>
                <exclude name="**/*.java"/>

    <target name="clean">
        <delete dir="${build.dir}"/>
        <delete dir="${bin.dir}"/>

    <target name="cleanall" depends="clean"/>

    <target name="build" depends="init">
        <echo message="${}: ${ant.file}"/>
        <javac debug="true" debuglevel="${debuglevel}" destdir="${classes.dir}" source="${source}" target="${target}">
            <src path="${src.dir}"/>
            <classpath refid="project.classpath"/>   

    <target name="build-jar" depends="build">
        <delete file="${final.jar}" />
        <one-jar destfile="${final.jar}" onejarmainclass="${main.class}">
                <fileset dir="${classes.dir}"/>
                <fileset dir="${external.lib.dir}" />

I hope someone else can benefit from this.

How to my "exe" from PyCharm project

You cannot directly save a Python file as an exe and expect it to work -- the computer cannot automatically understand whatever code you happened to type in a text file. Instead, you need to use another program to transform your Python code into an exe.

I recommend using a program like Pyinstaller. It essentially takes the Python interpreter and bundles it with your script to turn it into a standalone exe that can be run on arbitrary computers that don't have Python installed (typically Windows computers, since Linux tends to come pre-installed with Python).

To install it, you can either download it from the linked website or use the command:

pip install pyinstaller

...from the command line. Then, for the most part, you simply navigate to the folder containing your source code via the command line and run:


You can find more information about how to use Pyinstaller and customize the build process via the documentation.

You don't necessarily have to use Pyinstaller, though. Here's a comparison of different programs that can be used to turn your Python code into an executable.

How does Task<int> become an int?

No requires converting the Task to int. Simply Use The Task Result.

int taskResult = AccessTheWebAndDouble().Result;

public async Task<int> AccessTheWebAndDouble()
    int task = AccessTheWeb();
    return task;

It will return the value if available otherwise it return 0.

Reading a binary file with python

In general, I would recommend that you look into using Python's struct module for this. It's standard with Python, and it should be easy to translate your question's specification into a formatting string suitable for struct.unpack().

Do note that if there's "invisible" padding between/around the fields, you will need to figure that out and include it in the unpack() call, or you will read the wrong bits.

Reading the contents of the file in order to have something to unpack is pretty trivial:

import struct

data = open("from_fortran.bin", "rb").read()

(eight, N) = struct.unpack("@II", data)

This unpacks the first two fields, assuming they start at the very beginning of the file (no padding or extraneous data), and also assuming native byte-order (the @ symbol). The Is in the formatting string mean "unsigned integer, 32 bits".

jQuery delete all table rows except first

I think this is more readable given the intent:

$('someTableSelector').children( 'tr:not(:first)' ).remove();

Using children also takes care of the case where the first row contains a table by limiting the depth of the search.

If you had an TBODY element, you can do this:

$("someTableSelector > tbody:last").children().remove();

If you have THEAD or TFOOT elements you'll need to do something different.

UIView bottom border?


Create UIView extension

private var bottomLineColorAssociatedKey : UIColor = .black
private var topLineColorAssociatedKey : UIColor = .black
private var rightLineColorAssociatedKey : UIColor = .black
private var leftLineColorAssociatedKey : UIColor = .black
extension UIView {

@IBInspectable var bottomLineColor: UIColor {
    get {
        if let color = objc_getAssociatedObject(self, &bottomLineColorAssociatedKey) as? UIColor {
            return color
        } else {
            return .black
    } set {
        objc_setAssociatedObject(self, &bottomLineColorAssociatedKey, newValue, .OBJC_ASSOCIATION_RETAIN)
@IBInspectable var bottomLineWidth: CGFloat {
    get {
        return self.bottomLineWidth
    set {
        DispatchQueue.main.async {
            self.addBottomBorderWithColor(color: self.bottomLineColor, width: newValue)
@IBInspectable var topLineColor: UIColor {
    get {
        if let color = objc_getAssociatedObject(self, &topLineColorAssociatedKey) as? UIColor {
            return color
        } else {
            return .black
    } set {
        objc_setAssociatedObject(self, &topLineColorAssociatedKey, newValue, .OBJC_ASSOCIATION_RETAIN)
@IBInspectable var topLineWidth: CGFloat {
    get {
        return self.topLineWidth
    set {
        DispatchQueue.main.async {
            self.addTopBorderWithColor(color: self.topLineColor, width: newValue)
@IBInspectable var rightLineColor: UIColor {
    get {
        if let color = objc_getAssociatedObject(self, &rightLineColorAssociatedKey) as? UIColor {
            return color
        } else {
            return .black
    } set {
        objc_setAssociatedObject(self, &rightLineColorAssociatedKey, newValue, .OBJC_ASSOCIATION_RETAIN)
@IBInspectable var rightLineWidth: CGFloat {
    get {
        return self.rightLineWidth
    set {
        DispatchQueue.main.async {
            self.addRightBorderWithColor(color: self.rightLineColor, width: newValue)
@IBInspectable var leftLineColor: UIColor {
    get {
        if let color = objc_getAssociatedObject(self, &leftLineColorAssociatedKey) as? UIColor {
            return color
        } else {
            return .black
    } set {
        objc_setAssociatedObject(self, &leftLineColorAssociatedKey, newValue, .OBJC_ASSOCIATION_RETAIN)
@IBInspectable var leftLineWidth: CGFloat {
    get {
        return self.leftLineWidth
    set {
        DispatchQueue.main.async {
            self.addLeftBorderWithColor(color: self.leftLineColor, width: newValue)
func addTopBorderWithColor(color: UIColor, width: CGFloat) {
    let border = CALayer() = "topBorderLayer"
    removePreviouslyAddedLayer(name: ?? "")
    border.backgroundColor = color.cgColor
    border.frame = CGRect(x: 0, y : 0,width: self.frame.size.width, height: width)
    self.addObserver(self, forKeyPath: #keyPath(UIView.bounds), options: .new, context: UnsafeMutableRawPointer(bitPattern: 1111) )

func addRightBorderWithColor(color: UIColor, width: CGFloat) {
    let border = CALayer() = "rightBorderLayer"
    removePreviouslyAddedLayer(name: ?? "")
    border.backgroundColor = color.cgColor
    border.frame = CGRect(x: self.frame.size.width - width, y: 0, width : width, height :self.frame.size.height)
     self.addObserver(self, forKeyPath: #keyPath(UIView.bounds), options: .new, context: UnsafeMutableRawPointer(bitPattern: 2222) )

func addBottomBorderWithColor(color: UIColor, width: CGFloat) {
    let border = CALayer() = "bottomBorderLayer"
    removePreviouslyAddedLayer(name: ?? "")
    border.backgroundColor = color.cgColor
    border.frame = CGRect(x: 0, y: self.frame.size.height - width,width : self.frame.size.width,height: width)
    self.addObserver(self, forKeyPath: #keyPath(UIView.bounds), options: .new, context: UnsafeMutableRawPointer(bitPattern: 3333) )
func addLeftBorderWithColor(color: UIColor, width: CGFloat) {
    let border = CALayer() = "leftBorderLayer"
    removePreviouslyAddedLayer(name: ?? "")
    border.backgroundColor = color.cgColor
    border.frame = CGRect(x:0, y:0,width : width, height : self.frame.size.height)
    self.addObserver(self, forKeyPath: #keyPath(UIView.bounds), options: .new, context: UnsafeMutableRawPointer(bitPattern: 4444) )
override open func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {

    if let objectView = object as? UIView,
        objectView === self,
        keyPath == #keyPath(UIView.bounds) {
        switch context {
        case UnsafeMutableRawPointer(bitPattern: 1111):
            for border in self.layer.sublayers ?? [] {
                if == "topBorderLayer" {
                    border.frame = CGRect(x: 0, y : 0,width: self.frame.size.width, height: border.frame.height)
        case UnsafeMutableRawPointer(bitPattern: 2222):
            for border in self.layer.sublayers ?? [] {
                if == "rightBorderLayer" {
                     border.frame = CGRect(x: self.frame.size.width - border.frame.width, y: 0, width : border.frame.width, height :self.frame.size.height)
        case UnsafeMutableRawPointer(bitPattern: 3333):
            for border in self.layer.sublayers ?? [] {
                if == "bottomBorderLayer" {
                    border.frame = CGRect(x: 0, y: self.frame.size.height - border.frame.height,width : self.frame.size.width,height: border.frame.height)
        case UnsafeMutableRawPointer(bitPattern: 4444):
            for border in self.layer.sublayers ?? [] {
                if == "leftBorderLayer" {
                   border.frame = CGRect(x:0, y:0,width : border.frame.width, height : self.frame.size.height)
func removePreviouslyAddedLayer(name : String) {
    if self.layer.sublayers?.count ?? 0 > 0 {
        self.layer.sublayers?.forEach {
            if $ == name {

Objective C

Create category class of UIView


#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
@interface UIView (Border) 

@property (nonatomic) IBInspectable UIColor *topLineColor;
@property (nonatomic) IBInspectable CGFloat topLineWidth;
@property (nonatomic) IBInspectable UIColor *bottomLineColor;
@property (nonatomic) IBInspectable CGFloat bottomLineWidth;
@property (nonatomic) IBInspectable UIColor *rightLineColor;
@property (nonatomic) IBInspectable CGFloat rightLineWidth;
@property (nonatomic) IBInspectable UIColor *leftLineColor;
@property (nonatomic) IBInspectable CGFloat leftLineWidth;

- (void)addBottomBorderWithColor: (UIColor *) color andWidth:(CGFloat) borderWidth;

- (void)addLeftBorderWithColor: (UIColor *) color andWidth:(CGFloat) borderWidth;

- (void)addRightBorderWithColor: (UIColor *) color andWidth:(CGFloat) borderWidth;

- (void)addTopBorderWithColor: (UIColor *) color andWidth:(CGFloat) borderWidth;



static void *topBorderContext = &topBorderContext;
static void *bottomBorderContext = &bottomBorderContext;
static void *leftBorderContext = &leftBorderContext;
static void *rightBorderContext = &rightBorderContext;
static char bottomLineColorKey,topLineColorKey,rightLineColorKey,leftLineColorKey;
@implementation UIView(Utility)
@dynamic borderColor,borderWidth,cornerRadius,bottomLineWidth,topLineWidth,rightLineWidth,leftLineWidth;

-(void)setBorderColor:(UIColor *)borderColor{
    [self.layer setBorderColor:borderColor.CGColor];

    [self.layer setBorderWidth:borderWidth];

    [self.layer setCornerRadius:cornerRadius];
// for Bottom Line
- (UIColor *)bottomLineColor {
    return objc_getAssociatedObject(self, &bottomLineColorKey);
- (void)setBottomLineColor:(UIColor *)bottomLineColor {
    objc_setAssociatedObject(self, &bottomLineColorKey,
                             bottomLineColor, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
-(void)setBottomLineWidth:(CGFloat)bottomLineWidth {
    [self addBottomBorderWithColor:[self bottomLineColor] andWidth:bottomLineWidth];
// for top Line
- (UIColor *)topLineColor {
    return objc_getAssociatedObject(self, &topLineColorKey);
- (void)setTopLineColor:(UIColor *)topLineColor {
    objc_setAssociatedObject(self, &topLineColorKey,
                             topLineColor, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
- (void)setTopLineWidth:(CGFloat)topLineWidth{
    [self addTopBorderWithColor:[self topLineColor] andWidth:topLineWidth];
// for right Line
- (UIColor *)rightLineColor {
    return objc_getAssociatedObject(self, &rightLineColorKey);
-(void)setRightLineColor:(UIColor *)rightLineColor {
    objc_setAssociatedObject(self, &rightLineColorKey,
                             rightLineColor, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    [self addRightBorderWithColor:[self rightLineColor] andWidth:rightLineWidth];
// for left Line
-(UIColor *)leftLineColor {
    return objc_getAssociatedObject(self, &leftLineColorKey);
-(void)setLeftLineColor:(UIColor *)leftLineColor{
    objc_setAssociatedObject(self, &leftLineColorKey,
                             leftLineColor, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    [self addLeftBorderWithColor:[self leftLineColor] andWidth:leftLineWidth];

- (void)addTopBorderWithColor:(UIColor *)color andWidth:(CGFloat) borderWidth {
    dispatch_async(dispatch_get_main_queue(), ^{
        CALayer *border = [CALayer layer]; = @"topBorderLayer";
        border.backgroundColor = color.CGColor;
        border.frame = CGRectMake(0, 0, self.frame.size.width, borderWidth);
        [self.layer addSublayer:border];
        [self addObserver:self forKeyPath: @"bounds" options:NSKeyValueObservingOptionNew context:topBorderContext];

- (void)addBottomBorderWithColor:(UIColor *)color andWidth:(CGFloat) borderWidth {
    dispatch_async(dispatch_get_main_queue(), ^{
        CALayer *border = [CALayer layer]; = @"bottomBorderLayer";
        border.backgroundColor = color.CGColor;
        border.frame = CGRectMake(0, self.frame.size.height - borderWidth, self.frame.size.width, borderWidth);
        [self.layer addSublayer:border];
        [self addObserver:self forKeyPath: @"bounds" options:NSKeyValueObservingOptionNew context:bottomBorderContext];

- (void)addLeftBorderWithColor:(UIColor *)color andWidth:(CGFloat) borderWidth {
    dispatch_async(dispatch_get_main_queue(), ^{
        CALayer *border = [CALayer layer]; = @"leftBorderLayer";
        border.backgroundColor = color.CGColor;
        border.frame = CGRectMake(0, 0, borderWidth, self.frame.size.height);
        [self.layer addSublayer:border];
        [self addObserver:self forKeyPath: @"bounds" options:NSKeyValueObservingOptionNew context:leftBorderContext];

- (void)addRightBorderWithColor:(UIColor *)color andWidth:(CGFloat) borderWidth {
    dispatch_async(dispatch_get_main_queue(), ^{
        CALayer *border = [CALayer layer]; = @"rightBorderLayer";
        border.backgroundColor = color.CGColor;
        border.frame = CGRectMake(self.frame.size.width - borderWidth, 0, borderWidth, self.frame.size.height);
        [self.layer addSublayer:border];
        [self addObserver:self forKeyPath: @"bounds" options:NSKeyValueObservingOptionNew context:rightBorderContext];
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
    if (context == topBorderContext) {
        for (CALayer *border in self.layer.sublayers) {
            if ([ isEqualToString:@"topBorderLayer"]) {
                [border setFrame:CGRectMake(0, 0, self.frame.size.width, border.frame.size.height)];
    } else if (context == bottomBorderContext) {
        for (CALayer *border in self.layer.sublayers) {
            if ([ isEqualToString:@"bottomBorderLayer"]) {
                [border setFrame:CGRectMake(0, self.frame.size.height - border.frame.size.height, self.frame.size.width, border.frame.size.height)];
    } else if (context == leftBorderContext) {
        for (CALayer *border in self.layer.sublayers) {
            if ([ isEqualToString:@"leftBorderLayer"]) {
                [border setFrame:CGRectMake(0, 0, border.frame.size.width, self.frame.size.height)];
    } else if (context == rightBorderContext) {
        for (CALayer *border in self.layer.sublayers) {
            if ([ isEqualToString:@"rightBorderLayer"]) {
                [border setFrame:CGRectMake(self.frame.size.width - border.frame.size.width, 0, border.frame.size.width, self.frame.size.height)];
    } else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
- (void)removePreviouslyAddedLayer:(NSString *)name {
    if (self.layer.sublayers.count > 0) {
        for (CALayer *layer in self.layer.sublayers) {
            if ([ isEqualToString:name]) {
                [layer removeFromSuperlayer];


Usage :- Select any control from storyboard, then show attribute inspector (Right side) You will see below image Example.(Note : Border only appear at run time.)

Now You can set any side of border colour and width.

The input is not a valid Base-64 string as it contains a non-base 64 character

Just in case you don't know the type of uploaded image, and you just you need to remove its base64 header:

 var imageParts = model.ImageAsString.Split(',').ToList<string>();
 //Exclude the header from base64 by taking second element in List.
 byte[] Image = Convert.FromBase64String(imageParts[1]);

Is there an XSL "contains" directive?

Sure there is! For instance:

<xsl:if test="not(contains($hhref, '1234'))">
    <a href="{$hhref}" title="{$pdate}">
      <xsl:value-of select="title"/>

The syntax is: contains(stringToSearchWithin, stringToSearchFor)

Run a single migration file

Looks like at least in the latest Rails release (5.2 at the time of writing) there is one more way of filtering the migrations being ran. One can pass a filter in a SCOPE environment variable which would be then used to select migration files.

Assuming you have two migration files 1_add_foos.rb and 2_add_foos.run_this_one.rb running

SCOPE=run_this_one rails db:migrate:up

will select and run only 2_add_foos.run_this_one.rb. Keep in mind that all migration files matching the scope will be ran.

Why is vertical-align:text-top; not working in CSS

The problem I had can't be made out from the info I have provided:

  • I had the text enclosed in old school <p> tags.

I changed the <p> to <span> and it works fine.

CSS3 transition events


All modern browsers now support the unprefixed event:

element.addEventListener('transitionend', callback, false);

I was using the approach given by Pete, however I have now started using the following

$(".myClass").one('transitionend webkitTransitionEnd oTransitionEnd otransitionend MSTransitionEnd', 
function() {
 //do something

Alternatively if you use bootstrap then you can simply do

function() {
 //do something

This is becuase they include the following in bootstrap.js

+function ($) {
  'use strict';

  // ============================================================

  function transitionEnd() {
    var el = document.createElement('bootstrap')

    var transEndEventNames = {
      'WebkitTransition' : 'webkitTransitionEnd',
      'MozTransition'    : 'transitionend',
      'OTransition'      : 'oTransitionEnd otransitionend',
      'transition'       : 'transitionend'

    for (var name in transEndEventNames) {
      if ([name] !== undefined) {
        return { end: transEndEventNames[name] }

    return false // explicit for ie8 (  ._.)

  $(function () {
    $.support.transition = transitionEnd()


Note they also include an emulateTransitionEnd function which may be needed to ensure a callback always occurs.

  $.fn.emulateTransitionEnd = function (duration) {
    var called = false, $el = this
    $(this).one($.support.transition.end, function () { called = true })
    var callback = function () { if (!called) $($el).trigger($.support.transition.end) }
    setTimeout(callback, duration)
    return this

Be aware that sometimes this event doesn’t fire, usually in the case when properties don’t change or a paint isn’t triggered. To ensure we always get a callback, let’s set a timeout that’ll trigger the event manually.

T-sql - determine if value is integer

Why not just do something like:


how to write an array to a file Java

If you're okay with Apache commons lib

outputWriter.write(ArrayUtils.join(array, ","));

Getting date format m-d-Y H:i:s.u from milliseconds says:

Microseconds (added in PHP 5.2.2). Note that date() will always generate 000000 since it takes an integer parameter, whereas DateTime::format() does support microseconds if DateTime was created with microseconds.

So use as simple:

$micro_date = microtime();
$date_array = explode(" ",$micro_date);
$date = date("Y-m-d H:i:s",$date_array[1]);
echo "Date: $date:" . $date_array[0]."<br>";

Recommended and use dateTime() class from referenced:

$t = microtime(true);
$micro = sprintf("%06d",($t - floor($t)) * 1000000);
$d = new DateTime( date('Y-m-d H:i:s.'.$micro, $t) );

print $d->format("Y-m-d H:i:s.u"); // note at point on "u"

Note u is microseconds (1 seconds = 1000000 µs).

Another example from

$d2=new DateTime("2012-07-08 11:14:15.889342");

Reference of dateTime() on

I've answered on question as short and simplify to author. Please see for more information to author: getting date format m-d-Y H:i:s.u from milliseconds

How can I discard remote changes and mark a file as "resolved"?

git checkout has the --ours option to check out the version of the file that you had locally (as opposed to --theirs, which is the version that you pulled in). You can pass . to git checkout to tell it to check out everything in the tree. Then you need to mark the conflicts as resolved, which you can do with git add, and commit your work once done:

git checkout --ours .  # checkout our local version of all files
git add -u             # mark all conflicted files as merged
git commit             # commit the merge

Note the . in the git checkout command. That's very important, and easy to miss. git checkout has two modes; one in which it switches branches, and one in which it checks files out of the index into the working copy (sometimes pulling them into the index from another revision first). The way it distinguishes is by whether you've passed a filename in; if you haven't passed in a filename, it tries switching branches (though if you don't pass in a branch either, it will just try checking out the current branch again), but it refuses to do so if there are modified files that that would effect. So, if you want a behavior that will overwrite existing files, you need to pass in . or a filename in order to get the second behavior from git checkout.

It's also a good habit to have, when passing in a filename, to offset it with --, such as git checkout --ours -- <filename>. If you don't do this, and the filename happens to match the name of a branch or tag, Git will think that you want to check that revision out, instead of checking that filename out, and so use the first form of the checkout command.

I'll expand a bit on how conflicts and merging work in Git. When you merge in someone else's code (which also happens during a pull; a pull is essentially a fetch followed by a merge), there are few possible situations.

The simplest is that you're on the same revision. In this case, you're "already up to date", and nothing happens.

Another possibility is that their revision is simply a descendent of yours, in which case you will by default have a "fast-forward merge", in which your HEAD is just updated to their commit, with no merging happening (this can be disabled if you really want to record a merge, using --no-ff).

Then you get into the situations in which you actually need to merge two revisions. In this case, there are two possible outcomes. One is that the merge happens cleanly; all of the changes are in different files, or are in the same files but far enough apart that both sets of changes can be applied without problems. By default, when a clean merge happens, it is automatically committed, though you can disable this with --no-commit if you need to edit it beforehand (for instance, if you rename function foo to bar, and someone else adds new code that calls foo, it will merge cleanly, but produce a broken tree, so you may want to clean that up as part of the merge commit in order to avoid having any broken commits).

The final possibility is that there's a real merge, and there are conflicts. In this case, Git will do as much of the merge as it can, and produce files with conflict markers (<<<<<<<, =======, and >>>>>>>) in your working copy. In the index (also known as the "staging area"; the place where files are stored by git add before committing them), you will have 3 versions of each file with conflicts; there is the original version of the file from the ancestor of the two branches you are merging, the version from HEAD (your side of the merge), and the version from the remote branch.

In order to resolve the conflict, you can either edit the file that is in your working copy, removing the conflict markers and fixing the code up so that it works. Or, you can check out the version from one or the other sides of the merge, using git checkout --ours or git checkout --theirs. Once you have put the file into the state you want it, you indicate that you are done merging the file and it is ready to commit using git add, and then you can commit the merge with git commit.

How to run cron once, daily at 10pm

Here is what I look at everytime I am writing a new crontab entry:

To start editing from terminal -type:

 zee$ crontab -e

what you will add to crontab file:

0 22 * * 0  some-user /opt/somescript/to/

What it means:

+ user => 'some-user',      
+ minute => ‘0’,             <<= on top of the hour.
+ hour => '22',              <<= at 10 PM. Military time.
+ monthday => '*',           <<= Every day of the month*
+ month => '*',              <<= Every month*
+ weekday => ‘0’,            <<= Everyday (0 thru 6) = sunday thru saturday

Also, check what shell your machine is running and name the the file accordingly OR it wont execute.

Check the shell with either echo $SHELL or echo $0

It can be "Bourne shell (sh) , Bourne again shell (bash),Korn shell (ksh)..etc"

VS2010 How to include files in project, to copy them to build output directory automatically during build or publish

Just so my fellow neuronically impaired comrades might chance upon it here, I had assumed that, for web projects, if the linked file was an external .config file that the "output directory" would be the same directory that web.config lives in, i.e. your web project's root. In retrospect, it is entirely unsurprising that it copies the linked file into the root/bin folder.

So, if it's an appSettings include file, your web.config's open tag would be

<appSettings file=".\bin\includedAppSettingsFile.config">


Select second last element with css

Note: Posted this answer because OP later stated in comments that they need to select the last two elements, not just the second to last one.

The :nth-child CSS3 selector is in fact more capable than you ever imagined!

For example, this will select the last 2 elements of #container:

#container :nth-last-child(-n+2) {}

But this is just the beginning of a beautiful friendship.

#container :nth-last-child(-n+2) {
  background-color: cyan;
<div id="container">
 <div>SELECT THIS</div>
 <div>SELECT THIS</div>

How to reverse a singly linked list using only two pointers?

I don't understand why there is need to return head as we are passing it as argument. We are passing head of the link list then we can update also. Below is simple solution.


struct NODE
    struct NODE *next;
    int value;

typedef struct NODE node;

void reverse(node **head);
void add_end(node **head,int val);
void alloc(node **p);
void print_all(node *head);

void main()
    node *head;
    head = NULL;
    add_end( &head, 1 );
    add_end( &head, 2 );
    add_end( &head, 3 );
    print_all( head );
    reverse( &head );
    print_all( head );
void alloc(node **p)
    node *temp;
    temp = (node *) malloc( sizeof(node *) );
    temp->next = NULL;
    *p = temp;
void add_end(node **head,int val)
    node *temp,*new_node;
    new_node->value = val;
    if( *head == NULL )
        *head = new_node;
    for(temp = *head;temp->next!=NULL;temp=temp->next);
    temp->next = new_node;
void print_all(node *head)
    node *temp;
    int index=0;
    printf ("\n\n");
    if (head == NULL)
        printf (" List is Empty \n");
    for (temp=head; temp != NULL; temp=temp->next,index++)
        printf (" %d ==> %d \n",index,temp->value);
void reverse(node **head)
    node *next,*new_head;
    while(*head != NULL)
        next = (*head)->next;
        (*head)->next = new_head;
        new_head = (*head);
        (*head) = next;

Disable LESS-CSS Overwriting calc()

Example for escaped string with variable:

@some-variable-height: 10px;


div {
    height: ~"calc(100vh - "@some-variable-height~")";

compiles to

div {
    height: calc(100vh - 10px );

Show DataFrame as table in iPython Notebook

You'll need to use the HTML() or display() functions from IPython's display module:

from IPython.display import display, HTML

# Assuming that dataframes df1 and df2 are already defined:
print "Dataframe 1:"
print "Dataframe 2:"

Note that if you just print df1.to_html() you'll get the raw, unrendered HTML.

You can also import from IPython.core.display with the same effect

Duplicate Entire MySQL Database

Once upon a time in MySQL you could just copy all the table files to another directory in the mysql tree

mysql cli - create database db2

linux cli - cp db1 db2

How to reset all checkboxes using jQuery or pure JS?

If you want to use form's reset feature, you'd better to use this:




Looks like removeAttr() can not be reset by form.reset().

Assigning more than one class for one event

    $('.tag1, .tag2').on('click', function() {

      if ($(this).hasClass('clickedTag')){
         // code here
      } else {
         // and here



function dothing() {
   if ($(this).hasClass('clickedTag')){
        // code here
    } else {
        // and here

$('.tag1, .tag2').on('click', dothing);


 $('[class^=tag]').on('click', dothing);

Can't import javax.servlet.annotation.WebServlet

I had the same issue, it turns that I had my project configured as many of you stated above, yet the problem persisted, so I went deeper and came across that I was using Apache Tomcat 6 as my Runtime Server, so the fix was simple, I just upgraded the project to use Apache Tomcat 7 and that's all, finally the IDE recognized javax.servlet.annotation.WebServlet annotation.

How to turn IDENTITY_INSERT on and off using SQL Server 2008?

I had a problem where it did not allow me to insert it even after setting the IDENTITY_INSERT ON.

The problem was that i did not specify the column names and for some reason it did not like it.

INSERT INTO tbl Values(vals)

So basically do the full INSERT INTO tbl(cols) Values(vals)

How to force the browser to reload cached CSS and JavaScript files

If you are using a modern browser, you could use a manifest file to inform the browsers which files need to be updated. This requires no headers, no versions in URLs, etc.

For more details, see: Using the application cache

JAXB: how to marshall map into <key>value</key>

Jackson has an XmlMapper which will support this out of the box, no need to write any code at all.

Here's a nice tutorial

Maven dependency:


For writing a Map to xml:

Map<String, String> map = new HashMap<>();
map.put("SomeKey", "someValue");

XmlMapper mapper = new XmlMapper();
String xml = mapper.writeValueAsString(map);

Will give you


I was able to customise the root element by creating a HashMap subclass

@JacksonXmlRootElement(localName = "MyRootElement")
public class XmlHashMap<K, V> extends HashMap<K, V>


So now

Map<String, String> map = new XmlHashMap<>();
map.put("SomeKey", "someValue");

XmlMapper mapper = new XmlMapper();
String xml = mapper.writeValueAsString(map);

Will give you


How to echo or print an array in PHP?

I checked the answer however, (for each) in PHP is deprecated and no longer work with the latest php versions.

Usually we would convert an array into a string to log it somewhere, perhaps debugging or test etc.

I would convert the array into a string by doing:

$Output = implode(",", $SourceArray);


$output is the result (where the string would be generated

",": is the separator (between each array field

$SourceArray: is your source array.

I hope this helps

Input type=password, don't let browser remember the password

Read also this answer where he is using this easy solution that works everywhere (see also the fix for Safari mobile):

<input type="password" readonly onfocus="this.removeAttribute('readonly');"/>

Key Value Pair List

Using one of the subsets method in this question

var list = new List<KeyValuePair<string, int>>() { 
    new KeyValuePair<string, int>("A", 1),
    new KeyValuePair<string, int>("B", 0),
    new KeyValuePair<string, int>("C", 0),
    new KeyValuePair<string, int>("D", 2),
    new KeyValuePair<string, int>("E", 8),

int input = 11;
var items = SubSets(list).FirstOrDefault(x => x.Sum(y => y.Value)==input);


a full console application:

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication1
    class Program
        static void Main(string[] args)
            var list = new List<KeyValuePair<string, int>>() { 
                new KeyValuePair<string, int>("A", 1),
                new KeyValuePair<string, int>("B", 2),
                new KeyValuePair<string, int>("C", 3),
                new KeyValuePair<string, int>("D", 4),
                new KeyValuePair<string, int>("E", 5),
                new KeyValuePair<string, int>("F", 6),

            int input = 12;
            var alternatives = list.SubSets().Where(x => x.Sum(y => y.Value) == input);

            foreach (var res in alternatives)
                Console.WriteLine(String.Join(",", res.Select(x => x.Key)));

    public static class Extenions
        public static IEnumerable<IEnumerable<T>> SubSets<T>(this IEnumerable<T> enumerable)
            List<T> list = enumerable.ToList();
            ulong upper = (ulong)1 << list.Count;

            for (ulong i = 0; i < upper; i++)
                List<T> l = new List<T>(list.Count);
                for (int j = 0; j < sizeof(ulong) * 8; j++)
                    if (((ulong)1 << j) >= upper) break;

                    if (((i >> j) & 1) == 1)

                yield return l;

Is there a performance difference between CTE , Sub-Query, Temporary Table or Table Variable?

SQL is a declarative language, not a procedural language. That is, you construct a SQL statement to describe the results that you want. You are not telling the SQL engine how to do the work.

As a general rule, it is a good idea to let the SQL engine and SQL optimizer find the best query plan. There are many person-years of effort that go into developing a SQL engine, so let the engineers do what they know how to do.

Of course, there are situations where the query plan is not optimal. Then you want to use query hints, restructure the query, update statistics, use temporary tables, add indexes, and so on to get better performance.

As for your question. The performance of CTEs and subqueries should, in theory, be the same since both provide the same information to the query optimizer. One difference is that a CTE used more than once could be easily identified and calculated once. The results could then be stored and read multiple times. Unfortunately, SQL Server does not seem to take advantage of this basic optimization method (you might call this common subquery elimination).

Temporary tables are a different matter, because you are providing more guidance on how the query should be run. One major difference is that the optimizer can use statistics from the temporary table to establish its query plan. This can result in performance gains. Also, if you have a complicated CTE (subquery) that is used more than once, then storing it in a temporary table will often give a performance boost. The query is executed only once.

The answer to your question is that you need to play around to get the performance you expect, particularly for complex queries that are run on a regular basis. In an ideal world, the query optimizer would find the perfect execution path. Although it often does, you may be able to find a way to get better performance.

Shadow Effect for a Text in Android?

Perhaps you'd consider using android:shadowColor, android:shadowDx, android:shadowDy, android:shadowRadius; alternatively setShadowLayer() ?

How do I retrieve an HTML element's actual width and height?

Take a look at Element.getBoundingClientRect().

This method will return an object containing the width, height, and some other useful values:

    width: 960,
    height: 71,
    top: 603,
    bottom: 674,
    left: 360,
    right: 1320

For Example:

var element = document.getElementById('foo');
var positionInfo = element.getBoundingClientRect();
var height = positionInfo.height;
var width = positionInfo.width;

I believe this does not have the issues that .offsetWidth and .offsetHeight do where they sometimes return 0 (as discussed in the comments here)

Another difference is getBoundingClientRect() may return fractional pixels, where .offsetWidth and .offsetHeight will round to the nearest integer.

IE8 Note: getBoundingClientRect does not return height and width on IE8 and below.*

If you must support IE8, use .offsetWidth and .offsetHeight:

var height = element.offsetHeight;
var width = element.offsetWidth;

Its worth noting that the Object returned by this method is not really a normal object. Its properties are not enumerable (so, for example, Object.keys doesn't work out-of-the-box.)

More info on this here: How best to convert a ClientRect / DomRect into a plain Object


PHP: Limit foreach() statement?

In PHP 5.5+, you can do

function limit($iterable, $limit) {
    foreach ($iterable as $key => $value) {
        if (!$limit--) break;
        yield $key => $value;

foreach (limit($arr, 10) as $key => $value) {
    // do stuff

Generators rock.

Bootstrap - dropdown menu not working?

This is a Rails specific answer, but I had this same problem with Bootstrap dropdown menus in my Rails app. What fixed it was adding this to app/assets/javascripts/application.js:

//= require bootstrap

Hope that helps someone.

Python 'If not' syntax

Yes, if bar is not None is more explicit, and thus better, assuming it is indeed what you want. That's not always the case, there are subtle differences: if not bar: will execute if bar is any kind of zero or empty container, or False. Many people do use not bar where they really do mean bar is not None.

Java out.println() how is this possible?

out is a PrintStream type of static variable(object) of System class and println() is function of the PrintStream class.

class PrintStream
    public void println(){}    //member function

class System
    public static final PrintStream out;   //data member

That is why the static variable(object) out is accessed with the class name System which further invokes the method println() of it's type PrintStream (which is a class).

What is Java Servlet?

What is a Servlet?

  • A servlet is simply a class which responds to a particular type of network request - most commonly an HTTP request.
  • Basically servlets are usually used to implement web applications - but there are also various frameworks which operate on top of servlets (e.g. Struts) to give a higher-level abstraction than the "here's an HTTP request, write to this HTTP response" level which servlets provide.
  • Servlets run in a servlet container which handles the networking side (e.g. parsing an HTTP request, connection handling etc). One of the best-known open source servlet containers is Tomcat.

  • In a request/response paradigm, a web server can serve only static pages to the client

  • To serve dynamic pages, a we require Servlets.
  • Servlet is nothing but a Java program
  • This Java program doesn’t have a main method. It only has some callback methods.
  • How does the web server communicate to the servlet? Via container or Servlet engine.
  • Servlet lives and dies within a web container.
  • Web container is responsible for invoking methods in a servlets. It knows what callback methods the Servlet has.

Flow of Request

  • Client sends HTTP request to Web server
  • Web server forwards that HTTP request to web container.
  • Since Servlet can not understand HTTP, its a Java program, it only understands objects, so web container converts that request into valid request object
  • Web container spins a thread for each request
  • All the business logic goes inside doGet() or doPost() callback methods inside the servlets
  • Servlet builds a Java response object and sends it to the container. It converts that to HTTP response again to send it to the client

How does the Container know which Servlet client has requested for?

  • There’s a file called web.xml
  • This is the master file for a web container
  • You have information about servlet in this file-

    • servlets
      • Servlet-name
      • Servlet-class
    • servlet-mappings- the path like /Login or /Notifications is mapped here in
      • Servlet-name
      • url-pattern
    • and so on
  • Every servlet in the web app should have an entry into this file

  • So this lookup happens like- url-pattern -> servlet-name -> servlet-class

How to "install" Servlets? * Well, the servlet objects are inherited from the library- javax.servlet.* . Tomcat and Spring can be used to utilize these objects to fit the use case.

Ref- Watch this on 1.5x- . This has an awesome explanation.

Printing list elements on separated lines in Python

Another good option for handling this kind of option is the pprint module, which (among other things) pretty prints long lists with one element per line:

>>> import sys
>>> import pprint
>>> pprint.pprint(sys.path)

How to change color in markdown cells ipython/jupyter notebook?

Similarly to Jakob's answer, you can use HTML tags. Just a note that the color attribute of font (<font color=...>) is deprecated in HTML5. The following syntax would be HTML5-compliant:

This <span style="color:red">word</span> is not black.

Same caution that Jakob made probably still applies:

Be aware that this will not survive a conversion of the notebook to latex.

django - get() returned more than one topic

Get is supposed to return, one and exactly one record, to fix this use filter(), and then take first element of the queryset returned to get the object you were expecting from get, also it would be useful to check if atleast one record is returned before taking out the first element to avoid IndexError

How can one print a size_t variable portably using the printf family?

Use the z modifier:

size_t x = ...;
ssize_t y = ...;
printf("%zu\n", x);  // prints as unsigned decimal
printf("%zx\n", x);  // prints as hex
printf("%zd\n", y);  // prints as signed decimal

Group By Multiple Columns

C# 7.1 or greater using Tuples and Inferred tuple element names (currently it works only with linq to objects and it is not supported when expression trees are required e.g. someIQueryable.GroupBy(...). Github issue):

// declarative query syntax
var result = 
    from x in inMemoryTable
    group x by (x.Column1, x.Column2) into g
    select (g.Key.Column1, g.Key.Column2, QuantitySum: g.Sum(x => x.Quantity));

// or method syntax
var result2 = inMemoryTable.GroupBy(x => (x.Column1, x.Column2))
    .Select(g => (g.Key.Column1, g.Key.Column2, QuantitySum: g.Sum(x => x.Quantity)));

C# 3 or greater using anonymous types:

// declarative query syntax
var result3 = 
    from x in table
    group x by new { x.Column1, x.Column2 } into g
    select new { g.Key.Column1, g.Key.Column2, QuantitySum = g.Sum(x => x.Quantity) };

// or method syntax
var result4 = table.GroupBy(x => new { x.Column1, x.Column2 })
    .Select(g => 
      new { g.Key.Column1, g.Key.Column2 , QuantitySum= g.Sum(x => x.Quantity) });

Any way to return PHP `json_encode` with encode UTF-8 and not Unicode?

Use JSON_UNESCAPED_UNICODE inside json_encode() if your php version >=5.4.

How to connect mySQL database using C++

Finally I could successfully compile a program with C++ connector in Ubuntu 12.04 I have installed the connector using this command

'apt-get install libmysqlcppconn-dev'

Initially I faced the same problem with "undefined reference to `get_driver_instance' " to solve this I declare my driver instance variable of MySQL_Driver type. For ready reference this type is defined in mysql_driver.h file. Here is the code snippet I used in my program.

sql::mysql::MySQL_Driver *driver;
try {     
    driver = sql::mysql::get_driver_instance();

and I compiled the program with -l mysqlcppconn linker option

and don't forget to include this header

#include "mysql_driver.h" 

What is the best way to determine a session variable is null or empty in C#?

I also like to wrap session variables in properties. The setters here are trivial, but I like to write the get methods so they have only one exit point. To do that I usually check for null and set it to a default value before returning the value of the session variable. Something like this:

string Name
       if(Session["Name"] == Null)
           Session["Name"] = "Default value";
       return (string)Session["Name"];
   set { Session["Name"] = value; }


Generating a drop down list of timezones with PHP

If you don't want to be dependent on static timezone list, or want to display the offset along with timezone.

Here is what I came up with

function timezones()
    $timezones = \DateTimeZone::listIdentifiers();
    $items = array();
    foreach($timezones as $timezoneId) {
        $timezone = new \DateTimeZone($timezoneId);
        $offsetInSeconds = $timezone->getOffset(new \DateTime());
        $items[$timezoneId] = $offsetInSeconds;
    array_walk ($items, function (&$offsetInSeconds, &$timezoneId) { 
        $offsetPrefix = $offsetInSeconds < 0 ? '-' : '+';
        $offset = gmdate('H:i', abs($offsetInSeconds));
        $offset = "(GMT${offsetPrefix}${offset}) ".$timezoneId;
        $offsetInSeconds = $offset;
    return $items;

Which gives me the following result

    [Pacific/Midway] => (GMT-11:00) Pacific/Midway
    [Pacific/Pago_Pago] => (GMT-11:00) Pacific/Pago_Pago
    [Pacific/Niue] => (GMT-11:00) Pacific/Niue
    [America/Adak] => (GMT-10:00) America/Adak
    [Pacific/Tahiti] => (GMT-10:00) Pacific/Tahiti
    [Pacific/Rarotonga] => (GMT-10:00) Pacific/Rarotonga
    [Pacific/Honolulu] => (GMT-10:00) Pacific/Honolulu
    [Pacific/Marquesas] => (GMT-09:30) Pacific/Marquesas
    [America/Sitka] => (GMT-09:00) America/Sitka
    [Pacific/Gambier] => (GMT-09:00) Pacific/Gambier
    [America/Yakutat] => (GMT-09:00) America/Yakutat
    [America/Juneau] => (GMT-09:00) America/Juneau
    [America/Nome] => (GMT-09:00) America/Nome
    [America/Anchorage] => (GMT-09:00) America/Anchorage
    [America/Metlakatla] => (GMT-09:00) America/Metlakatla
    [America/Los_Angeles] => (GMT-08:00) America/Los_Angeles
    [America/Tijuana] => (GMT-08:00) America/Tijuana
    [America/Whitehorse] => (GMT-08:00) America/Whitehorse
    [America/Vancouver] => (GMT-08:00) America/Vancouver
    [America/Dawson] => (GMT-08:00) America/Dawson
    [Pacific/Pitcairn] => (GMT-08:00) Pacific/Pitcairn
    [America/Mazatlan] => (GMT-07:00) America/Mazatlan
    [America/Fort_Nelson] => (GMT-07:00) America/Fort_Nelson
    [America/Yellowknife] => (GMT-07:00) America/Yellowknife
    [America/Inuvik] => (GMT-07:00) America/Inuvik
    [America/Edmonton] => (GMT-07:00) America/Edmonton
    [America/Denver] => (GMT-07:00) America/Denver
    [America/Chihuahua] => (GMT-07:00) America/Chihuahua
    [America/Boise] => (GMT-07:00) America/Boise
    [America/Ojinaga] => (GMT-07:00) America/Ojinaga
    [America/Cambridge_Bay] => (GMT-07:00) America/Cambridge_Bay
    [America/Dawson_Creek] => (GMT-07:00) America/Dawson_Creek
    [America/Phoenix] => (GMT-07:00) America/Phoenix
    [America/Hermosillo] => (GMT-07:00) America/Hermosillo
    [America/Creston] => (GMT-07:00) America/Creston
    [America/Matamoros] => (GMT-06:00) America/Matamoros
    [America/Menominee] => (GMT-06:00) America/Menominee
    [America/Indiana/Knox] => (GMT-06:00) America/Indiana/Knox
    [America/Managua] => (GMT-06:00) America/Managua
    [America/Bahia_Banderas] => (GMT-06:00) America/Bahia_Banderas
    [America/Indiana/Tell_City] => (GMT-06:00) America/Indiana/Tell_City
    [America/Belize] => (GMT-06:00) America/Belize
    [America/Chicago] => (GMT-06:00) America/Chicago
    [America/Guatemala] => (GMT-06:00) America/Guatemala
    [America/El_Salvador] => (GMT-06:00) America/El_Salvador
    [America/Merida] => (GMT-06:00) America/Merida
    [America/Costa_Rica] => (GMT-06:00) America/Costa_Rica
    [America/Mexico_City] => (GMT-06:00) America/Mexico_City
    [America/Winnipeg] => (GMT-06:00) America/Winnipeg
    [Pacific/Galapagos] => (GMT-06:00) Pacific/Galapagos
    [America/Resolute] => (GMT-06:00) America/Resolute
    [America/Regina] => (GMT-06:00) America/Regina
    [America/Rankin_Inlet] => (GMT-06:00) America/Rankin_Inlet
    [America/Rainy_River] => (GMT-06:00) America/Rainy_River
    [America/North_Dakota/New_Salem] => (GMT-06:00) America/North_Dakota/New_Salem
    [America/North_Dakota/Beulah] => (GMT-06:00) America/North_Dakota/Beulah
    [America/North_Dakota/Center] => (GMT-06:00) America/North_Dakota/Center
    [America/Tegucigalpa] => (GMT-06:00) America/Tegucigalpa
    [America/Swift_Current] => (GMT-06:00) America/Swift_Current
    [America/Monterrey] => (GMT-06:00) America/Monterrey
    [America/Pangnirtung] => (GMT-05:00) America/Pangnirtung
    [America/Indiana/Petersburg] => (GMT-05:00) America/Indiana/Petersburg
    [America/Indiana/Marengo] => (GMT-05:00) America/Indiana/Marengo
    [America/Bogota] => (GMT-05:00) America/Bogota
    [America/Toronto] => (GMT-05:00) America/Toronto
    [America/Detroit] => (GMT-05:00) America/Detroit
    [America/Panama] => (GMT-05:00) America/Panama
    [America/Cancun] => (GMT-05:00) America/Cancun
    [America/Rio_Branco] => (GMT-05:00) America/Rio_Branco
    [America/Port-au-Prince] => (GMT-05:00) America/Port-au-Prince
    [America/Cayman] => (GMT-05:00) America/Cayman
    [America/Grand_Turk] => (GMT-05:00) America/Grand_Turk
    [America/Havana] => (GMT-05:00) America/Havana
    [America/Indiana/Indianapolis] => (GMT-05:00) America/Indiana/Indianapolis
    [America/Indiana/Vevay] => (GMT-05:00) America/Indiana/Vevay
    [America/Guayaquil] => (GMT-05:00) America/Guayaquil
    [America/Nipigon] => (GMT-05:00) America/Nipigon
    [America/Indiana/Vincennes] => (GMT-05:00) America/Indiana/Vincennes
    [America/Atikokan] => (GMT-05:00) America/Atikokan
    [America/Indiana/Winamac] => (GMT-05:00) America/Indiana/Winamac
    [America/New_York] => (GMT-05:00) America/New_York
    [America/Iqaluit] => (GMT-05:00) America/Iqaluit
    [America/Jamaica] => (GMT-05:00) America/Jamaica
    [America/Nassau] => (GMT-05:00) America/Nassau
    [America/Kentucky/Louisville] => (GMT-05:00) America/Kentucky/Louisville
    [America/Kentucky/Monticello] => (GMT-05:00) America/Kentucky/Monticello
    [America/Eirunepe] => (GMT-05:00) America/Eirunepe
    [Pacific/Easter] => (GMT-05:00) Pacific/Easter
    [America/Lima] => (GMT-05:00) America/Lima
    [America/Thunder_Bay] => (GMT-05:00) America/Thunder_Bay
    [America/Guadeloupe] => (GMT-04:00) America/Guadeloupe
    [America/Manaus] => (GMT-04:00) America/Manaus
    [America/Guyana] => (GMT-04:00) America/Guyana
    [America/Halifax] => (GMT-04:00) America/Halifax
    [America/Puerto_Rico] => (GMT-04:00) America/Puerto_Rico
    [America/Porto_Velho] => (GMT-04:00) America/Porto_Velho
    [America/Port_of_Spain] => (GMT-04:00) America/Port_of_Spain
    [America/Montserrat] => (GMT-04:00) America/Montserrat
    [America/Moncton] => (GMT-04:00) America/Moncton
    [America/Martinique] => (GMT-04:00) America/Martinique
    [America/Kralendijk] => (GMT-04:00) America/Kralendijk
    [America/La_Paz] => (GMT-04:00) America/La_Paz
    [America/Marigot] => (GMT-04:00) America/Marigot
    [America/Lower_Princes] => (GMT-04:00) America/Lower_Princes
    [America/Grenada] => (GMT-04:00) America/Grenada
    [America/Santo_Domingo] => (GMT-04:00) America/Santo_Domingo
    [America/Goose_Bay] => (GMT-04:00) America/Goose_Bay
    [America/Caracas] => (GMT-04:00) America/Caracas
    [America/Anguilla] => (GMT-04:00) America/Anguilla
    [America/St_Barthelemy] => (GMT-04:00) America/St_Barthelemy
    [America/Barbados] => (GMT-04:00) America/Barbados
    [America/St_Kitts] => (GMT-04:00) America/St_Kitts
    [America/Blanc-Sablon] => (GMT-04:00) America/Blanc-Sablon
    [America/Boa_Vista] => (GMT-04:00) America/Boa_Vista
    [America/St_Lucia] => (GMT-04:00) America/St_Lucia
    [America/St_Thomas] => (GMT-04:00) America/St_Thomas
    [America/Antigua] => (GMT-04:00) America/Antigua
    [America/St_Vincent] => (GMT-04:00) America/St_Vincent
    [America/Thule] => (GMT-04:00) America/Thule
    [America/Curacao] => (GMT-04:00) America/Curacao
    [America/Tortola] => (GMT-04:00) America/Tortola
    [America/Dominica] => (GMT-04:00) America/Dominica
    [Atlantic/Bermuda] => (GMT-04:00) Atlantic/Bermuda
    [America/Glace_Bay] => (GMT-04:00) America/Glace_Bay
    [America/Aruba] => (GMT-04:00) America/Aruba
    [America/St_Johns] => (GMT-03:30) America/St_Johns
    [America/Argentina/Tucuman] => (GMT-03:00) America/Argentina/Tucuman
    [America/Belem] => (GMT-03:00) America/Belem
    [America/Santiago] => (GMT-03:00) America/Santiago
    [America/Santarem] => (GMT-03:00) America/Santarem
    [America/Recife] => (GMT-03:00) America/Recife
    [America/Punta_Arenas] => (GMT-03:00) America/Punta_Arenas
    [Atlantic/Stanley] => (GMT-03:00) Atlantic/Stanley
    [America/Paramaribo] => (GMT-03:00) America/Paramaribo
    [America/Fortaleza] => (GMT-03:00) America/Fortaleza
    [America/Argentina/San_Luis] => (GMT-03:00) America/Argentina/San_Luis
    [Antarctica/Palmer] => (GMT-03:00) Antarctica/Palmer
    [America/Montevideo] => (GMT-03:00) America/Montevideo
    [America/Cuiaba] => (GMT-03:00) America/Cuiaba
    [America/Miquelon] => (GMT-03:00) America/Miquelon
    [America/Cayenne] => (GMT-03:00) America/Cayenne
    [America/Campo_Grande] => (GMT-03:00) America/Campo_Grande
    [Antarctica/Rothera] => (GMT-03:00) Antarctica/Rothera
    [America/Godthab] => (GMT-03:00) America/Godthab
    [America/Bahia] => (GMT-03:00) America/Bahia
    [America/Asuncion] => (GMT-03:00) America/Asuncion
    [America/Argentina/Ushuaia] => (GMT-03:00) America/Argentina/Ushuaia
    [America/Argentina/La_Rioja] => (GMT-03:00) America/Argentina/La_Rioja
    [America/Araguaina] => (GMT-03:00) America/Araguaina
    [America/Argentina/Buenos_Aires] => (GMT-03:00) America/Argentina/Buenos_Aires
    [America/Argentina/Rio_Gallegos] => (GMT-03:00) America/Argentina/Rio_Gallegos
    [America/Argentina/Catamarca] => (GMT-03:00) America/Argentina/Catamarca
    [America/Maceio] => (GMT-03:00) America/Maceio
    [America/Argentina/San_Juan] => (GMT-03:00) America/Argentina/San_Juan
    [America/Argentina/Salta] => (GMT-03:00) America/Argentina/Salta
    [America/Argentina/Mendoza] => (GMT-03:00) America/Argentina/Mendoza
    [America/Argentina/Cordoba] => (GMT-03:00) America/Argentina/Cordoba
    [America/Argentina/Jujuy] => (GMT-03:00) America/Argentina/Jujuy
    [Atlantic/South_Georgia] => (GMT-02:00) Atlantic/South_Georgia
    [America/Noronha] => (GMT-02:00) America/Noronha
    [America/Sao_Paulo] => (GMT-02:00) America/Sao_Paulo
    [Atlantic/Cape_Verde] => (GMT-01:00) Atlantic/Cape_Verde
    [Atlantic/Azores] => (GMT-01:00) Atlantic/Azores
    [America/Scoresbysund] => (GMT-01:00) America/Scoresbysund
    [Europe/Lisbon] => (GMT+00:00) Europe/Lisbon
    [Europe/London] => (GMT+00:00) Europe/London
    [Europe/Jersey] => (GMT+00:00) Europe/Jersey
    [Europe/Isle_of_Man] => (GMT+00:00) Europe/Isle_of_Man
    [Atlantic/Faroe] => (GMT+00:00) Atlantic/Faroe
    [Europe/Guernsey] => (GMT+00:00) Europe/Guernsey
    [Europe/Dublin] => (GMT+00:00) Europe/Dublin
    [Atlantic/St_Helena] => (GMT+00:00) Atlantic/St_Helena
    [Atlantic/Reykjavik] => (GMT+00:00) Atlantic/Reykjavik
    [Atlantic/Madeira] => (GMT+00:00) Atlantic/Madeira
    [Atlantic/Canary] => (GMT+00:00) Atlantic/Canary
    [Africa/Accra] => (GMT+00:00) Africa/Accra
    [Antarctica/Troll] => (GMT+00:00) Antarctica/Troll
    [Africa/Abidjan] => (GMT+00:00) Africa/Abidjan
    [UTC] => (GMT+00:00) UTC
    [America/Danmarkshavn] => (GMT+00:00) America/Danmarkshavn
    [Africa/Monrovia] => (GMT+00:00) Africa/Monrovia
    [Africa/Dakar] => (GMT+00:00) Africa/Dakar
    [Africa/Conakry] => (GMT+00:00) Africa/Conakry
    [Africa/Casablanca] => (GMT+00:00) Africa/Casablanca
    [Africa/Lome] => (GMT+00:00) Africa/Lome
    [Africa/Freetown] => (GMT+00:00) Africa/Freetown
    [Africa/El_Aaiun] => (GMT+00:00) Africa/El_Aaiun
    [Africa/Bissau] => (GMT+00:00) Africa/Bissau
    [Africa/Nouakchott] => (GMT+00:00) Africa/Nouakchott
    [Africa/Banjul] => (GMT+00:00) Africa/Banjul
    [Africa/Ouagadougou] => (GMT+00:00) Africa/Ouagadougou
    [Africa/Bamako] => (GMT+00:00) Africa/Bamako
    [Europe/Gibraltar] => (GMT+01:00) Europe/Gibraltar
    [Africa/Bangui] => (GMT+01:00) Africa/Bangui
    [Europe/Ljubljana] => (GMT+01:00) Europe/Ljubljana
    [Africa/Ceuta] => (GMT+01:00) Africa/Ceuta
    [Africa/Algiers] => (GMT+01:00) Africa/Algiers
    [Europe/Busingen] => (GMT+01:00) Europe/Busingen
    [Europe/Copenhagen] => (GMT+01:00) Europe/Copenhagen
    [Europe/Madrid] => (GMT+01:00) Europe/Madrid
    [Europe/Budapest] => (GMT+01:00) Europe/Budapest
    [Europe/Brussels] => (GMT+01:00) Europe/Brussels
    [Europe/Bratislava] => (GMT+01:00) Europe/Bratislava
    [Europe/Berlin] => (GMT+01:00) Europe/Berlin
    [Europe/Belgrade] => (GMT+01:00) Europe/Belgrade
    [Europe/Andorra] => (GMT+01:00) Europe/Andorra
    [Europe/Amsterdam] => (GMT+01:00) Europe/Amsterdam
    [Europe/Luxembourg] => (GMT+01:00) Europe/Luxembourg
    [Europe/Monaco] => (GMT+01:00) Europe/Monaco
    [Europe/Malta] => (GMT+01:00) Europe/Malta
    [Europe/Tirane] => (GMT+01:00) Europe/Tirane
    [Europe/Zurich] => (GMT+01:00) Europe/Zurich
    [Europe/Zagreb] => (GMT+01:00) Europe/Zagreb
    [Europe/Warsaw] => (GMT+01:00) Europe/Warsaw
    [Europe/Vienna] => (GMT+01:00) Europe/Vienna
    [Europe/Vatican] => (GMT+01:00) Europe/Vatican
    [Europe/Vaduz] => (GMT+01:00) Europe/Vaduz
    [Europe/Stockholm] => (GMT+01:00) Europe/Stockholm
    [Africa/Brazzaville] => (GMT+01:00) Africa/Brazzaville
    [Europe/Skopje] => (GMT+01:00) Europe/Skopje
    [Europe/Sarajevo] => (GMT+01:00) Europe/Sarajevo
    [Europe/San_Marino] => (GMT+01:00) Europe/San_Marino
    [Europe/Rome] => (GMT+01:00) Europe/Rome
    [Europe/Prague] => (GMT+01:00) Europe/Prague
    [Europe/Paris] => (GMT+01:00) Europe/Paris
    [Europe/Oslo] => (GMT+01:00) Europe/Oslo
    [Europe/Podgorica] => (GMT+01:00) Europe/Podgorica
    [Africa/Douala] => (GMT+01:00) Africa/Douala
    [Arctic/Longyearbyen] => (GMT+01:00) Arctic/Longyearbyen
    [Africa/Malabo] => (GMT+01:00) Africa/Malabo
    [Africa/Kinshasa] => (GMT+01:00) Africa/Kinshasa
    [Africa/Libreville] => (GMT+01:00) Africa/Libreville
    [Africa/Ndjamena] => (GMT+01:00) Africa/Ndjamena
    [Africa/Lagos] => (GMT+01:00) Africa/Lagos
    [Africa/Niamey] => (GMT+01:00) Africa/Niamey
    [Africa/Porto-Novo] => (GMT+01:00) Africa/Porto-Novo
    [Africa/Sao_Tome] => (GMT+01:00) Africa/Sao_Tome
    [Africa/Luanda] => (GMT+01:00) Africa/Luanda
    [Africa/Tunis] => (GMT+01:00) Africa/Tunis
    [Europe/Uzhgorod] => (GMT+02:00) Europe/Uzhgorod
    [Africa/Harare] => (GMT+02:00) Africa/Harare
    [Europe/Mariehamn] => (GMT+02:00) Europe/Mariehamn
    [Africa/Lubumbashi] => (GMT+02:00) Africa/Lubumbashi
    [Asia/Nicosia] => (GMT+02:00) Asia/Nicosia
    [Africa/Windhoek] => (GMT+02:00) Africa/Windhoek
    [Europe/Tallinn] => (GMT+02:00) Europe/Tallinn
    [Europe/Zaporozhye] => (GMT+02:00) Europe/Zaporozhye
    [Africa/Gaborone] => (GMT+02:00) Africa/Gaborone
    [Africa/Mbabane] => (GMT+02:00) Africa/Mbabane
    [Africa/Khartoum] => (GMT+02:00) Africa/Khartoum
    [Africa/Johannesburg] => (GMT+02:00) Africa/Johannesburg
    [Europe/Vilnius] => (GMT+02:00) Europe/Vilnius
    [Africa/Maseru] => (GMT+02:00) Africa/Maseru
    [Africa/Lusaka] => (GMT+02:00) Africa/Lusaka
    [Europe/Riga] => (GMT+02:00) Europe/Riga
    [Africa/Kigali] => (GMT+02:00) Africa/Kigali
    [Europe/Helsinki] => (GMT+02:00) Europe/Helsinki
    [Africa/Maputo] => (GMT+02:00) Africa/Maputo
    [Europe/Chisinau] => (GMT+02:00) Europe/Chisinau
    [Europe/Sofia] => (GMT+02:00) Europe/Sofia
    [Asia/Beirut] => (GMT+02:00) Asia/Beirut
    [Africa/Blantyre] => (GMT+02:00) Africa/Blantyre
    [Asia/Jerusalem] => (GMT+02:00) Asia/Jerusalem
    [Asia/Gaza] => (GMT+02:00) Asia/Gaza
    [Asia/Amman] => (GMT+02:00) Asia/Amman
    [Asia/Famagusta] => (GMT+02:00) Asia/Famagusta
    [Europe/Athens] => (GMT+02:00) Europe/Athens
    [Africa/Bujumbura] => (GMT+02:00) Africa/Bujumbura
    [Asia/Hebron] => (GMT+02:00) Asia/Hebron
    [Europe/Kaliningrad] => (GMT+02:00) Europe/Kaliningrad
    [Africa/Cairo] => (GMT+02:00) Africa/Cairo
    [Europe/Kiev] => (GMT+02:00) Europe/Kiev
    [Europe/Bucharest] => (GMT+02:00) Europe/Bucharest
    [Asia/Damascus] => (GMT+02:00) Asia/Damascus
    [Africa/Tripoli] => (GMT+02:00) Africa/Tripoli
    [Asia/Baghdad] => (GMT+03:00) Asia/Baghdad
    [Africa/Djibouti] => (GMT+03:00) Africa/Djibouti
    [Asia/Aden] => (GMT+03:00) Asia/Aden
    [Asia/Bahrain] => (GMT+03:00) Asia/Bahrain
    [Europe/Istanbul] => (GMT+03:00) Europe/Istanbul
    [Africa/Juba] => (GMT+03:00) Africa/Juba
    [Europe/Kirov] => (GMT+03:00) Europe/Kirov
    [Europe/Moscow] => (GMT+03:00) Europe/Moscow
    [Antarctica/Syowa] => (GMT+03:00) Antarctica/Syowa
    [Europe/Minsk] => (GMT+03:00) Europe/Minsk
    [Africa/Kampala] => (GMT+03:00) Africa/Kampala
    [Africa/Dar_es_Salaam] => (GMT+03:00) Africa/Dar_es_Salaam
    [Europe/Simferopol] => (GMT+03:00) Europe/Simferopol
    [Asia/Riyadh] => (GMT+03:00) Asia/Riyadh
    [Indian/Antananarivo] => (GMT+03:00) Indian/Antananarivo
    [Asia/Kuwait] => (GMT+03:00) Asia/Kuwait
    [Africa/Nairobi] => (GMT+03:00) Africa/Nairobi
    [Indian/Mayotte] => (GMT+03:00) Indian/Mayotte
    [Africa/Mogadishu] => (GMT+03:00) Africa/Mogadishu
    [Asia/Qatar] => (GMT+03:00) Asia/Qatar
    [Europe/Volgograd] => (GMT+03:00) Europe/Volgograd
    [Africa/Asmara] => (GMT+03:00) Africa/Asmara
    [Africa/Addis_Ababa] => (GMT+03:00) Africa/Addis_Ababa
    [Indian/Comoro] => (GMT+03:00) Indian/Comoro
    [Asia/Tehran] => (GMT+03:30) Asia/Tehran
    [Europe/Saratov] => (GMT+04:00) Europe/Saratov
    [Indian/Reunion] => (GMT+04:00) Indian/Reunion
    [Europe/Astrakhan] => (GMT+04:00) Europe/Astrakhan
    [Asia/Baku] => (GMT+04:00) Asia/Baku
    [Asia/Dubai] => (GMT+04:00) Asia/Dubai
    [Indian/Mauritius] => (GMT+04:00) Indian/Mauritius
    [Indian/Mahe] => (GMT+04:00) Indian/Mahe
    [Asia/Tbilisi] => (GMT+04:00) Asia/Tbilisi
    [Asia/Yerevan] => (GMT+04:00) Asia/Yerevan
    [Asia/Muscat] => (GMT+04:00) Asia/Muscat
    [Europe/Samara] => (GMT+04:00) Europe/Samara
    [Europe/Ulyanovsk] => (GMT+04:00) Europe/Ulyanovsk
    [Asia/Kabul] => (GMT+04:30) Asia/Kabul
    [Antarctica/Mawson] => (GMT+05:00) Antarctica/Mawson
    [Asia/Samarkand] => (GMT+05:00) Asia/Samarkand
    [Asia/Aqtobe] => (GMT+05:00) Asia/Aqtobe
    [Indian/Maldives] => (GMT+05:00) Indian/Maldives
    [Asia/Ashgabat] => (GMT+05:00) Asia/Ashgabat
    [Asia/Atyrau] => (GMT+05:00) Asia/Atyrau
    [Asia/Dushanbe] => (GMT+05:00) Asia/Dushanbe
    [Asia/Yekaterinburg] => (GMT+05:00) Asia/Yekaterinburg
    [Asia/Oral] => (GMT+05:00) Asia/Oral
    [Asia/Aqtau] => (GMT+05:00) Asia/Aqtau
    [Asia/Karachi] => (GMT+05:00) Asia/Karachi
    [Asia/Tashkent] => (GMT+05:00) Asia/Tashkent
    [Indian/Kerguelen] => (GMT+05:00) Indian/Kerguelen
    [Asia/Colombo] => (GMT+05:30) Asia/Colombo
    [Asia/Kolkata] => (GMT+05:30) Asia/Kolkata
    [Asia/Kathmandu] => (GMT+05:45) Asia/Kathmandu
    [Antarctica/Vostok] => (GMT+06:00) Antarctica/Vostok
    [Indian/Chagos] => (GMT+06:00) Indian/Chagos
    [Asia/Almaty] => (GMT+06:00) Asia/Almaty
    [Asia/Omsk] => (GMT+06:00) Asia/Omsk
    [Asia/Dhaka] => (GMT+06:00) Asia/Dhaka
    [Asia/Bishkek] => (GMT+06:00) Asia/Bishkek
    [Asia/Urumqi] => (GMT+06:00) Asia/Urumqi
    [Asia/Thimphu] => (GMT+06:00) Asia/Thimphu
    [Asia/Qyzylorda] => (GMT+06:00) Asia/Qyzylorda
    [Indian/Cocos] => (GMT+06:30) Indian/Cocos
    [Asia/Yangon] => (GMT+06:30) Asia/Yangon
    [Asia/Novokuznetsk] => (GMT+07:00) Asia/Novokuznetsk
    [Asia/Barnaul] => (GMT+07:00) Asia/Barnaul
    [Antarctica/Davis] => (GMT+07:00) Antarctica/Davis
    [Asia/Novosibirsk] => (GMT+07:00) Asia/Novosibirsk
    [Asia/Krasnoyarsk] => (GMT+07:00) Asia/Krasnoyarsk
    [Asia/Phnom_Penh] => (GMT+07:00) Asia/Phnom_Penh
    [Asia/Pontianak] => (GMT+07:00) Asia/Pontianak
    [Asia/Jakarta] => (GMT+07:00) Asia/Jakarta
    [Asia/Hovd] => (GMT+07:00) Asia/Hovd
    [Asia/Tomsk] => (GMT+07:00) Asia/Tomsk
    [Asia/Ho_Chi_Minh] => (GMT+07:00) Asia/Ho_Chi_Minh
    [Asia/Vientiane] => (GMT+07:00) Asia/Vientiane
    [Indian/Christmas] => (GMT+07:00) Indian/Christmas
    [Asia/Bangkok] => (GMT+07:00) Asia/Bangkok
    [Asia/Choibalsan] => (GMT+08:00) Asia/Choibalsan
    [Asia/Taipei] => (GMT+08:00) Asia/Taipei
    [Asia/Makassar] => (GMT+08:00) Asia/Makassar
    [Asia/Macau] => (GMT+08:00) Asia/Macau
    [Asia/Kuching] => (GMT+08:00) Asia/Kuching
    [Asia/Kuala_Lumpur] => (GMT+08:00) Asia/Kuala_Lumpur
    [Asia/Shanghai] => (GMT+08:00) Asia/Shanghai
    [Asia/Singapore] => (GMT+08:00) Asia/Singapore
    [Asia/Brunei] => (GMT+08:00) Asia/Brunei
    [Asia/Irkutsk] => (GMT+08:00) Asia/Irkutsk
    [Asia/Ulaanbaatar] => (GMT+08:00) Asia/Ulaanbaatar
    [Australia/Perth] => (GMT+08:00) Australia/Perth
    [Asia/Hong_Kong] => (GMT+08:00) Asia/Hong_Kong
    [Antarctica/Casey] => (GMT+08:00) Antarctica/Casey
    [Asia/Manila] => (GMT+08:00) Asia/Manila
    [Australia/Eucla] => (GMT+08:45) Australia/Eucla
    [Asia/Jayapura] => (GMT+09:00) Asia/Jayapura
    [Asia/Khandyga] => (GMT+09:00) Asia/Khandyga
    [Pacific/Palau] => (GMT+09:00) Pacific/Palau
    [Asia/Dili] => (GMT+09:00) Asia/Dili
    [Asia/Yakutsk] => (GMT+09:00) Asia/Yakutsk
    [Asia/Tokyo] => (GMT+09:00) Asia/Tokyo
    [Asia/Seoul] => (GMT+09:00) Asia/Seoul
    [Asia/Chita] => (GMT+09:00) Asia/Chita
    [Asia/Pyongyang] => (GMT+09:00) Asia/Pyongyang
    [Australia/Darwin] => (GMT+09:30) Australia/Darwin
    [Asia/Ust-Nera] => (GMT+10:00) Asia/Ust-Nera
    [Pacific/Chuuk] => (GMT+10:00) Pacific/Chuuk
    [Antarctica/DumontDUrville] => (GMT+10:00) Antarctica/DumontDUrville
    [Pacific/Guam] => (GMT+10:00) Pacific/Guam
    [Pacific/Port_Moresby] => (GMT+10:00) Pacific/Port_Moresby
    [Asia/Vladivostok] => (GMT+10:00) Asia/Vladivostok
    [Australia/Brisbane] => (GMT+10:00) Australia/Brisbane
    [Australia/Lindeman] => (GMT+10:00) Australia/Lindeman
    [Pacific/Saipan] => (GMT+10:00) Pacific/Saipan
    [Australia/Adelaide] => (GMT+10:30) Australia/Adelaide
    [Australia/Broken_Hill] => (GMT+10:30) Australia/Broken_Hill
    [Australia/Sydney] => (GMT+11:00) Australia/Sydney
    [Antarctica/Macquarie] => (GMT+11:00) Antarctica/Macquarie
    [Pacific/Noumea] => (GMT+11:00) Pacific/Noumea
    [Pacific/Norfolk] => (GMT+11:00) Pacific/Norfolk
    [Australia/Melbourne] => (GMT+11:00) Australia/Melbourne
    [Pacific/Kosrae] => (GMT+11:00) Pacific/Kosrae
    [Pacific/Pohnpei] => (GMT+11:00) Pacific/Pohnpei
    [Australia/Currie] => (GMT+11:00) Australia/Currie
    [Pacific/Guadalcanal] => (GMT+11:00) Pacific/Guadalcanal
    [Pacific/Efate] => (GMT+11:00) Pacific/Efate
    [Australia/Hobart] => (GMT+11:00) Australia/Hobart
    [Asia/Magadan] => (GMT+11:00) Asia/Magadan
    [Asia/Sakhalin] => (GMT+11:00) Asia/Sakhalin
    [Pacific/Bougainville] => (GMT+11:00) Pacific/Bougainville
    [Australia/Lord_Howe] => (GMT+11:00) Australia/Lord_Howe
    [Asia/Srednekolymsk] => (GMT+11:00) Asia/Srednekolymsk
    [Pacific/Fiji] => (GMT+12:00) Pacific/Fiji
    [Pacific/Wake] => (GMT+12:00) Pacific/Wake
    [Pacific/Nauru] => (GMT+12:00) Pacific/Nauru
    [Pacific/Majuro] => (GMT+12:00) Pacific/Majuro
    [Asia/Kamchatka] => (GMT+12:00) Asia/Kamchatka
    [Pacific/Kwajalein] => (GMT+12:00) Pacific/Kwajalein
    [Pacific/Funafuti] => (GMT+12:00) Pacific/Funafuti
    [Pacific/Wallis] => (GMT+12:00) Pacific/Wallis
    [Asia/Anadyr] => (GMT+12:00) Asia/Anadyr
    [Pacific/Tarawa] => (GMT+12:00) Pacific/Tarawa
    [Pacific/Fakaofo] => (GMT+13:00) Pacific/Fakaofo
    [Pacific/Enderbury] => (GMT+13:00) Pacific/Enderbury
    [Pacific/Auckland] => (GMT+13:00) Pacific/Auckland
    [Antarctica/McMurdo] => (GMT+13:00) Antarctica/McMurdo
    [Pacific/Tongatapu] => (GMT+13:00) Pacific/Tongatapu
    [Pacific/Chatham] => (GMT+13:45) Pacific/Chatham
    [Pacific/Kiritimati] => (GMT+14:00) Pacific/Kiritimati
    [Pacific/Apia] => (GMT+14:00) Pacific/Apia

Using number as "index" (JSON)

JSON only allows key names to be strings. Those strings can consist of numerical values.

You aren't using JSON though. You have a JavaScript object literal. You can use identifiers for keys, but an identifier can't start with a number. You can still use strings though.

var Game={
    "status": [
            "0": "val",
            "1": "val",
            "2": "val"
            "0": "val",
            "1": "val",
            "2": "val"

If you access the properties with dot-notation, then you have to use identifiers. Use square bracket notation instead: Game.status[0][0].

But given that data, an array would seem to make more sense.

var Game={
    "status": [

How to convert datetime to integer in python

I think I have a shortcut for that:

# Importing datetime.
from datetime import datetime

# Creating a datetime object so we can test.
a =

# Converting a to string in the desired format (YYYYMMDD) using strftime
# and then to int.
a = int(a.strftime('%Y%m%d'))

error LNK2005: xxx already defined in MSVCRT.lib(MSVCR100.dll) C:\something\LIBCMT.lib(setlocal.obj)

Getting this error, I changed the

c/C++ > Code Generation > Runtime Library to Multi-threaded library (DLL) /MD

for both code project and associated Google Test project. This solved the issue.

Note: all components of the project must have the same definition in c/C++ > Code Generation > Runtime Library. Either DLL or not DLL, but identical.

android.os.FileUriExposedException: file:///storage/emulated/0/test.txt exposed beyond app through Intent.getData()

I spent almost a day trying to figure out why I was getting this exception. After lots of struggle, this config worked perfectly (Kotlin):


    android:resource="@xml/file_paths" />


<?xml version="1.0" encoding="utf-8"?>
  <files-path name="movies_csv_files" path="."/>

Intent itself

fun goToFileIntent(context: Context, file: File): Intent {
    val intent = Intent(Intent.ACTION_VIEW)
    val contentUri = FileProvider.getUriForFile(context, "${context.packageName}.fileprovider", file)
    val mimeType = context.contentResolver.getType(contentUri)
    intent.setDataAndType(contentUri, mimeType)

    return intent

I explain the whole process here.

Nexus 7 not visible over USB via "adb devices" from Windows 7 x64

In my case I had two problems:

  1. My PC got a previous "Samsung Galaxy II" driver and assigned it to my Nexus 7. I needed uninstall it many times. Finally I could bind the correct Nexus 7 driver.

  2. The need to set the PTP option.

How to disable Google asking permission to regularly check installed apps on my phone?

On Android 5.0+

Settings > More > Developer Options > Uncheck "Verify apps via USB"!

enter image description here

when I try to open an HTML file through `http://localhost/xampp/htdocs/index.html` it says unable to connect to localhost

You need to start your Apache Server normally you should have an xampp icon in the info-section from the taskbar, with this tool you can start the apache server as wel as the mysql database (if you need it)

What is the attribute property="og:title" inside meta tag?

The property in meta tags allows you to specify values to property fields which come from a property library. The property library (RDFa format) is specified in the head tag.

For example, to use that code you would have to have something like this in your <head tag. <head xmlns:og=""> and inside the there would be a specification for title (og:title).

The tag from your example was almost definitely from the Open Graph Protocol, the purpose is to specify structured information about your website for the use of Facebook (and possibly other search engines).

How to empty the content of a div

This method works best to me:

Element.prototype.remove = function() {
NodeList.prototype.remove = HTMLCollection.prototype.remove = function() {
    for(var i = this.length - 1; i >= 0; i--) {
        if(this[i] && this[i].parentElement) {

To use it we can deploy like this:




Python find elements in one list that are not in the other

I used two methods and I found one method useful over other. Here is my answer:

My input data:

crkmod_mpp = ['M13','M18','M19','M24']
testmod_mpp = ['M13','M14','M15','M16','M17','M18','M19','M20','M21','M22','M23','M24']

Method1: np.setdiff1d I like this approach over other because it preserves the position

test= list(np.setdiff1d(testmod_mpp,crkmod_mpp))
['M15', 'M16', 'M22', 'M23', 'M20', 'M14', 'M17', 'M21']

Method2: Though it gives same answer as in Method1 but disturbs the order

test = list(set(testmod_mpp).difference(set(crkmod_mpp)))
['POA23', 'POA15', 'POA17', 'POA16', 'POA22', 'POA18', 'POA24', 'POA21']

Method1 np.setdiff1d meets my requirements perfectly. This answer for information.

How to convert numpy arrays to standard TensorFlow format?

You can use placeholders and feed_dict.

Suppose we have numpy arrays like these:

trX = np.linspace(-1, 1, 101) 
trY = 2 * trX + np.random.randn(*trX.shape) * 0.33 

You can declare two placeholders:

X = tf.placeholder("float") 
Y = tf.placeholder("float")

Then, use these placeholders (X, and Y) in your model, cost, etc.: model = tf.mul(X, w) ... Y ... ...

Finally, when you run the model/cost, feed the numpy arrays using feed_dict:

with tf.Session() as sess:
...., feed_dict={X: trY, Y: trY})

NewtonSoft.Json Serialize and Deserialize class with property of type IEnumerable<ISomeInterface>

It is quite simple and out of the box support provided by, you just have to use the following JsonSettings while serializing and Deserializing:

JsonConvert.SerializeObject(graph,Formatting.None, new JsonSerializerSettings()
    TypeNameHandling =TypeNameHandling.Objects,
    TypeNameAssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple

and for Deserialzing use the below code:

    new JsonSerializerSettings(){TypeNameHandling = TypeNameHandling.Objects}

Just take a note of the JsonSerializerSettings object initializer, that is important for you.

Correct way to find max in an Array in Swift

With Swift 1.2 (and maybe earlier) you now need to use:

let nums = [1, 6, 3, 9, 4, 6];
let numMax = nums.reduce(Int.min, combine: { max($0, $1) })

For working with Double values I used something like this:

let nums = [1.3, 6.2, 3.6, 9.7, 4.9, 6.3];
let numMax = nums.reduce(-Double.infinity, combine: { max($0, $1) })

How to insert blank lines in PDF?

You can try a blank phrase:

document.add(new Phrase("\n"));

Change a column type from Date to DateTime during ROR migration

AFAIK, migrations are there to try to reshape data you care about (i.e. production) when making schema changes. So unless that's wrong, and since he did say he does not care about the data, why not just modify the column type in the original migration from date to datetime and re-run the migration? (Hope you've got tests:)).

Origin null is not allowed by Access-Control-Allow-Origin

I would like to humbly add that according to this SO source:, this kind of trouble is now partially solved simply by using the following jQuery instruction:

    $.support.cors = true;

I tried it on IE10.0.9200, and it worked immediately (using jquery-1.9.0.js).

On chrome 28.0.1500.95 - this instruction doesn't work (this happens all over as david complains in the comments at the link above)

Running chrome with --allow-file-access-from-files did not work for me (as Maistora's claims above)

set gvim font in .vimrc file

When I try:

set guifont=Consolas:h16

I get: Warning: Font "Consolas" reports bad fixed pitch metrics

and the following is work, and don't show the waring.

autocmd vimenter * GuiFont! Consolas:h16

by the way, if you want to use the mouse wheel to control the font-size, then you can add:

function! AdjustFontSize(amount)
    let s:font_size = s:font_size + a:amount
    :execute "GuiFont! Consolas:h" . s:font_size

noremap <C-ScrollWheelUp> :call AdjustFontSize(1)<CR>
noremap <C-ScrollWheelDown> :call AdjustFontSize(-1)<CR>

and if you want to pick the font, you can set

set guifont=*

will bring up a font requester, where you can pick the font you want.

enter image description here

Use RSA private key to generate public key?

In most software that generates RSA private keys, including openssl's, the private key is represented as a PKCS#1 RSAPrivatekey object or some variant thereof:

A.1.2 RSA private key syntax

An RSA private key should be represented with the ASN.1 type

  RSAPrivateKey ::= SEQUENCE {
      version           Version,
      modulus           INTEGER,  -- n
      publicExponent    INTEGER,  -- e
      privateExponent   INTEGER,  -- d
      prime1            INTEGER,  -- p
      prime2            INTEGER,  -- q
      exponent1         INTEGER,  -- d mod (p-1)
      exponent2         INTEGER,  -- d mod (q-1)
      coefficient       INTEGER,  -- (inverse of q) mod p
      otherPrimeInfos   OtherPrimeInfos OPTIONAL

As you can see, this format has a number of fields including the modulus and public exponent and thus is a strict superset of the information in an RSA public key.

Plot width settings in ipython notebook

If you use %pylab inline you can (on a new line) insert the following command:

%pylab inline
pylab.rcParams['figure.figsize'] = (10, 6)

This will set all figures in your document (unless otherwise specified) to be of the size (10, 6), where the first entry is the width and the second is the height.

See this SO post for more details.

Why do we check up to the square root of a prime number to determine if it is prime?

Let's say m = sqrt(n) then m × m = n. Now if n is not a prime then n can be written as n = a × b, so m × m = a × b. Notice that m is a real number whereas n, a and b are natural numbers.

Now there can be 3 cases:

  1. a > m ? b < m
  2. a = m ? b = m
  3. a < m ? b > m

In all 3 cases, min(a, b) = m. Hence if we search till m, we are bound to find at least one factor of n, which is enough to show that n is not prime.

Chrome Uncaught Syntax Error: Unexpected Token ILLEGAL

I had the same error when multiline string included new line (\n) characters. Merging all lines into one (thus removing all new line characters) and sending it to a browser used to solve. But was very inconvenient to code.

Often could not understand why this was an issue in Chrome until I came across to a statement which said that the current version of JavaScript engine in Chrome doesn't support multiline strings which are wrapped in single quotes and have new line (\n) characters in them. To make it work, multiline string need to be wrapped in double quotes. Changing my code to this, resolved this issue.

I will try to find a reference to a standard or Chrome doc which proves this. Until then, try this solution and see if works for you as well.

What is your most productive shortcut with Vim?

CTRL + A increments the number you are standing on.

How to log request and response body with Retrofit-Android?

I hope this code will help you to logging .
you just need to add interceptor in your Build.Gradle then make RetrofitClient .

First Step

Add this line to your build.gradle

 implementation 'com.squareup.okhttp3:logging-interceptor:3.4.1' 

Second Step

Make your Retrofit Client

   public class RetrofitClient {

    private Retrofit retrofit;
    private static OkHttpClient.Builder httpClient =
            new OkHttpClient.Builder();
    private static RetrofitClient instance = null;
    private static ApiServices service = null;
    private static HttpLoggingInterceptor logging =
            new HttpLoggingInterceptor();

    private RetrofitClient(final Context context) {
        httpClient.interceptors().add(new Interceptor() {
            public okhttp3.Response intercept(Interceptor.Chain chain) throws IOException {
                Request originalRequest = chain.request();
                Request.Builder builder = originalRequest.newBuilder().
                        method(originalRequest.method(), originalRequest.body());
                okhttp3.Response response = chain.proceed(;
                Do what you want
                return response;

        if (BuildConfig.DEBUG) {
            // add logging as last interceptor

        retrofit = new Retrofit.Builder().client(
        service = retrofit.create(ApiServices.class);

    public static RetrofitClient getInstance(Context context) {
        if (instance == null) {
            instance = new RetrofitClient(context);
        return instance;

    public ApiServices getApiService() {
        return service;



Filter items which array contains any of given values

There's also terms query which should save you some work. Here example from docs:

  "terms" : {
      "tags" : [ "blue", "pill" ],
      "minimum_should_match" : 1

Under hood it constructs boolean should. So it's basically the same thing as above but shorter.

There's also a corresponding terms filter.

So to summarize your query could look like this:

  "filtered": {
    "query": {
      "match": { "title": "hello world" }
    "filter": {
      "terms": {
        "tags": ["c", "d"]

With greater number of tags this could make quite a difference in length.

Checking if float is an integer

#define twop22 (0x1.0p+22)
#define ABS(x) (fabs(x))
#define isFloatInteger(x) ((ABS(x) >= twop22) || (((ABS(x) + twop22) - twop22) == ABS(x)))

Read XML file into XmlDocument

Use XmlDocument.Load() method to load XML from your file. Then use XmlDocument.InnerXml property to get XML string.

XmlDocument doc = new XmlDocument();
doc.Load("path to your file");
string xmlcontents = doc.InnerXml;

How to delete an instantiated object Python?

What do you mean by delete? In Python, removing a reference (or a name) can be done with the del keyword, but if there are other names to the same object that object will not be deleted.

--> test = 3
--> print(test)
--> del test
--> print(test)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'test' is not defined

compared to:

--> test = 5
--> other is test  # check that both name refer to the exact same object
--> del test       # gets rid of test, but the object is still referenced by other
--> print(other)

Get the index of the object inside an array, matching a condition

var CarId = 23;

//x.VehicleId property to match in the object array
var carIndex = (x) { return x.VehicleId; }).indexOf(CarId);

And for basic array numbers you can also do this:

var numberList = [100,200,300,400,500];
var index = numberList.indexOf(200); // 1

You will get -1 if it cannot find a value in the array.

Using pointer to char array, values in that array can be accessed?

Your should create ptr as follows:

char *ptr;

You have created ptr as an array of pointers to chars. The above creates a single pointer to a char.

Edit: complete code should be:

char *ptr;
char arr[5] = {'a','b','c','d','e'};
ptr = arr;
printf("\nvalue:%c", *(ptr+0));

What is <=> (the 'Spaceship' Operator) in PHP 7?

According to the RFC that introduced the operator, $a <=> $b evaluates to:

  • 0 if $a == $b
  • -1 if $a < $b
  • 1 if $a > $b

which seems to be the case in practice in every scenario I've tried, although strictly the official docs only offer the slightly weaker guarantee that $a <=> $b will return

an integer less than, equal to, or greater than zero when $a is respectively less than, equal to, or greater than $b

Regardless, why would you want such an operator? Again, the RFC addresses this - it's pretty much entirely to make it more convenient to write comparison functions for usort (and the similar uasort and uksort).

usort takes an array to sort as its first argument, and a user-defined comparison function as its second argument. It uses that comparison function to determine which of a pair of elements from the array is greater. The comparison function needs to return:

an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

The spaceship operator makes this succinct and convenient:

$things = [
        'foo' => 5.5,
        'bar' => 'abc'
        'foo' => 7.7,
        'bar' => 'xyz'
        'foo' => 2.2,
        'bar' => 'efg'

// Sort $things by 'foo' property, ascending
usort($things, function ($a, $b) {
    return $a['foo'] <=> $b['foo'];

// Sort $things by 'bar' property, descending
usort($things, function ($a, $b) {
    return $b['bar'] <=> $a['bar'];

More examples of comparison functions written using the spaceship operator can be found in the Usefulness section of the RFC.

How to putAll on Java hashMap contents of one to another, but not replace existing keys and values?

You can make it in just 1 line if you change maps order in @erickson's solution:

mapWithNotSoImportantValues.putAll( mapWithImportantValues );

In this case you replace values in mapWithNotSoImportantValues with value from mapWithImportantValues with the same keys.

vba: get unique values from array

The Collection and Dictionary solutions are all nice and shine for a short approach, but if you want speed try using a more direct approach:

Function ArrayUnique(ByVal aArrayIn As Variant) As Variant
' ArrayUnique
' This function removes duplicated values from a single dimension array
Dim aArrayOut() As Variant
Dim bFlag As Boolean
Dim vIn As Variant
Dim vOut As Variant
Dim i%, j%, k%

ReDim aArrayOut(LBound(aArrayIn) To UBound(aArrayIn))
i = LBound(aArrayIn)
j = i

For Each vIn In aArrayIn
    For k = j To i - 1
        If vIn = aArrayOut(k) Then bFlag = True: Exit For
    If Not bFlag Then aArrayOut(i) = vIn: i = i + 1
    bFlag = False

If i <> UBound(aArrayIn) Then ReDim Preserve aArrayOut(LBound(aArrayIn) To i - 1)
ArrayUnique = aArrayOut
End Function

Calling it:

Sub Test()
Dim aReturn As Variant
Dim aArray As Variant

aArray = Array(1, 2, 3, 1, 2, 3, "Test", "Test")
aReturn = ArrayUnique(aArray)
End Sub

For speed comparasion, this will be 100x to 130x faster then the dictionary solution, and about 8000x to 13000x faster than the collection one.

Running Node.js in apache?

Although there are a lot of good tips here I'd like to answer the question you asked:

So in other words can they work hand in hand just like Apache/Perl or Apache/PHP etc..

YES, you can run Node.js on Apache along side Perl and PHP IF you run it as a CGI module. As of yet, I am unable to find a mod-node for Apache but check out: CGI-Node for Apache here .

The interesting part about cgi-node is that it uses JavaScript exactly like you would use PHP to generate dynamic content, service up static pages, access SQL database etc. You can even share core JavaScript libraries between the server and the client/browser.

I think the shift to a single language between client and server is happening and JavaScript seems to be a good candidate.

A quick example from site:

<? include('myJavaScriptFile.js'); ?>
      <? var helloWorld = 'Hello World!'; ?>
      <b><?= helloWorld ?><br/>
      <? for( var index = 0; index < 10; index++) write(index + ' '); ?>

This outputs:

Hello World!
0 1 2 3 4 5 6 7 8 9

You also have full access to the HTTP request. That includes forms, uploaded files, headers etc.

I am currently running Node.js through the cgi-node module on Godaddy. site has all the documentation to get started.

I know I'm raving about this but it is finally a relief to use something other than PHP. Also, to be able to code JavaScript on both client and server.

Hope this helps.

All libraries must use the exact same version specification

If you are facing problem after implementing all below mentioned new libraries. I was facing the above mentioned same problem on this '' compatible verions.

implementation ''
implementation ''
implementation ''
implementation ''
implementation ''
implementation ''
implementation ''
implementation ''

I just replace this


to this



From git reset

"pull" or "merge" always leaves the original tip of the current branch in ORIG_HEAD.

git reset --hard ORIG_HEAD

Resetting hard to it brings your index file and the working tree back to that state, and resets the tip of the branch to that commit.

git reset --merge ORIG_HEAD

After inspecting the result of the merge, you may find that the change in the other branch is unsatisfactory. Running "git reset --hard ORIG_HEAD" will let you go back to where you were, but it will discard your local changes, which you do not want. "git reset --merge" keeps your local changes.

Before any patches are applied, ORIG_HEAD is set to the tip of the current branch.
This is useful if you have problems with multiple commits, like running 'git am' on the wrong branch or an error in the commits that is more easily fixed by changing the mailbox (e.g. +errors in the "From:" lines).

In addition, merge always sets '.git/ORIG_HEAD' to the original state of HEAD so a problematic merge can be removed by using 'git reset ORIG_HEAD'.

Note: from here

HEAD is a moving pointer. Sometimes it means the current branch, sometimes it doesn't.

So HEAD is NOT a synonym for "current branch" everywhere already.

HEAD means "current" everywhere in git, but it does not necessarily mean "current branch" (i.e. detached HEAD).

But it almost always means the "current commit".
It is the commit "git commit" builds on top of, and "git diff --cached" and "git status" compare against.
It means the current branch only in very limited contexts (exactly when we want a branch name to operate on --- resetting and growing the branch tip via commit/rebase/etc.).

Reflog is a vehicle to go back in time and time machines have interesting interaction with the notion of "current".

HEAD@{5.minutes.ago} could mean "dereference HEAD symref to find out what branch we are on RIGHT NOW, and then find out where the tip of that branch was 5 minutes ago".
Alternatively it could mean "what is the commit I would have referred to as HEAD 5 minutes ago, e.g. if I did "git show HEAD" back then".

git1.8.4 (July 2013) introduces introduced a new notation!
(Actually, it will be for 1.8.5, Q4 2013: reintroduced with commit 9ba89f4), by Felipe Contreras.

Instead of typing four capital letters "HEAD", you can say "@" now,
e.g. "git log @".

See commit cdfd948

Typing 'HEAD' is tedious, especially when we can use '@' instead.

The reason for choosing '@' is that it follows naturally from the ref@op syntax (e.g. HEAD@{u}), except we have no ref, and no operation, and when we don't have those, it makes sens to assume 'HEAD'.

So now we can use 'git show @~1', and all that goody goodness.

Until now '@' was a valid name, but it conflicts with this idea, so let's make it invalid. Probably very few people, if any, used this name.

Object of custom type as dictionary key

You override __hash__ if you want special hash-semantics, and __cmp__ or __eq__ in order to make your class usable as a key. Objects who compare equal need to have the same hash value.

Python expects __hash__ to return an integer, returning Banana() is not recommended :)

User defined classes have __hash__ by default that calls id(self), as you noted.

There is some extra tips from the documentation.:

Classes which inherit a __hash__() method from a parent class but change the meaning of __cmp__() or __eq__() such that the hash value returned is no longer appropriate (e.g. by switching to a value-based concept of equality instead of the default identity based equality) can explicitly flag themselves as being unhashable by setting __hash__ = None in the class definition. Doing so means that not only will instances of the class raise an appropriate TypeError when a program attempts to retrieve their hash value, but they will also be correctly identified as unhashable when checking isinstance(obj, collections.Hashable) (unlike classes which define their own __hash__() to explicitly raise TypeError).

How do I disable fail_on_empty_beans in Jackson?

Adding a solution here for a different problem, but one that manifests with the same error... Take care when constructing json on the fly (as api responses or whatever) to escape literal double quotes in your string members. You may be consuming your own malformed json.

What does the KEY keyword mean?

KEY is normally a synonym for INDEX. The key attribute PRIMARY KEY can also be specified as just KEY when given in a column definition. This was implemented for compatibility with other database systems.

      data_type [NOT NULL | NULL] [DEFAULT default_value]


Make: how to continue after a command fails?

Return successfully by blocking rm's returncode behind a pipe with the true command, which always returns 0 (success)

rm file | true

Nesting optgroups in a dropdownlist/select

I really like the Broken Arrow's solution above in this post. I have just improved/changed it a bit so that what was called labels can be toggled and are not considered options. I have used a small piece of jQuery, but this could be done without jQuery.

I have replaced intermediate labels (no leaf labels) with links, which call a function on click. This function is in charge of toggling the next div of the clicked link, so that it expands/collapses the options. This avoids the possibility of selecting an intermediate element in the hierarchy, which usually is something desired. Making a variant that allows to select intermediate elements should be easy.

This is the modified html:

<div class="NestedSelect">
    <a onclick="toggleDiv(this)">Fruit</a>
            <input type="radio" name="MySelectInputName"><span>Apple</span></label>
            <input type="radio" name="MySelectInputName"><span>Banana</span></label>
            <input type="radio" name="MySelectInputName"><span>Orange</span></label>

    <a onclick="toggleDiv(this)">Drink</a>
            <input type="radio" name="MySelectInputName"><span>Water</span></label>

        <a onclick="toggleDiv(this)">Soft</a>
                <input type="radio" name="MySelectInputName"><span>Cola</span></label>
                <input type="radio" name="MySelectInputName"><span>Soda</span></label>
                <input type="radio" name="MySelectInputName"><span>Lemonade</span></label>

        <a onclick="toggleDiv(this)">Hard</a>
                <input type="radio" name="MySelectInputName"><span>Bear</span></label>
                <input type="radio" name="MySelectInputName"><span>Whisky</span></label>
                <input type="radio" name="MySelectInputName"><span>Vodka</span></label>
                <input type="radio" name="MySelectInputName"><span>Gin</span></label>

A small javascript/jQuery function:

function toggleDiv(element) {

And the css:

.NestedSelect {
    display: inline-block;
    height: 100%;
    border: 1px Black solid;
    overflow-y: scroll;

.NestedSelect a:hover, .NestedSelect span:hover  {
    background-color: #0092ff;
    color: White;
    cursor: pointer;

.NestedSelect input[type="radio"] {
    display: none;

.NestedSelect input[type="radio"] + span {
    display: block;
    padding-left: 0px;
    padding-right: 5px;

.NestedSelect input[type="radio"]:checked + span {
    background-color: Black;
    color: White;

.NestedSelect div {
    display: none;
    margin-left: 15px;
    border-left: 1px black

.NestedSelect label > span:before, .NestedSelect a:before{
    content: '- ';

.NestedSelect a {
    display: block;

Running sample in JSFiddle

How to horizontally center an element

This method also works just fine:

div.container {
   display: flex;
   justify-content: center; /* For horizontal alignment */
   align-items: center;     /* For vertical alignment   */

For the inner <div>, the only condition is that its height and width must not be larger than the ones of its container.

How do I create executable Java program?

I'm not quite sure what you mean.

But I assume you mean either 1 of 2 things.

  • You want to create an executable .jar file

Eclipse can do this really easily File --> Export and create a jar and select the appropriate Main-Class and it'll generate the .jar for you. In windows you may have to associate .jar with the java runtime. aka Hold shift down, Right Click "open with" browse to your jvm and associate it with javaw.exe

  • create an actual .exe file then you need to use an extra library like or will create a native .exe stub with a nice icon that will essentially bootstrap your app. They even figure out if your customer hasn't got a JVM installed and prompt you to get one.

Python TypeError: cannot convert the series to <class 'int'> when trying to do math on dataframe

Seems your initial data contains strings and not numbers. It would probably be best to ensure that the data is already of the required type up front.

However, you can convert strings to numbers like this:

pd.Series(['123', '42']).astype(float)

instead of float(series)

Specified cast is not valid.. how to resolve this

Use Convert.ToDouble(value) rather than (double)value. It takes an object and supports all of the types you asked for! :)

Also, your method is always returning a string in the code above; I'd recommend having the method indicate so, and give it a more obvious name (public string FormatLargeNumber(object value))

The page cannot be displayed because an internal server error has occurred on server

I think the best first approach is to make sure to turn on detailed error messages via your web.config file, like this:

        <httpErrors errorMode="Detailed"></httpErrors>

After doing this, you should get a more detailed error message from the server.

In my particular case, the more detailed error pointed out that my <defaultDocument> section of the web.config file was not allowed at the folder level where I'd placed my web.config. It said

This configuration section cannot be used at this path. This happens when the section is locked at a parent level. Locking is either by default (overrideModeDefault="Deny"), or set explicitly by a location tag with overrideMode="Deny" or the legacy allowOverride="false". "

No Such Element Exception?

Another situation which issues the same problem, map.entrySet().iterator().next()

If there is no element in the Map object, then the above code will return NoSuchElementException. Make sure to call hasNext() first.

How to make asynchronous HTTP requests in PHP

let me show you my way :)

needs nodejs installed on the server

(my server sends 1000 https get request takes only 2 seconds)

url.php :

$urls = array_fill(0, 100, '');

function execinbackground($cmd) { 
    if (substr(php_uname(), 0, 7) == "Windows"){ 
        pclose(popen("start /B ". $cmd, "r"));  
    else { 
        exec($cmd . " > /dev/null &");   
execinbackground("nodejs urlscript.js urls.txt");
// { do your work while get requests being executed.. }

urlscript.js >

var https = require('https');
var url = require('url');
var http = require('http');
var fs = require('fs');
var dosya = process.argv[2];
var logdosya = 'log.txt';
var count=0;
http.globalAgent.maxSockets = 300;
https.globalAgent.maxSockets = 300;

setTimeout(timeout,100000); // maximum execution time (in ms)

function trim(string) {
    return string.replace(/^\s*|\s*$/g, '')

fs.readFile(process.argv[2], 'utf8', function (err, data) {
    if (err) {
        throw err;

function parcala(data) {
    var data = data.split("\n");
    data.forEach(function (d) {
    fs.unlink(dosya, function d() {
        console.log('<%s> file deleted', dosya);

function req(link) {
    var linkinfo = url.parse(link);
    if (linkinfo.protocol == 'https:') {
        var options = {
        port: 443,
        path: linkinfo.path,
        method: 'GET'
https.get(options, function(res) {res.on('data', function(d) {});}).on('error', function(e) {console.error(e);});
    } else {
    var options = {
        port: 80,
        path: linkinfo.path,
        method: 'GET'
http.get(options, function(res) {res.on('data', function(d) {});}).on('error', function(e) {console.error(e);});

process.on('exit', onExit);

function onExit() {

function timeout()
console.log("i am too far gone");process.exit();

function log() 
    var fd = fs.openSync(logdosya, 'a+');
    fs.writeSync(fd, dosya + '-'+count+'\n');

How to convert a string to an integer in JavaScript?

In my opinion, no answer covers all edge cases as parsing a float should result in an error.

function parseInteger(value) {
    if(value === '') return NaN;
    const number = Number(value);
    return Number.isInteger(number) ? number : NaN;
parseInteger("4")            // 4
parseInteger("5aaa")         // NaN
parseInteger("4.33333")      // NaN
parseInteger("aaa");         // NaN

jquery change div text

Put the title in its own span.

<span id="dialog_title_span">'+dialog_title+'</span>
$('#dialog_title_span').text("new dialog title");

LDAP root query syntax to search more than one specific OU

The answer is NO you can't. Why?

Because the LDAP standard describes a LDAP-SEARCH as kind of function with 4 parameters:

  1. The node where the search should begin, which is a Distinguish Name (DN)
  2. The attributes you want to be brought back
  3. The depth of the search (base, one-level, subtree)
  4. The filter

You are interested in the filter. You've got a summary here (it's provided by Microsoft for Active Directory, it's from a standard). The filter is composed, in a boolean way, by expression of the type Attribute Operator Value.

So the filter you give does not mean anything.

On the theoretical point of view there is ExtensibleMatch that allows buildind filters on the DN path, but it's not supported by Active Directory.

As far as I know, you have to use an attribute in AD to make the distinction for users in the two OUs.

It can be any existing discriminator attribute, or, for example the attribute called OU which is inherited from organizationalPerson class. you can set it (it's not automatic, and will not be maintained if you move the users) with "staff" for some users and "vendors" for others and them use the filter:


"And" and "Or" troubles within an IF statement

The problem is probably somewhere else. Try this code for example:

Sub test()

  origNum = "006260006"
  creditOrDebit = "D"

  If (origNum = "006260006" Or origNum = "30062600006") And creditOrDebit = "D" Then
    MsgBox "OK"
  End If

End Sub

And you will see that your Or works as expected. Are you sure that your ElseIf statement is executed (it will not be executed if any of the if/elseif before is true)?

Stored Procedure parameter default value - is this a constant or a variable

It has to be a constant - the value has to be computable at the time that the procedure is created, and that one computation has to provide the value that will always be used.

Look at the definition of sys.all_parameters:

default_value sql_variant If has_default_value is 1, the value of this column is the value of the default for the parameter; otherwise, NULL.

That is, whatever the default for a parameter is, it has to fit in that column.

As Alex K pointed out in the comments, you can just do:

CREATE PROCEDURE [dbo].[problemParam] 
    @StartDate INT = NULL,
    @EndDate INT = NULL
   SET @StartDate = COALESCE(@StartDate,CONVERT(INT,(CONVERT(CHAR(8),GETDATE()-130,112))))

provided that NULL isn't intended to be a valid value for @StartDate.

As to the blog post you linked to in the comments - that's talking about a very specific context - that, the result of evaluating GETDATE() within the context of a single query is often considered to be constant. I don't know of many people (unlike the blog author) who would consider a separate expression inside a UDF to be part of the same query as the query that calls the UDF.

How to set a bitmap from resource

Using this function you can get Image Bitmap. Just pass image url

 public Bitmap getBitmapFromURL(String strURL) {
      try {
        URL url = new URL(strURL);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        InputStream input = connection.getInputStream();
        Bitmap myBitmap = BitmapFactory.decodeStream(input);
        return myBitmap;
      } catch (IOException e) {
        return null;

How to print a single backslash?

A hacky way of printing a backslash that doesn't involve escaping is to pass its character code to chr:

>>> print(chr(92))

PHP Parse HTML code

Use PHP Document Object Model:

   $str = '<h1>T1</h1>Lorem ipsum.<h1>T2</h1>The quick red fox...<h1>T3</h1>... jumps over the lazy brown FROG';
   $DOM = new DOMDocument;

   //get all H1
   $items = $DOM->getElementsByTagName('h1');

   //display all H1 text
   for ($i = 0; $i < $items->length; $i++)
        echo $items->item($i)->nodeValue . "<br/>";

This outputs as:


[EDIT]: After OP Clarification:

If you want the content like Lorem ipsum. etc, you can directly use this regex:

   $str = '<h1>T1</h1>Lorem ipsum.<h1>T2</h1>The quick red fox...<h1>T3</h1>... jumps over the lazy brown FROG';
   echo preg_replace("#<h1.*?>.*?</h1>#", "", $str);

this outputs:

Lorem ipsum.The quick red fox...... jumps over the lazy brown FROG

error LNK2019: unresolved external symbol _WinMain@16 referenced in function ___tmainCRTStartup

If you are having this problem and are using Qt - you need to link qtmain.lib or qtmaind.lib

How to prevent a dialog from closing when a button is clicked

It could be built with easiest way:

Alert Dialog with Custom View and with two Buttons (Positive & Negative).

AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()).setTitle(getString(R.string.select_period));
builder.setPositiveButton(getString(R.string.ok), null);

 builder.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int which) {

    // Click of Cancel Button


  LayoutInflater li = LayoutInflater.from(getActivity());
  View promptsView = li.inflate(R.layout.dialog_date_picker, null, false);

  DatePicker startDatePicker = (DatePicker)promptsView.findViewById(;
  DatePicker endDatePicker = (DatePicker)promptsView.findViewById(;

  final AlertDialog alertDialog = builder.create();;

  Button theButton = alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
  theButton.setOnClickListener(new CustomListener(alertDialog, startDatePicker, endDatePicker));

CustomClickLister of Positive Button of Alert Dailog:

private class CustomListener implements View.OnClickListener {
        private final Dialog dialog;
        private DatePicker mStartDp, mEndDp;
    public CustomListener(Dialog dialog, DatePicker dS, DatePicker dE) {
        this.dialog = dialog;
        mStartDp = dS;
        mEndDp = dE;

    public void onClick(View v) {

        int day1  = mStartDp.getDayOfMonth();
        int month1= mStartDp.getMonth();
        int year1 = mStartDp.getYear();
        Calendar cal1 = Calendar.getInstance();
        cal1.set(Calendar.YEAR, year1);
        cal1.set(Calendar.MONTH, month1);
        cal1.set(Calendar.DAY_OF_MONTH, day1);

        int day2  = mEndDp.getDayOfMonth();
        int month2= mEndDp.getMonth();
        int year2 = mEndDp.getYear();
        Calendar cal2 = Calendar.getInstance();
        cal2.set(Calendar.YEAR, year2);
        cal2.set(Calendar.MONTH, month2);
        cal2.set(Calendar.DAY_OF_MONTH, day2);

            Log.i("Dialog", "Dismiss");
            // Condition is satisfied so do dialog dismiss
            }else {
            Log.i("Dialog", "Do not Dismiss");
            // Condition is not satisfied so do not dialog dismiss