Programs & Examples On #Quicksand

jQuery Quicksand is a jQuery plugin to reorder and filter items with a nice shuffling animation.

How to get the data-id attribute?

Important note. Keep in mind, that if you adjust the data- attribute dynamically via JavaScript it will NOT be reflected in the data() jQuery function. You have to adjust it via data() function as well.

<a data-id="123">link</a>


$(this).data("id") // returns 123
$(this).attr("data-id", "321"); //change the attribute
$(this).data("id") // STILL returns 123!!!
$(this).data("id", "321")
$(this).data("id") // NOW we have 321

How to sort List of objects by some property

In java you need to use the static Collections.sort method. Here is an example for a list of CompanyRole objects, sorted first by begin and then by end. You can easily adapt for your own object.

private static void order(List<TextComponent> roles) {

    Collections.sort(roles, new Comparator() {
        public int compare(Object o1, Object o2) {
            int x1 = ((CompanyRole) o1).getBegin();
            int x2 = ((CompanyRole) o2).getBegin();

            if (x1 != x2) {
                return x1 - x2;
            } else {
                int y1 = ((CompanyRole) o1).getEnd();
                int y2 = ((CompanyRole) o2).getEnd();
                return y2 - y1;

HashMap and int as key

You may try to use Trove
TIntObjectHashMap is probably what you are looking for.

Setting Spring Profile variable

In the <tomcat-home>\conf\ file, add this new line:

How do I get the n-th level parent of an element in jQuery?

You could give the target parent an id or class (e.g. myParent) and reference is with $('#element').parents(".myParent")

How to sort a list of lists by a specific index of the inner list?

This is a job for itemgetter

>>> from operator import itemgetter
>>> L=[[0, 1, 'f'], [4, 2, 't'], [9, 4, 'afsd']]
>>> sorted(L, key=itemgetter(2))
[[9, 4, 'afsd'], [0, 1, 'f'], [4, 2, 't']]

It is also possible to use a lambda function here, however the lambda function is slower in this simple case

How do you get the contextPath from JavaScript, the right way?

I render context path to attribute of link tag with id="contextPahtHolder" and then obtain it in JS code. For example:

        <link id="contextPathHolder" data-contextPath="${pageContext.request.contextPath}"/>
        <script src="main.js" type="text/javascript"></script>


var CONTEXT_PATH = $('#contextPathHolder').attr('data-contextPath');
$.get(CONTEXT_PATH + '/action_url', function() {});

If context path is empty (like in embedded servlet container istance), it will be empty string. Otherwise it contains contextPath string

What does "control reaches end of non-void function" mean?

The compiler cannot tell from that code if the function will ever reach the end and still return something. To make that clear, replace the last else if(...) with just else.

Error: Can't set headers after they are sent to the client

This type of error you will get when you pass statements after sending a response.

For example:

res.send("something response");
res.send("sopmething response");

Will result in the error you are seeing, because once the response has been sent, the following res.send will not be executed.

If you want do anything, you should do it before sending the response.

How to create a multi line body in C# System.Net.Mail.MailMessage

You need to enable IsBodyHTML

message.IsBodyHtml = true; //This will enable using HTML elements in email body
message.Body ="First Line <br /> second line";

Change a Git remote HEAD to point to something besides master

If you have access to the remote repo from a shell, just go into the .git (or the main dir if its a bare repo) and change the HEAD file to point to the correct head. For example, by default it always contains 'refs: refs/heads/master', but if you need foo to be the HEAD instead, just edit the HEAD file and change the contents to 'refs: refs/heads/foo'.

How can I check if a View exists in a Database?

IN SQL Server ,

declare @ViewName nvarchar(20)='ViewNameExample'

if exists(SELECT 1 from sys.objects where object_Id=object_Id(@ViewName) and Type_Desc='VIEW')
    -- Your SQL Code goes here ...


How to roundup a number to the closest ten?

You could also use CEILING which rounds up to an integer or desired multiple of significance

rounds up to a multiple of 10

12340.0001 will become 12350

Can't find bundle for base name /Bundle, locale en_US

I had the same problem using Netbeans. I went to the project folder and copied the properties file. I think clicked "build" and then "classes." I added the properties file in that folder. That solved my problem.

How to use OAuth2RestTemplate?

In the answer from @mariubog ( I was using password grant types too as in the example but needed to set the client authentication scheme to form. Scopes were not supported by the endpoint for password and there was no need to set the grant type as the ResourceOwnerPasswordResourceDetails object sets this itself in the constructor.


public ResourceOwnerPasswordResourceDetails() {


The key thing for me was the client_id and client_secret were not being added to the form object to post in the body if resource.setClientAuthenticationScheme(AuthenticationScheme.form); was not set.

See the switch in:

Finally, when connecting to Salesforce endpoint the password token needed to be appended to the password.

class MyConfig {

private String tokenUrl;

private String clientId;

private String clientSecret;

private String passwordToken;

private String username;

private String password;

protected OAuth2ProtectedResourceDetails resource() {

    ResourceOwnerPasswordResourceDetails resource = new ResourceOwnerPasswordResourceDetails();

    resource.setPassword(password + passwordToken);

    return resource;

 public OAuth2RestOperations restTemplate() {
    return new OAuth2RestTemplate(resource(), new DefaultOAuth2ClientContext(new DefaultAccessTokenRequest()));

class MyService {
    private OAuth2RestOperations restTemplate;

    public MyService() {

Convert ASCII TO UTF-8 Encoding

ASCII is a subset of UTF-8, so if a document is ASCII then it is already UTF-8.

IntelliJ IDEA 13 uses Java 1.5 despite setting to 1.7

File->Project structure->Project Settings->Project->Project Language level

File->Project structure->Project Settings->Modules->Language level

Change level using drop down

Coding Conventions - Naming Enums

If I can add my $0.02, I prefer using PascalCase as enum values in C.

In C, they are basically global, and PEER_CONNECTED gets really tiring as opposed to PeerConnected.

Breath of fresh air.

Literally, it makes me breathe easier.

In Java, it is possible to use raw enum names as long as you static import them from another class.

import static pkg.EnumClass.*;

Now, you can use the unqualified names, that you qualified in a different way already.

I am currently (thinking) about porting some C code to Java and currently 'torn' between choosing Java convention (which is more verbose, more lengthy, and more ugly) and my C style.

PeerConnected would become PeerState.CONNECTED except in switch statements, where it is CONNECTED.

Now there is much to say for the latter convention and it does look nice but certain "idiomatic phrases" such as if (s == PeerAvailable) become like if (s == PeerState.AVAILABLE) and nostalgically, this is a loss of meaning to me.

I think I still prefer the Java style because of clarity but I have a hard time looking at the screaming code.

Now I realize PascalCase is already widely used in Java but very confusing it would not really be, just a tad out of place.

Java Could not reserve enough space for object heap error

4gb RAM doesn't mean you can use it all for java process. Lots of RAM is needed for system processes. Dont go above 2GB or it will be trouble some.

Before starting jvm just check how much RAM is available and then set memory accordingly.

How to set iframe size dynamically

The height is different depending on the browser's window size. It should be set dynamically depending on the size of the browser window

<!DOCTYPE html>
    <iframe src="url" height="600" width="1350" title="Enter Here"></iframe>

Can I set enum start value in Java?

I think you're confused from looking at C++ enumerators. Java enumerators are different.

This would be the code if you are used to C/C++ enums:

public class TestEnum {
enum ids {

    public final int value = 100 + ordinal();

public static void main(String arg[]) {
    System.out.println("OPEN:  " + ids.OPEN.value);
    System.out.println("CLOSE: " + ids.CLOSE.value);
    System.out.println("OTHER: " + ids.OTHER.value);

For..In loops in JavaScript - key value pairs

Please try the below code:

 const games = {
  "Fifa": "232",
  "Minecraft": "476",
  "Call of Duty": "182"

Object.keys(games).forEach((item, index, array) => {
  var msg = item+' '+games[item];

MySQL load NULL values from CSV data

MySQL manual says:

When reading data with LOAD DATA INFILE, empty or missing columns are updated with ''. If you want a NULL value in a column, you should use \N in the data file. The literal word “NULL” may also be used under some circumstances.

So you need to replace the blanks with \N like this:


Returning IEnumerable<T> vs. IQueryable<T>

The top answer is good but it doesn't mention expression trees which explain "how" the two interfaces differ. Basically, there are two identical sets of LINQ extensions. Where(), Sum(), Count(), FirstOrDefault(), etc all have two versions: one that accepts functions and one that accepts expressions.

  • The IEnumerable version signature is: Where(Func<Customer, bool> predicate)

  • The IQueryable version signature is: Where(Expression<Func<Customer, bool>> predicate)

You've probably been using both of those without realizing it because both are called using identical syntax:

e.g. Where(x => x.City == "<City>") works on both IEnumerable and IQueryable

  • When using Where() on an IEnumerable collection, the compiler passes a compiled function to Where()

  • When using Where() on an IQueryable collection, the compiler passes an expression tree to Where(). An expression tree is like the reflection system but for code. The compiler converts your code into a data structure that describes what your code does in a format that's easily digestible.

Why bother with this expression tree thing? I just want Where() to filter my data. The main reason is that both the EF and Linq2SQL ORMs can convert expression trees directly into SQL where your code will execute much faster.

Oh, that sounds like a free performance boost, should I use AsQueryable() all over the place in that case? No, IQueryable is only useful if the underlying data provider can do something with it. Converting something like a regular List to IQueryable will not give you any benefit.

Object does not support item assignment error

The error seems clear: model objects do not support item assignment. MyModel.objects.latest('id')['foo'] = 'bar' will throw this same error.

It's a little confusing that your model instance is called projectForm...

To reproduce your first block of code in a loop, you need to use setattr

for k,v in session_results.iteritems():
    setattr(projectForm, k, v)

Cross-thread operation not valid: Control 'textBox1' accessed from a thread other than the thread it was created on

I don't know if this is good enough but I made a static ThreadHelperClass class and implemented it as following .Now I can easily set text property of various controls without much coding .

public static class ThreadHelperClass
    delegate void SetTextCallback(Form f, Control ctrl, string text);
    /// <summary>
    /// Set text property of various controls
    /// </summary>
    /// <param name="form">The calling form</param>
    /// <param name="ctrl"></param>
    /// <param name="text"></param>
    public static void SetText(Form form, Control ctrl, string text)
        // InvokeRequired required compares the thread ID of the 
        // calling thread to the thread ID of the creating thread. 
        // If these threads are different, it returns true. 
        if (ctrl.InvokeRequired)
            SetTextCallback d = new SetTextCallback(SetText);
            form.Invoke(d, new object[] { form, ctrl, text });
            ctrl.Text = text;

Using the code:

 private void btnTestThread_Click(object sender, EventArgs e)
    Thread demoThread =
       new Thread(new ThreadStart(this.ThreadProcSafe));

 // This method is executed on the worker thread and makes 
 // a thread-safe call on the TextBox control. 
 private void ThreadProcSafe()
     ThreadHelperClass.SetText(this, textBox1, "This text was set safely.");
     ThreadHelperClass.SetText(this, textBox2, "another text was set safely.");

How to simulate a real mouse click using java?

You could create a simple AutoIt Script that does the job for you, compile it as an executable and perform a system call there.

in au3 Script:

; how to use: MouseClick ( "button" [, x, y [, clicks = 1 [, speed = 10]]] )
MouseClick ( "left" , $CmdLine[1], $CmdLine[1] )

Now find aut2exe in your au3 Folder or find 'Compile Script to .exe' in your Start Menu and create an executable.

in your Java class call:

    new String[]{

AutoIt will behave as if it was a human and won't be detected as a machine.

Find AutoIt here:

jQuery - disable selected options

pls try this,

$('#select_id option[value="'+value+'"]').attr("disabled", true);

Jenkins CI Pipeline Scripts not permitted to use method groovy.lang.GroovyObject


I had similar issue and I resolved it doing the following

  1. Navigate to jenkins > Manage jenkins > In-process Script Approval
  2. There was a pending command, which I had to approve.

In process approval link in Jenkins 2.61 Alternative 1: Disable sandbox

As this article explains in depth, groovy scripts are run in sandbox mode by default. This means that a subset of groovy methods are allowed to run without administrator approval. It's also possible to run scripts not in sandbox mode, which implies that the whole script needs to be approved by an administrator at once. This preventing users from approving each line at the time.

Running scripts without sandbox can be done by unchecking this checkbox in your project config just below your script: enter image description here

Alternative 2: Disable script security

As this article explains it also possible to disable script security completely. First install the permissive script security plugin and after that change your jenkins.xml file add this argument:


So you jenkins.xml will look something like this:

<arguments>-Dpermissive-script-security.enabled=true -Xrs -Xmx4096m -Dhudson.lifecycle=hudson.lifecycle.WindowsServiceLifecycle -jar "%BASE%\jenkins.war" --httpPort=80 --webroot="%BASE%\war"</arguments>

Make sure you know what you are doing if you implement this!

What is the difference between the GNU Makefile variable assignments =, ?=, := and +=?

In the above answers, it is important to understand what is meant by "values are expanded at declaration/use time". Giving a value like *.c does not entail any expansion. It is only when this string is used by a command that it will maybe trigger some globbing. Similarly, a value like $(wildcard *.c) or $(shell ls *.c) does not entail any expansion and is completely evaluated at definition time even if we used := in the variable definition.

Try the following Makefile in directory where you have some C files:

VAR1 = *.c
VAR2 := *.c
VAR3 = $(wildcard *.c)
VAR4 := $(wildcard *.c)
VAR5 = $(shell ls *.c)
VAR6 := $(shell ls *.c)

all :
    touch foo.c
    @echo "now VAR1 = \"$(VAR1)\"" ; ls $(VAR1)
    @echo "now VAR2 = \"$(VAR2)\"" ; ls $(VAR2)
    @echo "now VAR3 = \"$(VAR3)\"" ; ls $(VAR3)
    @echo "now VAR4 = \"$(VAR4)\"" ; ls $(VAR4)
    @echo "now VAR5 = \"$(VAR5)\"" ; ls $(VAR5)
    @echo "now VAR6 = \"$(VAR6)\"" ; ls $(VAR6)
    rm -v foo.c

Running make will trigger a rule that creates an extra (empty) C file, called foo.c but none of the 6 variables has foo.c in its value.

How do I return the SQL data types from my query?

You could also insert the results (or top 10 results) into a temp table and get the columns from the temp table (as long as the column names are all different).

INTO #TempTable
FROM <DataSource>

Then use:

EXEC tempdb.dbo.sp_help N'#TempTable';


FROM tempdb.sys.columns 
WHERE [object_id] = OBJECT_ID(N'tempdb..#TempTable');

Extrapolated from Aaron's answer here.

Resize height with Highcharts

You must set the height of the container explicitly

#container {

See other Stackoverflow answer

Highcharts documentation

How to add "active" class to Html.ActionLink in ASP.NET MVC

I would like to propose this solution which is based on the first part of Dom's answer.

We first define two variables, "action" and "controller" and use them to determine the active link:

{ string controller = ViewContext.RouteData.Values["Controller"].ToString();
string action = ViewContext.RouteData.Values["Action"].ToString();}

And then:

<ul class="nav navbar-nav">
    <li class="@((controller == "Home" && action == "Index") ? "active" : "")">@Html.ActionLink("Home", "Index", "Home")</li>
    <li class="@((controller == "Home" && action == "About") ? "active" : "")">@Html.ActionLink("About", "About", "Home")</li>
    <li class="@((controller == "Home" && action == "Contact") ? "active" : "")">@Html.ActionLink("Contact", "Contact", "Home")</li>

Now it looks nicer and no need for more complex solutions.

How to center a Window in Java?

On Linux the code


Put my window to random location each time I launched it, in a multi display environment. And the code

setLocation((Toolkit.getDefaultToolkit().getScreenSize().width  - getSize().width) / 2, (Toolkit.getDefaultToolkit().getScreenSize().height - getSize().height) / 2);

"cut" the window in half with placing it to the exact center, which is between my two displays. I used the following method to center it:

private void setWindowPosition(JFrame window, int screen)
    GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
    GraphicsDevice[] allDevices = env.getScreenDevices();
    int topLeftX, topLeftY, screenX, screenY, windowPosX, windowPosY;

    if (screen < allDevices.length && screen > -1)
        topLeftX = allDevices[screen].getDefaultConfiguration().getBounds().x;
        topLeftY = allDevices[screen].getDefaultConfiguration().getBounds().y;

        screenX  = allDevices[screen].getDefaultConfiguration().getBounds().width;
        screenY  = allDevices[screen].getDefaultConfiguration().getBounds().height;
        topLeftX = allDevices[0].getDefaultConfiguration().getBounds().x;
        topLeftY = allDevices[0].getDefaultConfiguration().getBounds().y;

        screenX  = allDevices[0].getDefaultConfiguration().getBounds().width;
        screenY  = allDevices[0].getDefaultConfiguration().getBounds().height;

    windowPosX = ((screenX - window.getWidth())  / 2) + topLeftX;
    windowPosY = ((screenY - window.getHeight()) / 2) + topLeftY;

    window.setLocation(windowPosX, windowPosY);

Makes the window appear right at the center of the first display. This is probably not the easiest solution.

Works properly on Linux, Windows and Mac.

How to use JavaScript source maps (.map files)?

The .map files are for js and css (and now ts too) files that have been minified. They are called SourceMaps. When you minify a file, like the angular.js file, it takes thousands of lines of pretty code and turns it into only a few lines of ugly code. Hopefully, when you are shipping your code to production, you are using the minified code instead of the full, unminified version. When your app is in production, and has an error, the sourcemap will help take your ugly file, and will allow you to see the original version of the code. If you didn't have the sourcemap, then any error would seem cryptic at best.

Same for CSS files. Once you take a SASS or LESS file and compile it to CSS, it looks nothing like its original form. If you enable sourcemaps, then you can see the original state of the file, instead of the modified state.

So, to answer you questions in order:

  • What is it for? To de-reference uglified code
  • How can a developer use it? You use it for debugging a production app. In development mode you can use the full version of Angular. In production, you would use the minified version.
  • Should I care about creating a file? If you care about being able to debug production code easier, then yes, you should do it.
  • How does it get created? It is created at build time. There are build tools that can build your .map file for you as it does other files.

I hope this makes sense.

Is there a stopwatch in Java?

The code doesn't work because elapsed variable in getElapsedTimeSecs() is not a float or double.

IE and Edge fix for object-fit: cover;

Here is the only CSS solution to fix this. Use the below css.

.row-fluid {
  display: table;

.row-fluid .span6 {
  display: table-cell;
  vertical-align: top;

.vc_single_image-wrapper {
  position: relative;

.vc_single_image-wrapper .image-wrapper {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  background-size: cover;
  background-repeat: no-repeat;
  background-position: 50% 50%;

HTML from the OP:

<div class="vc_single_image-wrapper   vc_box_border_grey">
  <div class="image-wrapper" style="background-image: url(;"></div>

try this, it should work. also remove float from .row-fluid .span6

ImportError: numpy.core.multiarray failed to import

I had the same issue, and here's how it's solved in my case.

I tried pip install -U numpy but it didn't upgrade numpy, but conda install worked for me

ImportError: numpy.core.multiarray failed to import
admin@MacBook-Air$ pip install -U numpy
Requirement already up-to-date: numpy in /Users/admin/anaconda/lib/python2.7/site-packages
admin@MacBook-Air$ python
Python 2.7.12 |Anaconda 2.4.0 (x86_64)| (default, Jul  2 2016, 17:43:17) 
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.11.00)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
Anaconda is brought to you by Continuum Analytics.
Please check out: and
>>> import numpy
>>> numpy.version.version
>>> exit
Use exit() or Ctrl-D (i.e. EOF) to exit
admin@MacBook-Air$ conda install numpy
Fetching package metadata .......
Solving package specifications: ..........

Package plan for installation in environment /Users/admin/anaconda:

The following packages will be downloaded:

    package                    |            build
    scikit-learn-0.18.1        |      np111py27_0         4.9 MB

The following packages will be UPDATED:

    numexpr:      2.3.0-np17py27_0  --> 2.6.1-np111py27_1 
    numpy:        1.7.1-py27_2      --> 1.11.2-py27_0     
    scikit-learn: 0.14.1-np17py27_1 --> 0.18.1-np111py27_0
    scipy:        0.13.2-np17py27_1 --> 0.18.1-np111py27_0

Proceed ([y]/n)? y

Fetching packages ...
scikit-learn-0 100% |#################################################################| Time: 0:00:16 312.60 kB/s
Extracting packages ...
[      COMPLETE      ]|####################################################################################| 100%
Unlinking packages ...
[      COMPLETE      ]|####################################################################################| 100%
Linking packages ...
[      COMPLETE      ]|####################################################################################| 100%

How to split/partition a dataset into training and test datasets for, e.g., cross validation?

Split into train test and valid

x =np.expand_dims(np.arange(100), -1)


indices = np.random.permutation(x.shape[0])

training_idx, test_idx, val_idx = indices[:int(x.shape[0]*.9)], indices[int(x.shape[0]*.9):int(x.shape[0]*.95)],  indices[int(x.shape[0]*.9):int(x.shape[0]*.95)]

training, test, val = x[training_idx,:], x[test_idx,:], x[val_idx,:]

print(training, test, val)

How to change column datatype in SQL database without losing data

I can modify the table field's datatype, with these following query: and also in the Oracle DB,

ALTER TABLE table_name
MODIFY column_name datatype;

Combine several images horizontally with Python

I would try this:

import numpy as np
import PIL
from PIL import Image

list_im = ['Test1.jpg', 'Test2.jpg', 'Test3.jpg']
imgs    = [ for i in list_im ]
# pick the image which is the smallest, and resize the others to match it (can be arbitrary image shape here)
min_shape = sorted( [(np.sum(i.size), i.size ) for i in imgs])[0][1]
imgs_comb = np.hstack( (np.asarray( i.resize(min_shape) ) for i in imgs ) )

# save that beautiful picture
imgs_comb = PIL.Image.fromarray( imgs_comb) 'Trifecta.jpg' )    

# for a vertical stacking it is simple: use vstack
imgs_comb = np.vstack( (np.asarray( i.resize(min_shape) ) for i in imgs ) )
imgs_comb = PIL.Image.fromarray( imgs_comb) 'Trifecta_vertical.jpg' )

It should work as long as all images are of the same variety (all RGB, all RGBA, or all grayscale). It shouldn't be difficult to ensure this is the case with a few more lines of code. Here are my example images, and the result:








combined images


enter image description here

Get Cell Value from a DataTable in C#

You can iterate DataTable like this:

private void button1_Click(object sender, EventArgs e)
    for(int i = 0; i< dt.Rows.Count;i++)
        for (int j = 0; j <dt.Columns.Count ; j++)
            object o = dt.Rows[i].ItemArray[j];
            //if you want to get the string
            //string s = o = dt.Rows[i].ItemArray[j].ToString();

Depending on the type of the data in the DataTable cell, you can cast the object to whatever you want.

How to parse a JSON string to an array using Jackson

The complete example with an array. Replace "constructArrayType()" by "constructCollectionType()" or any other type you need.


import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;

public class Sorting {

    private String property;

    private String direction;

    public Sorting() {


    public Sorting(String property, String direction) { = property;
        this.direction = direction;

    public String getProperty() {
        return property;

    public void setProperty(String property) { = property;

    public String getDirection() {
        return direction;

    public void setDirection(String direction) {
        this.direction = direction;

    public static void main(String[] args) throws JsonParseException, IOException {
        final String json = "[{\"property\":\"title1\", \"direction\":\"ASC\"}, {\"property\":\"title2\", \"direction\":\"DESC\"}]";
        ObjectMapper mapper = new ObjectMapper();
        Sorting[] sortings = mapper.readValue(json, TypeFactory.defaultInstance().constructArrayType(Sorting.class));

How to insert text with single quotation sql server 2005

Escape single quote with an additional single as Kirtan pointed out
And if you are trying to execute a dynamic sql (which is not a good idea in the first place) via sp_executesql then the below code would work for you

sp_executesql N'INSERT INTO SomeTable (SomeColumn) VALUES (''John''''s'')'

How do you create a static class in C++?

Consider Matt Price's solution.

  1. In C++, a "static class" has no meaning. The nearest thing is a class with only static methods and members.
  2. Using static methods will only limit you.

What you want is, expressed in C++ semantics, to put your function (for it is a function) in a namespace.

Edit 2011-11-11

There is no "static class" in C++. The nearest concept would be a class with only static methods. For example:

// header
class MyClass
   public :
      static void myMethod() ;
} ;

// source
void MyClass::myMethod()
   // etc.

But you must remember that "static classes" are hacks in the Java-like kind of languages (e.g. C#) that are unable to have non-member functions, so they have instead to move them inside classes as static methods.

In C++, what you really want is a non-member function that you'll declare in a namespace:

// header
namespace MyNamespace
   void myMethod() ;

// source
namespace MyNamespace
   void myMethod()
      // etc.

Why is that?

In C++, the namespace is more powerful than classes for the "Java static method" pattern, because:

  • static methods have access to the classes private symbols
  • private static methods are still visible (if inaccessible) to everyone, which breaches somewhat the encapsulation
  • static methods cannot be forward-declared
  • static methods cannot be overloaded by the class user without modifying the library header
  • there is nothing that can be done by a static method that can't be done better than a (possibly friend) non-member function in the same namespace
  • namespaces have their own semantics (they can be combined, they can be anonymous, etc.)
  • etc.

Conclusion: Do not copy/paste that Java/C#'s pattern in C++. In Java/C#, the pattern is mandatory. But in C++, it is bad style.

Edit 2010-06-10

There was an argument in favor to the static method because sometimes, one needs to use a static private member variable.

I disagree somewhat, as show below:

The "Static private member" solution

// HPP

class Foo
   public :
      void barA() ;
   private :
      void barB() ;
      static std::string myGlobal ;
} ;

First, myGlobal is called myGlobal because it is still a global private variable. A look at the CPP source will clarify that:

// CPP
std::string Foo::myGlobal ; // You MUST declare it in a CPP

void Foo::barA()
   // I can access Foo::myGlobal

void Foo::barB()
   // I can access Foo::myGlobal, too

void barC()
   // I CAN'T access Foo::myGlobal !!!

At first sight, the fact the free function barC can't access Foo::myGlobal seems a good thing from an encapsulation viewpoint... It's cool because someone looking at the HPP won't be able (unless resorting to sabotage) to access Foo::myGlobal.

But if you look at it closely, you'll find that it is a colossal mistake: Not only your private variable must still be declared in the HPP (and so, visible to all the world, despite being private), but you must declare in the same HPP all (as in ALL) functions that will be authorized to access it !!!

So using a private static member is like walking outside in the nude with the list of your lovers tattooed on your skin : No one is authorized to touch, but everyone is able to peek at. And the bonus: Everyone can have the names of those authorized to play with your privies.

private indeed... :-D

The "Anonymous namespaces" solution

Anonymous namespaces will have the advantage of making things private really private.

First, the HPP header

// HPP

namespace Foo
   void barA() ;

Just to be sure you remarked: There is no useless declaration of barB nor myGlobal. Which means that no one reading the header knows what's hidden behind barA.

Then, the CPP:

// CPP
namespace Foo
      std::string myGlobal ;

      void Foo::barB()
         // I can access Foo::myGlobal

   void barA()
      // I can access myGlobal, too

void barC()
   // I STILL CAN'T access myGlobal !!!

As you can see, like the so-called "static class" declaration, fooA and fooB are still able to access myGlobal. But no one else can. And no one else outside this CPP knows fooB and myGlobal even exist!

Unlike the "static class" walking on the nude with her address book tattooed on her skin the "anonymous" namespace is fully clothed, which seems quite better encapsulated AFAIK.

Does it really matter?

Unless the users of your code are saboteurs (I'll let you, as an exercise, find how one can access to the private part of a public class using a dirty behaviour-undefined hack...), what's private is private, even if it is visible in the private section of a class declared in a header.

Still, if you need to add another "private function" with access to the private member, you still must declare it to all the world by modifying the header, which is a paradox as far as I am concerned: If I change the implementation of my code (the CPP part), then the interface (the HPP part) should NOT change. Quoting Leonidas : "This is ENCAPSULATION!"

Edit 2014-09-20

When are classes static methods are actually better than namespaces with non-member functions?

When you need to group together functions and feed that group to a template:

namespace alpha
   void foo() ;
   void bar() ;

struct Beta
   static void foo() ;
   static void bar() ;

template <typename T>
struct Gamma
   void foobar()
      T::foo() ;
      T::bar() ;

Gamma<alpha> ga ; // compilation error
Gamma<Beta> gb ;  // ok
gb.foobar() ;     // ok !!!

Because, if a class can be a template parameter, a namespaces cannot.

Pretty-Print JSON Data to a File using Python

import json
def writeToFile(logData, fileName, openOption="w"):
  file = open(fileName, openOption)
  file.write(json.dumps(json.loads(logData), indent=4)) 

How do I do base64 encoding on iOS?

#import "NSDataAdditions.h"
@implementation NSData (NSDataAdditions)

+ (NSData *) base64DataFromString: (NSString *)string {
  unsigned long ixtext, lentext;
  unsigned char ch, input[4], output[3];
  short i, ixinput;
  Boolean flignore, flendtext = false;
  const char *temporary;
  NSMutableData *result;

  if (!string)
    return [NSData data];

  ixtext = 0;
  temporary = [string UTF8String];
  lentext = [string length];
  result = [NSMutableData dataWithCapacity: lentext];
  ixinput = 0;

  while (true) {
    if (ixtext >= lentext)
    ch = temporary[ixtext++];
    flignore = false;

    if ((ch >= 'A') && (ch <= 'Z'))
      ch = ch - 'A';
    else if ((ch >= 'a') && (ch <= 'z'))
      ch = ch - 'a' + 26;
    else if ((ch >= '0') && (ch <= '9'))
      ch = ch - '0' + 52;
    else if (ch == '+')
      ch = 62;
    else if (ch == '=')
      flendtext = true;
    else if (ch == '/')
      ch = 63;
      flignore = true;

    if (!flignore) {
      short ctcharsinput = 3;
      Boolean flbreak = false;

      if (flendtext) {
         if (ixinput == 0)
         if ((ixinput == 1) || (ixinput == 2))
           ctcharsinput = 1;
           ctcharsinput = 2;
         ixinput = 3;
         flbreak = true;

      input[ixinput++] = ch;

      if (ixinput == 4){
        ixinput = 0;
        output[0] = (input[0] << 2) | ((input[1] & 0x30) >> 4);
        output[1] = ((input[1] & 0x0F) << 4) | ((input[2] & 0x3C) >> 2);
        output[2] = ((input[2] & 0x03) << 6) | (input[3] & 0x3F);
        for (i = 0; i < ctcharsinput; i++)
        [result appendBytes: &output[i] length: 1];
    if (flbreak)
  return result;

How to hide status bar in Android


Can I export a variable to the environment from a bash script without sourcing it?

Maybe you can write a function in ~/.zshrc, ~/.bashrc .

# set my env
[ -s ~/.env ] && export MYENV=`cat ~/.env`
function myenv() { [[ -s ~/.env ]] && echo $argv > ~/.env && export MYENV=$argv }

Beacause of use variable outside, you can avoid write script file.

Compare given date with today

Here you go:

function isToday($time) // midnight second
    return (strtotime($time) === strtotime('today'));

isToday('2010-01-22 00:00:00.0'); // true

Also, some more helper functions:

function isPast($time)
    return (strtotime($time) < time());

function isFuture($time)
    return (strtotime($time) > time());

.htaccess, order allow, deny, deny from all: confused?

This is a quite confusing way of using Apache configuration directives.

Technically, the first bit is equivalent to

Allow From All

This is because Order Deny,Allow makes the Deny directive evaluated before the Allow Directives. In this case, Deny and Allow conflict with each other, but Allow, being the last evaluated will match any user, and access will be granted.

Now, just to make things clear, this kind of configuration is BAD and should be avoided at all cost, because it borders undefined behaviour.

The Limit sections define which HTTP methods have access to the directory containing the .htaccess file.

Here, GET and POST methods are allowed access, and PUT and DELETE methods are denied access. Here's a link explaining what the various HTTP methods are:

However, it's more than often useless to use these limitations as long as you don't have custom CGI scripts or Apache modules that directly handle the non-standard methods (PUT and DELETE), since by default, Apache does not handle them at all.

It must also be noted that a few other methods exist that can also be handled by Limit, namely CONNECT, OPTIONS, PATCH, PROPFIND, PROPPATCH, MKCOL, COPY, MOVE, LOCK, and UNLOCK.

The last bit is also most certainly useless, since any correctly configured Apache installation contains the following piece of configuration (for Apache 2.2 and earlier):

# The following lines prevent .htaccess and .htpasswd files from being 
# viewed by Web clients. 
<Files ~ "^\.ht">
    Order allow,deny
    Deny from all
    Satisfy all

which forbids access to any file beginning by ".ht".

The equivalent Apache 2.4 configuration should look like:

<Files ~ "^\.ht">
    Require all denied

Gridview with two columns and auto resized images

another simple approach with modern built-in stuff like PercentRelativeLayout is now available for new users who hit this problem. thanks to android team for release this item.

< xmlns:android=""

<FrameLayout xmlns:android=""

        android:scaleType="centerCrop" />

        android:textColor="@android:color/white" />


and for better performance you can use some stuff like picasso image loader which help you to fill whole width of every image parents. for example in your adapter you should use this:

int width= context.getResources().getDisplayMetrics().widthPixels;
            .load("some url")

now you dont need CustomImageView Class anymore.

P.S i recommend to use ImageView in place of Type Int in class Item.

hope this help..

nodeJS - How to create and read session with express

Steps I did:

  1. Include the angular-cookies.js file in the HTML!
  2. Init cookies as being NOT http-only in server-side app.'s:

       //a bunch of stuff
       app.use(express.cookieSession({secret: 'mySecret', store: store, cookie: cookieSettings}));```
  3. Then in client-side services.jss I put ['ngCookies'] in like this:

    angular.module('swrp', ['ngCookies']).//etc

  4. Then in controller.js, in my function UserLoginCtrl, I have $cookies in there with $scope at the top like so:

    function UserLoginCtrl($scope, $cookies, socket) {

  5. Lastly, to get the value of a cookie inside the controller function I did:

    var mySession = $cookies['connect.sess'];

Now you can send that back to the server from the client. Awesome. Wish they would've put this in the Angular.js documentation. I figured it out by just reading the actual code for angular-cookies.js directly.

Jquery function return value

The return statement you have is stuck in the inner function, so it won't return from the outer function. You just need a little more code:

function getMachine(color, qty) {
    var returnValue = null;
    $("#getMachine li").each(function() {
        var thisArray = $(this).text().split("~");
        if(thisArray[0] == color&& qty>= parseInt(thisArray[1]) && qty<= parseInt(thisArray[2])) {
            returnValue = thisArray[3];
            return false; // this breaks out of the each
    return returnValue;

var retval = getMachine(color, qty);

How big can a MySQL database get before performance starts to degrade

The database size does matter. If you have more than one table with more than a million records, then performance starts indeed to degrade. The number of records does of course affect the performance: MySQL can be slow with large tables. If you hit one million records you will get performance problems if the indices are not set right (for example no indices for fields in "WHERE statements" or "ON conditions" in joins). If you hit 10 million records, you will start to get performance problems even if you have all your indices right. Hardware upgrades - adding more memory and more processor power, especially memory - often help to reduce the most severe problems by increasing the performance again, at least to a certain degree. For example 37 signals went from 32 GB RAM to 128GB of RAM for the Basecamp database server.

Converting a factor to numeric without losing information R (as.numeric() doesn't seem to work)

First, factor consists of indices and levels. This fact is very very important when you are struggling with factor.

For example,

> z <- factor(letters[c(3, 2, 3, 4)])

# human-friendly display, but internal structure is invisible
> z
[1] c b c d
Levels: b c d

# internal structure of factor
> unclass(z)
[1] 2 1 2 3
[1] "b" "c" "d"

here, z has 4 elements.
The index is 2, 1, 2, 3 in that order.
The level is associated with each index: 1 -> b, 2 -> c, 3 -> d.

Then, as.numeric converts simply the index part of factor into numeric.
as.character handles the index and levels, and generates character vector expressed by its level.

?as.numeric says that Factors are handled by the default method.

How can I get sin, cos, and tan to use degrees instead of radians?

Multiply the input by Math.PI/180 to convert from degrees to radians before calling the system trig functions.

You could also define your own functions:

function sinDegrees(angleDegrees) {
    return Math.sin(angleDegrees*Math.PI/180);

and so on.

passing argument to DialogFragment

Using newInstance

public static MyDialogFragment newInstance(int num) {
    MyDialogFragment f = new MyDialogFragment();

    // Supply num input as an argument.
    Bundle args = new Bundle();
    args.putInt("num", num);

    return f;

And get the Args like this

public void onCreate(Bundle savedInstanceState) {
    mNum = getArguments().getInt("num");

See the full example here

Page loaded over HTTPS but requested an insecure XMLHttpRequest endpoint

I had the same issue for my angular project, then I make it work in Chrome by changing the setting. Go to Chrome setting -->site setting -->Insecure content --> click add button of allow, then add your domain name [*.]

Now problem will be solved.

if, elif, else statement issues in Bash

There is a space missing between elif and [:

elif[ "$seconds" -gt 0 ]

should be

elif [ "$seconds" -gt 0 ]

As I see this question is getting a lot of views, it is important to indicate that the syntax to follow is:

if [ conditions ]
# ^ ^          ^

meaning that spaces are needed around the brackets. Otherwise, it won't work. This is because [ itself is a command.

The reason why you are not seeing something like elif[: command not found (or similar) is that after seeing if and then, the shell is looking for either elif, else, or fi. However it finds another then (after the mis-formatted elif[). Only after having parsed the statement it would be executed (and an error message like elif[: command not found would be output).

Why has it failed to load main-class manifest attribute from a JAR file?

I faced the same problem. This unix command is not able to find the main class. This is because the runtime and compile time JDK versions are different. Make the jar through eclipse after changing the java compiler version. The following link helped me.

Try running the jar created after this step and then execute it

Can the Android layout folder contain subfolders?

The answer is no.

I would like to draw your attention towards this book Pro Android 2 that states:

It is also worth noting a few constraints regarding resources. First, Android supports only a linear list of files within the predefined folders under res. For example, it does not support nested folders under the layout folder (or the other folders under res).

Second, there are some similarities between the assets folder and the raw folder under res. Both folders can contain raw files, but the files within raw are considered resources and the files within assets are not.

Note that because the contents of the assets folder are not considered resources, you can put an arbitrary hierarchy of folders and files within it.

How to properly -filter multiple strings in a PowerShell copy script

Something like this should work (it did for me). The reason for wanting to use -Filter instead of -Include is that include takes a huge performance hit compared to -Filter.

Below just loops each file type and multiple servers/workstations specified in separate files.

##  This script will pull from a list of workstations in a text file and search for the specified string

## Change the file path below to where your list of target workstations reside
## Change the file path below to where your list of filetypes reside

$filetypes = gc 'pathToListOffiletypes.txt'
$servers = gc 'pathToListOfWorkstations.txt'

##Set the scope of the variable so it has visibility
set-variable -Name searchString -Scope 0
$searchString = 'whatYouAreSearchingFor'

foreach ($server in $servers)

    foreach ($filetype in $filetypes)

    ## below creates the search path.  This could be further improved to exclude the windows directory
    $serverString = "\\"+$server+"\c$\Program Files"

    ## Display the server being queried
    write-host “Server:” $server "searching for " $filetype in $serverString

    Get-ChildItem -Path $serverString -Recurse -Filter $filetype |
    #-Include "*.xml","*.ps1","*.cnf","*.odf","*.conf","*.bat","*.cfg","*.ini","*.config","*.info","*.nfo","*.txt" |
    Select-String -pattern $searchstring | group path | select name | out-file f:\DataCentre\String_Results.txt

    $os = gwmi win32_operatingsystem -computer $server
    $sp = $os | % {$_.servicepackmajorversion}
    $a = $os | % {$_.caption}

    ##  Below will list again the server name as well as its OS and SP
    ##  Because the script may not be monitored, this helps confirm the machine has been successfully scanned
        write-host $server “has completed its " $filetype "scan:” “|” “OS:” $a “SP:” “|” $sp


#end script

Rotating a Vector in 3D Space

If you want to rotate a vector you should construct what is known as a rotation matrix.

Rotation in 2D

Say you want to rotate a vector or a point by ?, then trigonometry states that the new coordinates are

    x' = x cos ? - y sin ?
    y' = x sin ? + y cos ?

To demo this, let's take the cardinal axes X and Y; when we rotate the X-axis 90° counter-clockwise, we should end up with the X-axis transformed into Y-axis. Consider

    Unit vector along X axis = <1, 0>
    x' = 1 cos 90 - 0 sin 90 = 0
    y' = 1 sin 90 + 0 cos 90 = 1
    New coordinates of the vector, <x', y'> = <0, 1>  ?  Y-axis

When you understand this, creating a matrix to do this becomes simple. A matrix is just a mathematical tool to perform this in a comfortable, generalized manner so that various transformations like rotation, scale and translation (moving) can be combined and performed in a single step, using one common method. From linear algebra, to rotate a point or vector in 2D, the matrix to be built is

    |cos ?   -sin ?| |x| = |x cos ? - y sin ?| = |x'|
    |sin ?    cos ?| |y|   |x sin ? + y cos ?|   |y'|

Rotation in 3D

That works in 2D, while in 3D we need to take in to account the third axis. Rotating a vector around the origin (a point) in 2D simply means rotating it around the Z-axis (a line) in 3D; since we're rotating around Z-axis, its coordinate should be kept constant i.e. 0° (rotation happens on the XY plane in 3D). In 3D rotating around the Z-axis would be

    |cos ?   -sin ?   0| |x|   |x cos ? - y sin ?|   |x'|
    |sin ?    cos ?   0| |y| = |x sin ? + y cos ?| = |y'|
    |  0       0      1| |z|   |        z        |   |z'|

around the Y-axis would be

    | cos ?    0   sin ?| |x|   | x cos ? + z sin ?|   |x'|
    |   0      1       0| |y| = |         y        | = |y'|
    |-sin ?    0   cos ?| |z|   |-x sin ? + z cos ?|   |z'|

around the X-axis would be

    |1     0           0| |x|   |        x        |   |x'|
    |0   cos ?    -sin ?| |y| = |y cos ? - z sin ?| = |y'|
    |0   sin ?     cos ?| |z|   |y sin ? + z cos ?|   |z'|

Note 1: axis around which rotation is done has no sine or cosine elements in the matrix.

Note 2: This method of performing rotations follows the Euler angle rotation system, which is simple to teach and easy to grasp. This works perfectly fine for 2D and for simple 3D cases; but when rotation needs to be performed around all three axes at the same time then Euler angles may not be sufficient due to an inherent deficiency in this system which manifests itself as Gimbal lock. People resort to Quaternions in such situations, which is more advanced than this but doesn't suffer from Gimbal locks when used correctly.

I hope this clarifies basic rotation.

Rotation not Revolution

The aforementioned matrices rotate an object at a distance r = v(x² + y²) from the origin along a circle of radius r; lookup polar coordinates to know why. This rotation will be with respect to the world space origin a.k.a revolution. Usually we need to rotate an object around its own frame/pivot and not around the world's i.e. local origin. This can also be seen as a special case where r = 0. Since not all objects are at the world origin, simply rotating using these matrices will not give the desired result of rotating around the object's own frame. You'd first translate (move) the object to world origin (so that the object's origin would align with the world's, thereby making r = 0), perform the rotation with one (or more) of these matrices and then translate it back again to its previous location. The order in which the transforms are applied matters. Combining multiple transforms together is called concatenation or composition.


I urge you to read about linear and affine transformations and their composition to perform multiple transformations in one shot, before playing with transformations in code. Without understanding the basic maths behind it, debugging transformations would be a nightmare. I found this lecture video to be a very good resource. Another resource is this tutorial on transformations that aims to be intuitive and illustrates the ideas with animation (caveat: authored by me!).

Rotation around Arbitrary Vector

A product of the aforementioned matrices should be enough if you only need rotations around cardinal axes (X, Y or Z) like in the question posted. However, in many situations you might want to rotate around an arbitrary axis/vector. The Rodrigues' formula (a.k.a. axis-angle formula) is a commonly prescribed solution to this problem. However, resort to it only if you’re stuck with just vectors and matrices. If you're using Quaternions, just build a quaternion with the required vector and angle. Quaternions are a superior alternative for storing and manipulating 3D rotations; it's compact and fast e.g. concatenating two rotations in axis-angle representation is fairly expensive, moderate with matrices but cheap in quaternions. Usually all rotation manipulations are done with quaternions and as the last step converted to matrices when uploading to the rendering pipeline. See Understanding Quaternions for a decent primer on quaternions.

fork() child and parent processes

This is the correct way for getting the correct output.... However, childs parent id maybe sometimes printed as 1 because parent process gets terminated and the root process with pid = 1 controls this orphan process.

 pid_t  pid;
 pid = fork();
 if (pid == 0) 
    printf("This is the child process. My pid is %d and my parent's id 
      is %d.\n", getpid(), getppid());
     printf("This is the parent process. My pid is %d and my parent's 
         id is %d.\n", getpid(), pid);

MySQL add days to a date

For your need:

UPDATE classes 
SET `date` = DATE_ADD(`date`, INTERVAL 2 DAY)
WHERE id = 161

Can I simultaneously declare and assign a variable in VBA?

You can define and assign value as shown below in one line. I have given an example of two variables declared and assigned in single line. if the data type of multiple variables are same

 Dim recordStart, recordEnd As Integer: recordStart = 935: recordEnd = 946

gradlew command not found?

I use intellj idea and in windows in terminal type: gradlew.bat run it is working for me.

How to fully clean bin and obj folders within Visual Studio?

You can easily find and remove bin and obj folders in Far Manager.

  1. Navigate to you solution and press Alt+F7
  2. In search setting dialog:

    • Type "bin,obj" in field "A file mask or several file masks"
    • Check option "Search for folders"
    • Press Enter
  3. After the search is done, switch view to "Panel".

  4. Select all files (with Ctrl+A) and delete folders (press "Shift+Del")

Hope it helps someone.

When to use in vs ref vs out

Below are some notes which i pulled from this codeproject article on C# Out Vs Ref

  1. It should be used only when we are expecting multiple outputs from a function or a method. A thought on structures can be also a good option for the same.
  2. REF and OUT are keywords which dictate how data is passed from caller to callee and vice versa.
  3. In REF data passes two way. From caller to callee and vice-versa.
  4. In Out data passes only one way from callee to caller. In this case if Caller tried to send data to the callee it will be overlooked / rejected.

If you are a visual person then please see this yourtube video which demonstrates the difference practically

Below image shows the differences more visually

C# Out Vs Ref

Disable keyboard on EditText

Below code is both for API >= 11 and API < 11. Cursor is still available.

 * Disable soft keyboard from appearing, use in conjunction with android:windowSoftInputMode="stateAlwaysHidden|adjustNothing"
 * @param editText
public static void disableSoftInputFromAppearing(EditText editText) {
    if (Build.VERSION.SDK_INT >= 11) {
    } else {

Use index in pandas to plot data

Try this,

monthly_mean.plot(y='A', use_index=True)

How to resolve the "ADB server didn't ACK" error?

On my Mac, I wrote this code in my Terminal:

xxx-MacBook-Pro:~ xxx$ cd /Users/xxx/Documents/0_Software/adt20140702/sdk/platform-tools/

xxx-MacBook-Pro:platform-tools xxx$ ./adb kill-server

xxx-MacBook-Pro:platform-tools xxx$ ./adb start-server

  • daemon not running. starting it now on port 5037 *
  • daemon started successfully *

xxx-MacBook-Pro:platform-tools tuananh$

Hope this help.

Proxy with urllib2

You can set proxies using environment variables.

import os
os.environ['http_proxy'] = ''
os.environ['https_proxy'] = ''

urllib2 will add proxy handlers automatically this way. You need to set proxies for different protocols separately otherwise they will fail (in terms of not going through proxy), see below.

For example:

proxy = urllib2.ProxyHandler({'http': ''})
opener = urllib2.build_opener(proxy)
# next line will fail (will not go through the proxy) (https)


proxy = urllib2.ProxyHandler({
    'http': '',
    'https': ''
opener = urllib2.build_opener(proxy)
# this way both http and https requests go through the proxy

Go: panic: runtime error: invalid memory address or nil pointer dereference

According to the docs for func (*Client) Do:

"An error is returned if caused by client policy (such as CheckRedirect), or if there was an HTTP protocol error. A non-2xx response doesn't cause an error.

When err is nil, resp always contains a non-nil resp.Body."

Then looking at this code:

res, err := client.Do(req)
defer res.Body.Close()

if err != nil {
    return nil, err

I'm guessing that err is not nil. You're accessing the .Close() method on res.Body before you check for the err.

The defer only defers the function call. The field and method are accessed immediately.

So instead, try checking the error immediately.

res, err := client.Do(req)

if err != nil {
    return nil, err
defer res.Body.Close()

#1142 - SELECT command denied to user ''@'localhost' for table 'pma_table_uiprefs'

There is another way of solving this.

Following the instructions in

1.- I opned xampp\phpMyAdmin\ file and found the following lines:

/* User for advanced features */\\

$cfg['Servers'][$i]['controluser'] = 'pma';

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

2.- Then I observed in phpmyadmin the following tables:

DATABASE: phpmyadmin

TABLES: pma_bookmark pma_column_info pma_designer_coords pma_history pma_pdf_pages pma_recent pma_relation pma_table_coords pma_table_info pma_table_uiprefs pma_tracking pma_userconfig

3.- I run this sql statement:

 GRANT SELECT , INSERT , UPDATE , DELETE ON phpmyadmin.* TO  `pma`@`localhost` IDENTIFIED BY  ''

And it worked.

How do I set a textbox's value using an anchor with jQuery?

To assign value of a text box whose id is "textbox" in JQuery please do the following

$("#textbox").get(0).value = "blah"

Adding to a vector of pair

Use std::make_pair:


Error: "The sandbox is not in sync with the Podfile.lock..." after installing RestKit with cocoapods

I encountered this issue with a misconfigured xcconfig file.

The Pods-generated xcconfig was not correctly #included in the customise xcconfig that I was using. This caused $PODS_ROOT to not be set resulting in the failure of diff "/../Podfile.lock" "/Manifest.lock", for obvious reasons, which Pods misinterprets as a sync issue.

Create SQLite Database and table

The next link will bring you to a great tutorial, that helped me a lot!

How to SQLITE in C#

I nearly used everything in that article to create the SQLite database for my own C# Application.

Don't forget to download the SQLite.dll, and add it as a reference to your project. This can be done using NuGet and by adding the dll manually.

After you added the reference, refer to the dll from your code using the following line on top of your class:

using System.Data.SQLite;

You can find the dll's here:

SQLite DLL's

You can find the NuGet way here:


Up next is the create script. Creating a database file:


SQLiteConnection m_dbConnection = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;");

string sql = "create table highscores (name varchar(20), score int)";

SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);

sql = "insert into highscores (name, score) values ('Me', 9001)";

command = new SQLiteCommand(sql, m_dbConnection);


After you created a create script in C#, I think you might want to add rollback transactions, it is safer and it will keep your database from failing, because the data will be committed at the end in one big piece as an atomic operation to the database and not in little pieces, where it could fail at 5th of 10 queries for example.

Example on how to use transactions:

 using (TransactionScope tran = new TransactionScope())
     //Insert create script here.

     //Indicates that creating the SQLiteDatabase went succesfully, so the database can be committed.

Error "The connection to adb is down, and a severe error has occurred."

Eclipse ? preferences ? Android ? NDK

Check the "NDK Location" path is set correctly, and use the browse button to set it.

How do I stop/start a scheduled task on a remote computer programmatically?

Here's what I found.


schtasks /end /s <machine name> /tn <task name>


schtasks /run /s <machine name> /tn <task name>

C:\>schtasks /?

SCHTASKS /parameter [arguments]

    Enables an administrator to create, delete, query, change, run and
    end scheduled tasks on a local or remote system. Replaces AT.exe.

Parameter List:
    /Create         Creates a new scheduled task.

    /Delete         Deletes the scheduled task(s).

    /Query          Displays all scheduled tasks.

    /Change         Changes the properties of scheduled task.

    /Run            Runs the scheduled task immediately.

    /End            Stops the currently running scheduled task.

    /?              Displays this help message.

    SCHTASKS /Run /?
    SCHTASKS /End /?
    SCHTASKS /Create /?
    SCHTASKS /Delete /?
    SCHTASKS /Query  /?
    SCHTASKS /Change /?

CURL to pass SSL certifcate and password

Addition to previous answer make sure that your curl installation supports https.
You can use curl --version to get information about supported protocols.

If your curl supports https follow the previous answer.

curl --cert certificate_path:password

If it does not support https, you need to install a cURL version that supports https.

Space between border and content? / Border distance from content?

Its possible using pseudo element (after).
I have added to the original code a

and some margin.
Here is the modified JSFiddle:

  width: 100px;
  min-height: 100px;
  margin: 20px auto;
  border-style: ridge;
  border-color: #567498;
#content:after {
  content: '';
  position: absolute;
  top: -15px;
  left: -15px;
  right: -15px;
  bottom: -15px;
  border: red 2px solid;

How to split a string in Haskell?

Without importing anything a straight substitution of one character for a space, the target separator for words is a space. Something like:

words [if c == ',' then ' ' else c|c <- "my,comma,separated,list"]


words let f ',' = ' '; f c = c in map f "my,comma,separated,list"

You can make this into a function with parameters. You can eliminate the parameter character-to-match my matching many, like in:

 [if elem c ";,.:-+@!$#?" then ' ' else c|c <-"my,comma;separated!list"]

SQL How to Select the most recent date item

With SQL Server try:

SELECT TOP 1 * FROM dbo.youTable WHERE user_id = 'userid' ORDER BY date_added desc

org.apache.catalina.core.StandardContext startInternal SEVERE: Error listenerStart

I faced exactly the same issue in a Spring web app. In fact, I had removed spring-security by commenting the config annotation:

// @ImportResource({"/WEB-INF/spring-security.xml"})

but I had forgotten to remove the corresponding filters in web.xml:

<!-- Filters --> 


Commenting filters solved the issue.

How to select min and max values of a column in a datatable?

Use LINQ. It works just fine on datatables, as long as you convert the rows collection to an IEnumerable.

List<int> levels = AccountTable.AsEnumerable().Select(al => al.Field<int>("AccountLevel")).Distinct().ToList();
int min = levels.Min();
int max = levels.Max();

Edited to fix syntax; it's tricky when using LINQ on DataTables, and aggregating functions are fun, too.

Yes, it can be done with one query, but you will need to generate a list of results, then use .Min() and .Max() as aggregating functions in separate statements.

Is key-value pair available in Typescript?

class Pair<T1, T2> {
    private key: T1;
    private value: T2;

    constructor(key: T1, value: T2) {
        this.key = key;
        this.value = value;

    getKey() {
        return this.key;

    getValue() {
        return this.value;
const myPair = new Pair<string, number>('test', 123);
console.log(myPair.getKey(), myPair.getValue());

ngOnInit not being called when Injectable class is Instantiated

import {Injectable, OnInit} from 'angular2/core';
import { RestApiService, RestRequest } from './rest-api.service';
import {Service} from "path/to/service/";

export class MovieDbService implements OnInit {


constructor(private _movieDbRest: RestApiService,
            private instanceMyService : Service ){

   // do evreything like OnInit just on services


   this.userId = this.instanceMyService.getUserId()


What is the best way to remove the first element from an array?

You can't do it at all, let alone quickly. Arrays in Java are fixed size. Two things you could do are:

  1. Shift every element up one, then set the last element to null.
  2. Create a new array, then copy it.

You can use System.arraycopy for either of these. Both of these are O(n), since they copy all but 1 element.

If you will be removing the first element often, consider using LinkedList instead. You can use LinkedList.remove, which is from the Queue interface, for convenience. With LinkedList, removing the first element is O(1). In fact, removing any element is O(1) once you have a ListIterator to that position. However, accessing an arbitrary element by index is O(n).

Docker: How to use bash with an Alpine based docker image?

To Install bash you can do:

RUN apk add --update bash && rm -rf /var/cache/apk/*

If you do not want to add extra size to your image, you can use ash or sh that ships with alpine.


How to create an array of object literals in a loop?

RaYell's answer is good - it answers your question.

It seems to me though that you should really be creating an object keyed by labels with sub-objects as values:

var columns = {};
for (var i = 0; i < oFullResponse.results.length; i++) {
    var key = oFullResponse.results[i].label;
    columns[key] = {
        sortable: true,
        resizeable: true

// Now you can access column info like this. 

The above approach should be much faster and idiomatic than searching the entire object array for a key for each access.

Maven: add a folder or jar file into current classpath

The classpath setting of the compiler plugin are two args. Changed it like this and it worked for me:


I used the gmavenplus-plugin to read the path and create the property 'cp':

      Use Groovy to read classpath and store into
      file named value of property <cpfile>

      In second step use Groovy to read the contents of
      the file into a new property named <cp>

      In the compiler plugin this is used to create a
      valid classpath
        <!-- any version of Groovy \>= 1.5.0 should work here -->

                def file = new File(
                /* create a new property named 'cp'*/
       = file.getText()
                println '<<< Retrieving classpath into new property named <cp> >>>'
                println 'cp = ' +

How do I convert a double into a string in C++?

Use to_string().
example :

#include <iostream>   
#include <string>  

using namespace std;
int main ()
    string pi = "pi is " + to_string(3.1415926);
    cout<< "pi = "<< pi << endl;

  return 0;

run it yourself :
These are available as well :

string to_string (int val);
string to_string (long val);
string to_string (long long val);
string to_string (unsigned val);
string to_string (unsigned long val);
string to_string (unsigned long long val);
string to_string (float val);
string to_string (double val);
string to_string (long double val);

Oracle SQL Query for listing all Schemas in a DB

Using sqlplus

sqlplus / as sysdba


FROM dba_users

Should you only want the usernames do the following:

SELECT username 
FROM dba_users

Installing Java 7 (Oracle) in Debian via apt-get

Managed to get answer after do some google..

echo "deb precise main" | tee -a /etc/apt/sources.list
echo "deb-src precise main" | tee -a /etc/apt/sources.list
apt-key adv --keyserver hkp:// --recv-keys EEA14886
apt-get update
# Java 7
apt-get install oracle-java7-installer
# For Java 8 command is:
apt-get install oracle-java8-installer

Iterate through a HashMap


for (String key : hashMap.keySet()) {
    System.out.println("Key: " + key + ", Value: " + map.get(key));

Oracle database: How to read a BLOB?

SQL Developer can show the blob as an image (at least it works for jpegs). In the Data view, double click on the BLOB field to get the "pencil" icon. Click on the pencil to get a dialog that will allow you to select a "View As Image" checkbox.

Java System.out.print formatting

Something likes this

public void testPrintOut() {
    int val1 = 8;
    String val2 = "$951.23";
    String val3 = "$215.92";
    String val4 = "$198,301.22";
    System.out.println(String.format("%03d %7s %7s %11s", val1, val2, val3, val4));

    val1 = 9;
    val2 = "$950.19";
    val3 = "$216.95";
    val4 = "$198,084.26";
    System.out.println(String.format("%03d %7s %7s %11s", val1, val2, val3, val4));

Why use Redux over Facebook Flux?

Redux author here!

Redux is not that different from Flux. Overall it has same architecture, but Redux is able to cut some complexity corners by using functional composition where Flux uses callback registration.

There is not a fundamental difference in Redux, but I find it makes certain abstractions easier, or at least possible to implement, that would be hard or impossible to implement in Flux.

Reducer Composition

Take, for example, pagination. My Flux + React Router example handles pagination, but the code for that is awful. One of the reasons it's awful is that Flux makes it unnatural to reuse functionality across stores. If two stores need to handle pagination in response to different actions, they either need to inherit from a common base store (bad! you're locking yourself into a particular design when you use inheritance), or call an externally defined function from within the event handler, which will need to somehow operate on the Flux store's private state. The whole thing is messy (although definitely in the realm of possible).

On the other hand, with Redux pagination is natural thanks to reducer composition. It's reducers all the way down, so you can write a reducer factory that generates pagination reducers and then use it in your reducer tree. The key to why it's so easy is because in Flux, stores are flat, but in Redux, reducers can be nested via functional composition, just like React components can be nested.

This pattern also enables wonderful features like no-user-code undo/redo. Can you imagine plugging Undo/Redo into a Flux app being two lines of code? Hardly. With Redux, it is—again, thanks to reducer composition pattern. I need to highlight there's nothing new about it—this is the pattern pioneered and described in detail in Elm Architecture which was itself influenced by Flux.

Server Rendering

People have been rendering on the server fine with Flux, but seeing that we have 20 Flux libraries each attempting to make server rendering “easier”, perhaps Flux has some rough edges on the server. The truth is Facebook doesn't do much server rendering, so they haven't been very concerned about it, and rely on the ecosystem to make it easier.

In traditional Flux, stores are singletons. This means it's hard to separate the data for different requests on the server. Not impossible, but hard. This is why most Flux libraries (as well as the new Flux Utils) now suggest you use classes instead of singletons, so you can instantiate stores per request.

There are still the following problems that you need to solve in Flux (either yourself or with the help of your favorite Flux library such as Flummox or Alt):

  • If stores are classes, how do I create and destroy them with dispatcher per request? When do I register stores?
  • How do I hydrate the data from the stores and later rehydrate it on the client? Do I need to implement special methods for this?

Admittedly Flux frameworks (not vanilla Flux) have solutions to these problems, but I find them overcomplicated. For example, Flummox asks you to implement serialize() and deserialize() in your stores. Alt solves this nicer by providing takeSnapshot() that automatically serializes your state in a JSON tree.

Redux just goes further: since there is just a single store (managed by many reducers), you don't need any special API to manage the (re)hydration. You don't need to “flush” or “hydrate” stores—there's just a single store, and you can read its current state, or create a new store with a new state. Each request gets a separate store instance. Read more about server rendering with Redux.

Again, this is a case of something possible both in Flux and Redux, but Flux libraries solve this problem by introducing a ton of API and conventions, and Redux doesn't even have to solve it because it doesn't have that problem in the first place thanks to conceptual simplicity.

Developer Experience

I didn't actually intend Redux to become a popular Flux library—I wrote it as I was working on my ReactEurope talk on hot reloading with time travel. I had one main objective: make it possible to change reducer code on the fly or even “change the past” by crossing out actions, and see the state being recalculated.

I haven't seen a single Flux library that is able to do this. React Hot Loader also doesn't let you do this—in fact it breaks if you edit Flux stores because it doesn't know what to do with them.

When Redux needs to reload the reducer code, it calls replaceReducer(), and the app runs with the new code. In Flux, data and functions are entangled in Flux stores, so you can't “just replace the functions”. Moreover, you'd have to somehow re-register the new versions with the Dispatcher—something Redux doesn't even have.


Redux has a rich and fast-growing ecosystem. This is because it provides a few extension points such as middleware. It was designed with use cases such as logging, support for Promises, Observables, routing, immutability dev checks, persistence, etc, in mind. Not all of these will turn out to be useful, but it's nice to have access to a set of tools that can be easily combined to work together.


Redux preserves all the benefits of Flux (recording and replaying of actions, unidirectional data flow, dependent mutations) and adds new benefits (easy undo-redo, hot reloading) without introducing Dispatcher and store registration.

Keeping it simple is important because it keeps you sane while you implement higher-level abstractions.

Unlike most Flux libraries, Redux API surface is tiny. If you remove the developer warnings, comments, and sanity checks, it's 99 lines. There is no tricky async code to debug.

You can actually read it and understand all of Redux.

See also my answer on downsides of using Redux compared to Flux.

How to change max_allowed_packet size

in MYSQL 5.7, max_allowed_packet is at most 1G. if you want to set it to 4G, it would failed without error and warning.

C# binary literals

If you look at the language feature implementation status of the .NET Compiler Platform ("Roslyn") you can clearly see that in C# 6.0 this is a planned feature, so in the next release we can do it in the usual way.

Binary literal status

Putting GridView data in a DataTable

protected void btnExportExcel_Click(object sender, EventArgs e)
    DataTable _datatable = new DataTable();
    for (int i = 0; i < grdReport.Columns.Count; i++)
    foreach (GridViewRow row in grdReport.Rows)
        DataRow dr = _datatable.NewRow();
        for (int j = 0; j < grdReport.Columns.Count; j++)
            if (!row.Cells[j].Text.Equals("&nbsp;"))
                dr[grdReport.Columns[j].ToString()] = row.Cells[j].Text;


how to remove the first two columns in a file using shell (awk, sed, whatever)

Its pretty straight forward to do it with only shell

while read A B C; do
echo "$C"
done < oldfile >newfile

How do I append to a table in Lua

I'd personally make use of the table.insert function:


This saves you from having to iterate over the whole table therefore saving valuable resources such as memory and time.

Responsive Images with CSS

Use max-width:100%;, height: auto; and display:block; as follow:

image {
    height: auto;

Get latest from Git branch

use git pull:

git pull origin yourbranch

How do I remove  from the beginning of a file?

I don't know PHP, so I don't know if this is possible, but the best solution would be to read the file as UTF-8 rather than some other encoding. The BOM is actually a ZERO WIDTH NO BREAK SPACE. This is whitespace, so if the file were being read in the correct encoding (UTF-8), then the BOM would be interpreted as whitespace and it would be ignored in the resulting CSS file.

Also, another advantage of reading the file in the correct encoding is that you don't have to worry about characters being misinterpreted. Your editor is telling you that the code page you want to save it in won't do all the characters that you need. If PHP is then reading the file in the incorrect encoding, then it is very likely that other characters besides the BOM are being silently misinterpreted. Use UTF-8 everywhere, and these problems disappear.

getResourceAsStream() is always returning null

I had a similar problem and I searched for the solution for quite a while: It appears that the string parameter is case sensitive. So if your filename is abc.TXT but you search for abc.txt, eclipse will find it - the executable JAR file won't.

Serializing class instance to JSON

Use arbitrary, extensible object, and then serialize it to JSON:

import json

class Object(object):

response = Object()
response.debug = []
response.result = Object()

# Any manipulations with the object:
response.debug.append("Debug string here")
response.result.body = "404 Not Found"
response.result.code = 404

# Proper JSON output, with nice formatting:
print(json.dumps(response, indent=4, default=lambda x: x.__dict__))

Excel data validation with suggestions/autocomplete

This is a solution how to make autocomplete drop down list with VBA :

Firstly you need to insert a combo box into the worksheet and change its properties, and then running the VBA code to enable the autocomplete.

  1. Get into the worksheet which contains the drop down list you want it to be autocompleted.

  2. Before inserting the Combo box, you need to enable the Developer tab in the ribbon.

a). In Excel 2010 and 2013, click File > Options. And in the Options dialog box, click Customize Ribbon in the right pane, check the Developer box, then click the OK button.

b). In Outlook 2007, click Office button > Excel Options. In the Excel Options dialog box, click Popular in the right bar, then check the Show Developer tabin the Ribbon box, and finally click the OK button.

  1. Then click Developer > Insert > Combo Box under ActiveX Controls.

  2. Draw the combo box in current opened worksheet and right click it. Select Properties in the right-clicking menu.

  3. Turn off the Design Mode with clicking Developer > Design Mode.

  4. Right click on the current opened worksheet tab and click View Code.

  5. Make sure that the current worksheet code editor is opened, and then copy and paste the below VBA code into it.

Code borrowed from

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
'Update by Extendoffice: 2018/9/21
    Dim xCombox As OLEObject
    Dim xStr As String
    Dim xWs As Worksheet
    Dim xArr

    Set xWs = Application.ActiveSheet
    On Error Resume Next
    Set xCombox = xWs.OLEObjects("TempCombo")
    With xCombox
        .ListFillRange = ""
        .LinkedCell = ""
        .Visible = False
    End With
    If Target.Validation.Type = 3 Then
        Target.Validation.InCellDropdown = False
        Cancel = True
        xStr = Target.Validation.Formula1
        xStr = Right(xStr, Len(xStr) - 1)
        If xStr = "" Then Exit Sub
        With xCombox
            .Visible = True
            .Left = Target.Left
            .Top = Target.Top
            .Width = Target.Width + 5
            .Height = Target.Height + 5
            .ListFillRange = xStr
            If .ListFillRange = "" Then
                xArr = Split(xStr, ",")
                Me.TempCombo.List = xArr
            End If
            .LinkedCell = Target.Address
        End With
    End If
End Sub

Private Sub TempCombo_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
    Select Case KeyCode
        Case 9
            Application.ActiveCell.Offset(0, 1).Activate
        Case 13
            Application.ActiveCell.Offset(1, 0).Activate
    End Select
End Sub
  1. Click File > Close and Return to Microsoft Excel to close the Microsoft Visual Basic for Application window.

  2. Now, just click the cell with drop down list, you can see the drop-down list is displayed as a combo box, then type the first letter into the box, the corresponding word will be completed automatically.

Note: This VBA code is not applied to merged cells.

Source : How To Autocomplete When Typing In Excel Drop Down List?

Elasticsearch : Root mapping definition has unsupported parameters index : not_analyzed

You're almost here, you're just missing a few things:

PUT /test
  "mappings": {
    "type_name": {                <--- add the type name
      "properties": {             <--- enclose all field definitions in "properties"
        "field1": {
          "type": "integer"
        "field2": {
          "type": "integer"
        "field3": {
          "type": "string",
          "index": "not_analyzed"
        "field4,": {
          "type": "string",
          "analyzer": "autocomplete",
          "search_analyzer": "standard"
  "settings": {


If your index already exists, you can also modify your mappings like this:

PUT test/_mapping/type_name
    "properties": {             <--- enclose all field definitions in "properties"
        "field1": {
          "type": "integer"
        "field2": {
          "type": "integer"
        "field3": {
          "type": "string",
          "index": "not_analyzed"
        "field4,": {
          "type": "string",
          "analyzer": "autocomplete",
          "search_analyzer": "standard"


As of ES 7, mapping types have been removed. You can read more details here

Type safety: Unchecked cast

Well, first of all, you're wasting memory with the new HashMap creation call. Your second line completely disregards the reference to this created hashmap, making it then available to the garbage collector. So, don't do that, use:

private Map<String, String> someMap = (HashMap<String, String>)getApplicationContext().getBean("someMap");

Secondly, the compiler is complaining that you cast the object to a HashMap without checking if it is a HashMap. But, even if you were to do:

if(getApplicationContext().getBean("someMap") instanceof HashMap) {
    private Map<String, String> someMap = (HashMap<String, String>)getApplicationContext().getBean("someMap");

You would probably still get this warning. The problem is, getBean returns Object, so it is unknown what the type is. Converting it to HashMap directly would not cause the problem with the second case (and perhaps there would not be a warning in the first case, I'm not sure how pedantic the Java compiler is with warnings for Java 5). However, you are converting it to a HashMap<String, String>.

HashMaps are really maps that take an object as a key and have an object as a value, HashMap<Object, Object> if you will. Thus, there is no guarantee that when you get your bean that it can be represented as a HashMap<String, String> because you could have HashMap<Date, Calendar> because the non-generic representation that is returned can have any objects.

If the code compiles, and you can execute String value = map.get("thisString"); without any errors, don't worry about this warning. But if the map isn't completely of string keys to string values, you will get a ClassCastException at runtime, because the generics cannot block this from happening in this case.

How to remove a branch locally?

I think (based on your comments) that I understand what you want to do: you want your local copy of the repository to have neither the ordinary local branch master, nor the remote-tracking branch origin/master, even though the repository you cloned—the github one—has a local branch master that you do not want deleted from the github version.

You can do this by deleting the remote-tracking branch locally, but it will simply come back every time you ask your git to synchronize your local repository with the remote repository, because your git asks their git "what branches do you have" and it says "I have master" so your git (re)creates origin/master for you, so that your repository has what theirs has.

To delete your remote-tracking branch locally using the command line interface:

git branch -d -r origin/master

but again, it will just come back on re-synchronizations. It is possible to defeat this as well (using remote.origin.fetch manipulation), but you're probably better off just being disciplined enough to not create or modify master locally.

ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)

Open a terminal and take a look at:

/Applications/Python 3.6/Install Certificates.command

Python 3.6 on MacOS uses an embedded version of OpenSSL, which does not use the system certificate store. More details here.

(To be explicit: MacOS users can probably resolve by opening Finder and double clicking Install Certificates.command)

List Directories and get the name of the Directory

You seem to be using Python as if it were the shell. Whenever I've needed to do something like what you're doing, I've used os.walk()

For example, as explained here: [x[0] for x in os.walk(directory)] should give you all of the subdirectories, recursively.

How read Doc or Docx file in java?

Here is the code of ReadDoc/ This will read a dox/docx file and print its content to the console. you can customize it your way.

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;

public class ReadDocFile
    public static void main(String[] args)
        File file = null;
        WordExtractor extractor = null;

            file = new File("c:\\New.doc");
            FileInputStream fis = new FileInputStream(file.getAbsolutePath());
            HWPFDocument document = new HWPFDocument(fis);
            extractor = new WordExtractor(document);
            String[] fileData = extractor.getParagraphText();
            for (int i = 0; i < fileData.length; i++)
                if (fileData[i] != null)
        catch (Exception exep)

What is the command for cut copy paste a file from one directory to other directory

use the xclip which is command line interface to X selections


apt-get install xclip


echo "test xclip " > /tmp/test.xclip
xclip -i < /tmp/test.xclip
xclip -o > /tmp/test.xclip.out

cat /tmp/test.xclip.out   # "test xclip"


How to rotate portrait/landscape Android emulator?

Yes. Thanks

Ctrl + F11 for Portrait


Ctrl + F12 for Landscape

How to add a scrollbar to an HTML5 table?

You can use a division class with the overflow attribute using the value scroll. Or you can enclose the table inside an iframe. The iframe works well with old and new IE browsers, but it may not work with other browsers and probably not with the latest IE.

 #myid { overflow-x: scroll; overflow-y: hide; width:200px; /* Or whatever the amount of pixels */ }
.myid { overflow-x: scroll; overflow-y: hide; width:200px; /* Or whatever the amount of pixels */ }

<div class="myid">
     <div class="row">Content1</div>
     <div class="row2">Content2</div>

<table id="myid"><tr><td>Content</td></tr></table>

How can I set the default timezone in node.js?

Here's an answer for those deploying a Node.js application to Amazon AWS Elastic Beanstalk. I haven't seen this documented anywhere else:

Under Configuration -> Software -> Environment Properties, simply set the key value pair TZ and your time zone e.g. America/Los Angeles, and Apply the change.

You can verify the effect by outputting new Date().toString() in your Node app and paying attention to the time zone suffix.

PHP multidimensional array search by value

Here is one liner for the same,

$pic_square = $userdb[array_search($uid,array_column($userdb, 'uid'))]['pic_square'];

How to install PostgreSQL's pg gem on Ubuntu?

Another option is to use Homebrew which works on Linux and macOS to install just the supporting libraries:

brew install libpq


brew link libpq --force

(the --force option is required because it conflicts with the postgres formula.)

Add to python path mac os x

Mathew's answer works for the terminal python shell, but it didn't work for IDLE shell in my case because many versions of python existed before I replaced them all with Python2.7.7. How I solved the problem with IDLE.

  1. In terminal, cd /Applications/Python\ 2.7/
  2. then sudo nano, enter password if required.
  3. after os.chdir(os.path.expanduser('~/Documents')) this line, I added sys.path.append("/Users/admin/Downloads....") NOTE: replace contents of the quotes with the directory where python module to be added
  4. to save the change, ctrl+x and enter Now open idle and try to import the python module, no error for me!!!

Closing database connections in Java

When you are done with using your Connection, you need to explicitly close it by calling its close() method in order to release any other database resources (cursors, handles, etc.) the connection may be holding on to.

Actually, the safe pattern in Java is to close your ResultSet, Statement, and Connection (in that order) in a finally block when you are done with them. Something like this:

Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;

try {
    // Do stuff

} catch (SQLException ex) {
    // Exception handling stuff
} finally {
    if (rs != null) {
        try {
        } catch (SQLException e) { /* Ignored */}
    if (ps != null) {
        try {
        } catch (SQLException e) { /* Ignored */}
    if (conn != null) {
        try {
        } catch (SQLException e) { /* Ignored */}

The finally block can be slightly improved into (to avoid the null check):

} finally {
    try { rs.close(); } catch (Exception e) { /* Ignored */ }
    try { ps.close(); } catch (Exception e) { /* Ignored */ }
    try { conn.close(); } catch (Exception e) { /* Ignored */ }

But, still, this is extremely verbose so you generally end up using an helper class to close the objects in null-safe helper methods and the finally block becomes something like this:

} finally {

And, actually, the Apache Commons DbUtils has a DbUtils class which is precisely doing that, so there isn't any need to write your own.

SQL: capitalize first letter only

Please check the query without using a function:

declare @T table(Insurance varchar(max))

insert into @T values ('wezembeek-oppem')
insert into @T values ('roeselare')
insert into @T values ('BRUGGE')
insert into @T values ('louvain-la-neuve')

select (
       select upper(T.N.value('.', 'char(1)'))+
                lower(stuff(T.N.value('.', 'varchar(max)'), 1, 1, ''))+(CASE WHEN RIGHT(T.N.value('.', 'varchar(max)'), 1)='-' THEN '' ELSE ' ' END)
       from X.InsXML.nodes('/N') as T(N)
       for xml path(''), type
       ).value('.', 'varchar(max)') as Insurance
  select cast('<N>'+replace(
                ' ', '</N><N>'),
            '-', '-</N><N>')+'</N>' as xml) as InsXML
  from @T
  ) as X

Redirecting from HTTP to HTTPS with PHP

On my AWS beanstalk server, I don't see $_SERVER['HTTPS'] variable. I do see $_SERVER['HTTP_X_FORWARDED_PROTO'] which can be either 'http' or 'https' so if you're hosting on AWS, use this:

if ($_SERVER['HTTP_HOST'] != 'localhost' and $_SERVER['HTTP_X_FORWARDED_PROTO'] != "https") {
    $location = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    header('HTTP/1.1 301 Moved Permanently');
    header('Location: ' . $location);

SVN Commit specific files

Sure. Just list the files:

$ svn ci -m "Fixed all those horrible crashes" foo bar baz graphics/logo.png

I'm not aware of a way to tell it to ignore a certain set of files. Of course, if the files you do want to commit are easily listed by the shell, you can use that:

$ svn ci -m "No longer sets printer on fire" printer-driver/*.c

You can also have the svn command read the list of files to commit from a file:

$ svn ci -m "Now works" --targets fix4711.txt

How do I export a project in the Android studio?

Follow this steps:

-Generate Signed Apk
-Create new

Then fill up "New Key Store" form. If you wand to change .jnk file destination then chick on destination and give a name to get Ok button. After finishing it you will get "Key store password", "Key alias", "Key password" Press next and change your the destination folder. Then press finish, thats all. :)

enter image description here

enter image description here enter image description here

enter image description here enter image description here

Adjust list style image position?

The solution I settled for in the end was to modify the image itself to add some spacing.

Using a background image on the li as some suggest works in a lot of cases but fails when the list is used alongside a floated image (for example to get the text to wrap around the image).

Hope this helps.

What is Android's file system?

Most answers here are pretty old.

In the past when un managed nand was the most popular storage technology, yaffs2 was the most common file system. This days there are few devices using un-managed nand, and those still in use are slowly migrating to ubifs.

Today most common storage is emmc (managed nand), for such devices ext4 is far more popular, but, this file system is slowly clears its way for f2fs (flash friendly fs).

Edit: f2fs will probably won't make it as the common fs for flash devices (including android)

Spark DataFrame groupBy and sort in the descending order (pyspark)

In PySpark 1.3 sort method doesn't take ascending parameter. You can use desc method instead:

from pyspark.sql.functions import col

    .filter("`count` >= 10")

or desc function:

from pyspark.sql.functions import desc

    .filter("`count` >= 10")

Both methods can be used with with Spark >= 1.3 (including Spark 2.x).

LINQ-to-SQL vs stored procedures?

For basic data retrieval I would be going for Linq without hesitation.

Since moving to Linq I've found the following advantages:

  1. Debugging my DAL has never been easier.
  2. Compile time safety when your schema changes is priceless.
  3. Deployment is easier because everything is compiled into DLL's. No more managing deployment scripts.
  4. Because Linq can support querying anything that implements the IQueryable interface, you will be able to use the same syntax to query XML, Objects and any other datasource without having to learn a new syntax

How to change the buttons text using javascript

If the HTMLElement is input[type='button'], input[type='submit'], etc.

<input id="ShowButton" type="button" value="Show">
<input id="ShowButton" type="submit" value="Show">

change it using this code:

document.querySelector('#ShowButton').value = 'Hide';

If, the HTMLElement is button[type='button'], button[type='submit'], etc:

<button id="ShowButton" type="button">Show</button>
<button id="ShowButton" type="submit">Show</button>

change it using any of these methods,

document.querySelector('#ShowButton').innerHTML = 'Hide';
document.querySelector('#ShowButton').innerText = 'Hide';
document.querySelector('#ShowButton').textContent = 'Hide';

Please note that

  • input is an empty tag and cannot have innerHTML, innerText or textContent
  • button is a container tag and can have innerHTML, innerText or textContent

Ignore this answer if you ain't using, and rad-grid

You must use value instead of innerHTML.

Try this.

document.getElementById("ShowButton").value= "Hide Filter";

And since you are running the button at server the ID may get mangled in the framework. I so, try

document.getElementById('<%=ShowButton.ClientID %>').value= "Hide Filter";

Another better way to do this is like this.

On markup, change your onclick attribute like this. onclick="showFilterItem(this)"

Now use it like this

function showFilterItem(objButton) {
    if (filterstatus == 0) {
        filterstatus = 1;
        $find('<%=FileAdminRadGrid.ClientID %>').get_masterTableView().showFilterItem();
        objButton.value = "Hide Filter";
    else {
        filterstatus = 0;
        $find('<%=FileAdminRadGrid.ClientID %>').get_masterTableView().hideFilterItem();
        objButton.value = "Show filter";

Vertical divider doesn't work in Bootstrap 3

I find using the pipe character with some top and bottom padding works well. Using a div with a border will require more CSS to vertically align it and get the horizontal spacing even with the other elements.


.divider-vertical {
    padding-top: 14px;
    padding-bottom: 14px;


<ul class="nav navbar-nav">
    <li class="active"><a href="#">Home</a></li>
    <li class="divider-vertical">&#124;</li>
    <li><a href="#">Faq</a></li>
    <li class="divider-vertical">&#124;</li>
    <li><a href="#">News</a></li>
    <li class="divider-vertical">&#124;</li>
    <li><a href="#">Contact</a></li>

When to use virtual destructors?

Virtual destructors are useful when you might potentially delete an instance of a derived class through a pointer to base class:

class Base 
    // some virtual methods

class Derived : public Base
        // Do some important cleanup

Here, you'll notice that I didn't declare Base's destructor to be virtual. Now, let's have a look at the following snippet:

Base *b = new Derived();
// use b
delete b; // Here's the problem!

Since Base's destructor is not virtual and b is a Base* pointing to a Derived object, delete b has undefined behaviour:

[In delete b], if the static type of the object to be deleted is different from its dynamic type, the static type shall be a base class of the dynamic type of the object to be deleted and the static type shall have a virtual destructor or the behavior is undefined.

In most implementations, the call to the destructor will be resolved like any non-virtual code, meaning that the destructor of the base class will be called but not the one of the derived class, resulting in a resources leak.

To sum up, always make base classes' destructors virtual when they're meant to be manipulated polymorphically.

If you want to prevent the deletion of an instance through a base class pointer, you can make the base class destructor protected and nonvirtual; by doing so, the compiler won't let you call delete on a base class pointer.

You can learn more about virtuality and virtual base class destructor in this article from Herb Sutter.

Eclipse - java.lang.ClassNotFoundException

Run project as Maven test, then Run as JUnit Test.

Finding elements not in a list

You are reassigning item to the values in z as you iterate through z. So the first time in your for loop, item = 0, next item = 1, etc... You are never checking one list against the other.

To do it very explicitly:

>>> item = [0,1,2,3,4,5,6,7,8,9]
>>> z = [0,1,2,3,4,5,6,7]
>>> for elem in item:
...   if elem not in z:
...     print elem

Explode string by one or more spaces or tabs

The author asked for explode, to you can use explode like this

$resultArray = explode("\t", $inputString);

Note: you must used double quote, not single.

how to import csv data into django models

Use the Pandas library to create a dataframe of the csv data.
Name the fields either by including them in the csv file's first line or in code by using the dataframe's columns method.
Then create a list of model instances.
Finally use the django method .bulk_create() to send your list of model instances to the database table.

The read_csv function in pandas is great for reading csv files and gives you lots of parameters to skip lines, omit fields, etc.

import pandas as pd

#ensure fields are named~ID,Product_ID,Name,Ratio,Description
#concatenate name and Product_id to make a new field a la Dr.Dee's answer
products = [
        name = tmp_data.ix[row]['Name'] 
        description = tmp_data.ix[row]['Description'],
        price = tmp_data.ix[row]['price'],
    for row in tmp_data['ID']

I was using the answer by mmrs151 but saving each row (instance) was very slow and any fields containing the delimiting character (even inside of quotes) were not handled by the open() -- line.split(';') method.

Pandas has so many useful caveats, it is worth getting to know

What is the difference between 'SAME' and 'VALID' padding in tf.nn.max_pool of tensorflow?

When stride is 1 (more typical with convolution than pooling), we can think of the following distinction:

  • "SAME": output size is the same as input size. This requires the filter window to slip outside input map, hence the need to pad.
  • "VALID": Filter window stays at valid position inside input map, so output size shrinks by filter_size - 1. No padding occurs.

Adding a regression line on a ggplot

If you want to fit other type of models, like a dose-response curve using logistic models you would also need to create more data points with the function predict if you want to have a smoother regression line:

fit: your fit of a logistic regression curve

#Create a range of doses:
mm <- data.frame(DOSE = seq(0, max(data$DOSE), length.out = 100))
#Create a new data frame for ggplot using predict and your range of new 
fit.ggplot=data.frame(y=predict(fit, newdata=mm),x=mm$DOSE)


Run Stored Procedure in SQL Developer?

Using SQL Developer Version Build 15.21 the following works:

var InParam1 varchar2(100)
var InParam2 varchar2(100)
var InParam3 varchar2(100)
var OutParam1 varchar2(100)

    /* Assign values to IN parameters */
    :InParam1 := 'one';
    :InParam2 := 'two';
    :InParam3 := 'three';

    /* Call procedure within package, identifying schema if necessary */
    schema.package.procedure(:InParam1, :InParam2, :InParam3, :OutParam1);
    dbms_output.put_line('OutParam1: ' || :OutParam1);

How to capitalize the first letter of text in a TextView in an Android Application

Following does not apply to TextView, but works with EditText; even then, it applies to the text entered from the keyboard, not the text loaded with setText(). To be more specific, it turns the Caps on in the keyboard, and the user can override this at her will.




This will CAP the first letter.


compile 'org.apache.commons:commons-lang3:3.4' //in build.gradle module(app)


setTimeout in for-loop does not print consecutive values

You could use bind method

for (var i = 1, j = 1; i <= 3; i++, j++) {
    setTimeout(function() {
    }.bind(i), j * 100);

Jenkins - how to build a specific branch

Best solution can be:

Add a string parameter in the existing job enter image description here

Then in the Source Code Management section update Branches to build to use the string parameter you defined enter image description here

If you see a checkbox labeled Lightweight checkout, make sure it is unchecked.

The configuration indicated in the images will tell the jenkins job to use master as the default branch, and for manual builds it will ask you to enter branch details (FYI: by default it's set to master)enter image description here

Which mime type should I use for mp3

The standard way is to use audio/mpeg which is something like this in your PHP header function ...

header('Content-Type: audio/mpeg');

Get button click inside UITableViewCell

If you want to pass parameter value from cell to UIViewController using closure then

//Your Cell Class
class TheCell: UITableViewCell {

    var callBackBlockWithParam: ((String) -> ()) = {_ in }

//Your Action on button
    @IBAction func didTap(_ sender: Any) {
        callBackBlockWithParam("Your Required Parameter like you can send button as sender or anything just change parameter type. Here I am passing string")

//Your Controller
extension TheController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: TheCell.identifier, for: indexPath) as! TheCell {
            cell.callBackBlockWithParam = { (passedParamter) in 

             //you will get string value from cell class
            return cell

configure Git to accept a particular self-signed server certificate for a particular https remote

On windows in a corporate environment where certificates are distributed from a single source, I found this answer solved the issue:

Express-js wildcard routing to cover everything under and including a path

The connect router has now been removed (, the author stating that you should use a framework on top of connect (like Express) for routing.

Express currently treats app.get("/foo*") as app.get(/\/foo(.*)/), removing the need for two separate routes. This is in contrast to the previous answer (referring to the now removed connect router) which stated that "* in a path is replaced with .+".

Update: Express now uses the "path-to-regexp" module (since Express 4.0.0) which maintains the same behavior in the version currently referenced. It's unclear to me whether the latest version of that module keeps the behavior, but for now this answer stands.

How can I open a link in a new window?

I just found an interesting solution to this issue. I was creating spans which contain information based on the return from a web service. I thought about trying to put a link around the span so that if I clicked on it, the "a" would capture the click.

But I was trying to capture the click with the span... so I thought why not do this when I created the span.

var span = $('<span id="something" data-href="'+url+'" />');

I then bound a click handler to the span which created a link based on the 'data-href' attribute: {
    var href = $(this).attr('data-href');
    var link = $('<a href="http://' + href + '" />');
    link.attr('target', '_blank');'href'));

This successfully allowed me to click on a span and open a new window with a proper url.

Disabling vertical scrolling in UIScrollView

Try setting the contentSize's height to the scrollView's height. Then the vertical scroll should be disabled because there would be nothing to scroll vertically.

scrollView.contentSize = CGSizeMake(scrollView.contentSize.width,scrollView.frame.size.height);

Extract XML Value in bash script

XMLStarlet or another XPath engine is the correct tool for this job.

For instance, with data.xml containing the following:

    <title>15:54:57 - George:</title>
    <description>Diane DeConn? You saw Diane DeConn!</description> 
    <title>15:55:17 - Jerry:</title> 
    <description>Something huh?</description>
</root> can extract only the first title with the following:

xmlstarlet sel -t -m '//title[1]' -v . -n <data.xml

Trying to use sed for this job is troublesome. For instance, the regex-based approaches won't work if the title has attributes; won't handle CDATA sections; won't correctly recognize namespace mappings; can't determine whether a portion of the XML documented is commented out; won't unescape attribute references (such as changing Brewster &amp; Jobs to Brewster & Jobs), and so forth.

Pinging an IP address using PHP and echoing the result

For Windows Use this class

$host = '';
$ping = new Ping($host);
$latency = $ping->ping();
if ($latency !== false) {
 print 'Latency is ' . $latency . ' ms';
else {
print 'Host could not be reached.';

Eclipse Generate Javadoc Wizard: what is "Javadoc Command"?

Had this problem and solved typing this : C:\Program Files (x86)\Java\jdk1.7.0_51\bin\javadoc.exe

How to efficiently remove duplicates from an array without using Set

public static int[] removeDuplicates(int[] arr) {

int end = arr.length;

 HashSet<Integer> set = new HashSet<Integer>(end);
    for(int i = 0 ; i < end ; i++){
return set.toArray();

Parsing command-line arguments in C

You can use James Theiler's "opt" package.

And a flattering post with some examples of how it is so much simpler than other approaches is here:

Opt 3.19 review and upgrades

How to get tf.exe (TFS command line client)?

I'm in a virtual machine, and am trying to keep my VHD as small as possible, so I find Team Explorer is a really heavyweight solution (300+ MB install). As an alternative, I've had some luck copying a minimal set of EXEs/DLLs from a Team Explorer installation to a clean machine (.NET 4.0 is still required, of course).

I've only tried a handful of operations so far, but this set of files (about 8.5 MB) has been enough to get basic source-control functionality via tf.exe:

  • TF.exe
  • TF.exe.config
  • Microsoft.TeamFoundation.dll
  • Microsoft.TeamFoundation.Client.dll
  • Microsoft.TeamFoundation.Common.dll
  • Microsoft.TeamFoundation.Common.Library.dll
  • Microsoft.TeamFoundation.VersionControl.Client.dll
  • Microsoft.TeamFoundation.VersionControl.Common.dll
  • Microsoft.TeamFoundation.VersionControl.Controls.dll

(It should go without saying that this is a completely unsupported solution, and it doesn't free you from the normal TFS licensing requirements.)

Depending on the operations you perform, you may find that additional DLLs are required. Fortunately, tf.exe will produce a nice error message telling you exactly which ones are missing.

Does HTTP use UDP?

From RFC 2616:

HTTP communication usually takes place over TCP/IP connections. The default port is TCP 80, but other ports can be used. This does not preclude HTTP from being implemented on top of any other protocol on the Internet, or on other networks. HTTP only presumes a reliable transport; any protocol that provides such guarantees can be used; the mapping of the HTTP/1.1 request and response structures onto the transport data units of the protocol in question is outside the scope of this specification.

So although it doesn't explicitly say so, UDP is not used because it is not a "reliable transport".

EDIT - more recently, the QUIC protocol (which is more strictly a pseudo-transport or a session layer protocol) does use UDP for carrying HTTP/2.0 traffic and much of Google's traffic already uses this protocol. It's currently progressing towards standardisation as HTTP/3.

Formatting code snippets for blogging on Blogger

Here's one site that will format your code and spit out html, and it even includes inline styles for syntax coloring. Might not work for all of your needs, but is a good start. I believe he has made the source available if you want to extend it:

How do I select an entire row which has the largest ID in the table?

One can always go for analytical functions as well which will give you more control

select tmp.row from ( select row, rank() over(partition by id order by id desc ) as rnk from table) tmp where tmp.rnk=1

If you face issue with rank() function depending on the type of data then one can choose from row_number() or dense_rank() too.

changing default x range in histogram matplotlib

plt.hist(hmag, 30, range=[6.5, 12.5], facecolor='gray', align='mid')

Code formatting shortcuts in Android Studio for Operation Systems

For formatting code in Android Studio on Linux you could instead use Ctrl + Alt + Super + L. You could use this and avoid having to change the system shortcut. (Super key is the Windows icon key besides the Alt key).

How to SHUTDOWN Tomcat in Ubuntu?

Try using this command : (this will stop tomcat servlet this really helps)

sudo service tomcat7 stop


sudo tomcat7 restart (if you need a restart)

How to calculate sum of a formula field in crystal Reports?

You can try like this:


It will work without creating a summarize field in formulae.

Ansible: how to get output to display

Every Ansible task when run can save its results into a variable. To do this, you have to specify which variable to save the results into. Do this with the register parameter, independently of the module used.

Once you save the results to a variable you can use it later in any of the subsequent tasks. So for example if you want to get the standard output of a specific task you can write the following:

- hosts: localhost
    - shell: ls
      register: shell_result

    - debug:
        var: shell_result.stdout_lines

Here register tells ansible to save the response of the module into the shell_result variable, and then we use the debug module to print the variable out.

An example run would look like the this:

PLAY [localhost] ***************************************************************

TASK [command] *****************************************************************
changed: [localhost]

TASK [debug] *******************************************************************
ok: [localhost] => {
    "shell_result.stdout_lines": [

Responses can contain multiple fields. stdout_lines is one of the default fields you can expect from a module's response.

Not all fields are available from all modules, for example for a module which doesn't return anything to the standard out you wouldn't expect anything in the stdout or stdout_lines values, however the msg field might be filled in this case. Also there are some modules where you might find something in a non-standard variable, for these you can try to consult the module's documentation for these non-standard return values.

Alternatively you can increase the verbosity level of ansible-playbook. You can choose between different verbosity levels: -v, -vvv and -vvvv. For example when running the playbook with verbosity (-vvv) you get this:

PLAY [localhost] ***************************************************************

TASK [command] *****************************************************************
changed: [localhost] => {
    "changed": true,
    "cmd": "ls",
    "delta": "0:00:00.007621",
    "end": "2017-02-17 23:04:41.912570",
    "invocation": {
        "module_args": {
            "_raw_params": "ls",
            "_uses_shell": true,
            "chdir": null,
            "creates": null,
            "executable": null,
            "removes": null,
            "warn": true
        "module_name": "command"
    "rc": 0,
    "start": "2017-02-17 23:04:41.904949",
    "stderr": "",
    "stdout": "play.retry\nplay.yml",
    "stdout_lines": [
    "warnings": []

As you can see this will print out the response of each of the modules, and all of the fields available. You can see that the stdout_lines is available, and its contents are what we expect.

To answer your main question about the jenkins_script module, if you check its documentation, you can see that it returns the output in the output field, so you might want to try the following:

  - jenkins_script:
      script: (...)
    register: jenkins_result

  - debug:
      var: jenkins_result.output

Alternative to the HTML Bold tag

The answer by @Darryl Hein is correct despite one point - <b> is not recommended at all since XHTML, because it's not semantic.

<strong> means semantically highlighted text

font-weight: bold means visually highlighted text

<strong> can be css-tuned to not be bold, though it's a conventional default. It can be made red, or italic, or underlined (though all these possibilities are not really user-friendly). Use it for phrases / words in text, not because of visual design, but related to their meaning

font-weight: bold should be used for design-related bold parts, like headers, sub-headers, table header cells etc.

What are C++ functors and their uses?

Except for used in callback, C++ functors can also help to provide a Matlab liking access style to a matrix class. There is a example.

how to call a onclick function in <a> tag?

Fun! There are a few things to tease out here:

  • $leadID seems to be a php string. Make sure it gets printed in the right place. Also be aware of all the risks involved in passing your own strings around, like cross-site scripting and SQL injection vulnerabilities. There’s really no excuse for having Internet-facing production code not running on a solid framework.
  • Strings in Javascript (like in PHP and usually HTML) need to be enclosed in " or ' characters. Since you’re already inside both " and ', you’ll want to escape whichever you choose. \' to escape the PHP quotes, or &apos; to escape the HTML quotes.
  • <a /> elements are commonly used for “hyper”links, and almost always with a href attribute to indicate their destination, like this: <a href="">Google homepage</a>.
  • You’re trying to double up on watching when the user clicks. Why? Because a standard click both activates the link (causing the browser to navigate to whatever URL, even that executes Javascript), and “triggers” the onclick event. Tip: Add a return false; to a Javascript event to suppress default behavior.
  • Within Javascript, onclick doesn’t mean anything on its own. That’s because onclick is a property, and not a variable. There has to be a reference to some object, so it knows whose onclick we’re talking about! One such object is window. You could write <a href="javascript:window.onclick = location.reload;">Activate me to reload when anything is clicked</a>.
  • Within HTML, onclick can mean something on its own, as long as its part of an HTML tag: <a href="#" onclick="location.reload(); return false;">. I bet you had this in mind.
  • Big difference between those two kinds of = assignments. The Javascript = expects something that hasn’t been run yet. You can wrap things in a function block to signal code that should be run later, if you want to specify some arguments now (like I didn’t above with reload): <a href="javascript:window.onclick = function () { ... ) };"> ....
  • Did you know you don’t even need to use Javascript to signal the browser to open a link in a new window? There’s a special target attribute for that: <a href="" target="_blank">Google homepage</a>.

Hope those are useful.

Using parameters in batch files at Windows command line

Use variables i.e. the .BAT variables and called %0 to %9

Crop image to specified size and picture location

You would need to do something like this. I am typing this off the top of my head, so this may not be 100% correct.

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef context = CGBitmapContextCreate(NULL, 640, 360, 8, 4 * width, colorSpace, kCGImageAlphaPremultipliedFirst); CGColorSpaceRelease(colorSpace);  CGContextDrawImage(context, CGRectMake(0,-160,640,360), cgImgFromAVCaptureSession);  CGImageRef image = CGBitmapContextCreateImage(context); UIImage* myCroppedImg = [UIImage imageWithCGImage:image]; CGContextRelease(context);       

SQL Server 2008: TOP 10 and distinct together

  FROM MyDatabase
  Where EXISTS 
     Select Distinct[A] FROM MyDatabase

add commas to a number in jQuery

Using toLocaleString ref at

function formatComma(value, sep = 0) {_x000D_
      return Number(value).toLocaleString("ja-JP", { style: "currency", currency: "JPY", minimumFractionDigits: sep });_x000D_
console.log(formatComma(123456789, 2)); // ?123,456,789.00_x000D_
console.log(formatComma(123456789, 0)); // ?123,456,789_x000D_
console.log(formatComma(1234, 0)); // ?1,234

How can I reference a dll in the GAC from Visual Studio?

Registering assmblies into the GAC does not then place a reference to the assembly in the add references dialog. You still need to reference the assembly by path for your project, the main difference being you do not need to use the copy local option, your app will find it at runtime.

In this particular case, you just need to reference your assembly by path (browse) or if you really want to have it in the add reference dialog there is a registry setting where you can add additional paths.

Note, if you ship your app to someone who does not have this assembly installed you will need to ship it, and in this case you really need to use the SharedManagementObjects.msi redistributable.

Sorting list based on values from another list

Shortest Code

[x for _,x in sorted(zip(Y,X))]


X = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
Y = [ 0,   1,   1,    0,   1,   2,   2,   0,   1]

Z = [x for _,x in sorted(zip(Y,X))]
print(Z)  # ["a", "d", "h", "b", "c", "e", "i", "f", "g"]

Generally Speaking

[x for _, x in sorted(zip(Y,X), key=lambda pair: pair[0])]


  1. zip the two lists.
  2. create a new, sorted list based on the zip using sorted().
  3. using a list comprehension extract the first elements of each pair from the sorted, zipped list.

For more information on how to set\use the key parameter as well as the sorted function in general, take a look at this.

ORA-12516, TNS:listener could not find available handler

You opened a lot of connections and that's the issue. I think in your code, you did not close the opened connection.

A database bounce could temporarily solve, but will re-appear when you do consecutive execution. Also, it should be verified the number of concurrent connections to the database. If maximum DB processes parameter has been reached this is a common symptom.

Courtesy of this thread:

Automatically get loop index in foreach loop in Perl

Well, there is this way:

use List::Rubyish;

$list = List::Rubyish->new( [ qw<a b c> ] );
$list->each_index( sub { say "\$_=$_" } );

See List::Rubyish.

Check synchronously if file/directory exists in Node.js

I use below function to test if file exists. It catches also other exceptions. So in case there are rights issues e.g. chmod ugo-rwx filename or in Windows Right Click -> Properties -> Security -> Advanced -> Permission entries: empty list .. function returns exception as it should. The file exists but we don't have rights to access it. It would be wrong to ignore this kinds of exceptions.

function fileExists(path) {

  try  {
    return fs.statSync(path).isFile();
  catch (e) {

    if (e.code == 'ENOENT') { // no such file or directory. File really does not exist
      console.log("File does not exist.");
      return false;

    console.log("Exception fs.statSync (" + path + "): " + e);
    throw e; // something else went wrong, we don't have rights, ...

Exception output, nodejs errors documentation in case file doesn't exist:

  [Error: ENOENT: no such file or directory, stat 'X:\\delsdfsdf.txt']
  errno: -4058,
  code: 'ENOENT',
  syscall: 'stat',
  path: 'X:\\delsdfsdf.txt'

Exception in case we don't have rights to the file, but exists:

  [Error: EPERM: operation not permitted, stat 'X:\file.txt']
  errno: -4048,
  code: 'EPERM',
  syscall: 'stat',
  path: 'X:\\file.txt'

Why am I getting a "401 Unauthorized" error in Maven?

I was dealing with this running Artifactory version 5.8.4. The "Set Me Up" function would generate settings.xml as follows:


After using the mvn deploy -e -X switch, I noticed the credentials were not accurate. I removed the ${security.getCurrentUsername()} and replaced it with my username and removed ${security.getEscapedEncryptedPassword()!""} and just put my encrypted password which worked for me:


Hope this helps!

Javascript: how to validate dates in format MM-DD-YYYY?

DateFormat = DD.MM.YYYY or D.M.YYYY

function dateValidate(val){ 
var dateStr = val.split('.'); 
  var date = new Date(dateStr[2], dateStr[1]-1, dateStr[0]); 
  if(date.getDate() == dateStr[0] && date.getMonth()+1 == dateStr[1] && date.getFullYear() == dateStr[2])
  { return date; }
  else{ return 'NotValid';} 

Regex - Does not contain certain Characters


The caret in the character class ([^) means match anything but, so this means, beginning of string, then one or more of anything except < and >, then the end of the string.

The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead

  1. Why is this happening?

    The entire ext/mysql PHP extension, which provides all functions named with the prefix mysql_, was officially deprecated in PHP v5.5.0 and removed in PHP v7.

    It was originally introduced in PHP v2.0 (November 1997) for MySQL v3.20, and no new features have been added since 2006. Coupled with the lack of new features are difficulties in maintaining such old code amidst complex security vulnerabilities.

    The manual has contained warnings against its use in new code since June 2011.

  2. How can I fix it?

    As the error message suggests, there are two other MySQL extensions that you can consider: MySQLi and PDO_MySQL, either of which can be used instead of ext/mysql. Both have been in PHP core since v5.0, so if you're using a version that is throwing these deprecation errors then you can almost certainly just start using them right away—i.e. without any installation effort.

    They differ slightly, but offer a number of advantages over the old extension including API support for transactions, stored procedures and prepared statements (thereby providing the best way to defeat SQL injection attacks). PHP developer Ulf Wendel has written a thorough comparison of the features. has an excellent tutorial on migrating from ext/mysql to PDO.

  3. I understand that it's possible to suppress deprecation errors by setting error_reporting in php.ini to exclude E_DEPRECATED:

    error_reporting = E_ALL ^ E_DEPRECATED

    What will happen if I do that?

    Yes, it is possible to suppress such error messages and continue using the old ext/mysql extension for the time being. But you really shouldn't do this—this is a final warning from the developers that the extension may not be bundled with future versions of PHP (indeed, as already mentioned, it has been removed from PHP v7). Instead, you should take this opportunity to migrate your application now, before it's too late.

    Note also that this technique will suppress all E_DEPRECATED messages, not just those to do with the ext/mysql extension: therefore you may be unaware of other upcoming changes to PHP that would affect your application code. It is, of course, possible to only suppress errors that arise on the expression at issue by using PHP's error control operator—i.e. prepending the relevant line with @—however this will suppress all errors raised by that expression, not just E_DEPRECATED ones.

What should you do?

  • You are starting a new project.

    There is absolutely no reason to use ext/mysql—choose one of the other, more modern, extensions instead and reap the rewards of the benefits they offer.

  • You have (your own) legacy codebase that currently depends upon ext/mysql.

    It would be wise to perform regression testing: you really shouldn't be changing anything (especially upgrading PHP) until you have identified all of the potential areas of impact, planned around each of them and then thoroughly tested your solution in a staging environment.

    • Following good coding practice, your application was developed in a loosely integrated/modular fashion and the database access methods are all self-contained in one place that can easily be swapped out for one of the new extensions.

      Spend half an hour rewriting this module to use one of the other, more modern, extensions; test thoroughly. You can later introduce further refinements to reap the rewards of the benefits they offer.

    • The database access methods are scattered all over the place and cannot easily be swapped out for one of the new extensions.

      Consider whether you really need to upgrade to PHP v5.5 at this time.

      You should begin planning to replace ext/mysql with one of the other, more modern, extensions in order that you can reap the rewards of the benefits they offer; you might also use it as an opportunity to refactor your database access methods into a more modular structure.

      However, if you have an urgent need to upgrade PHP right away, you might consider suppressing deprecation errors for the time being: but first be sure to identify any other deprecation errors that are also being thrown.

  • You are using a third party project that depends upon ext/mysql.

    Consider whether you really need to upgrade to PHP v5.5 at this time.

    Check whether the developer has released any fixes, workarounds or guidance in relation to this specific issue; or, if not, pressure them to do so by bringing this matter to their attention. If you have an urgent need to upgrade PHP right away, you might consider suppressing deprecation errors for the time being: but first be sure to identify any other deprecation errors that are also being thrown.

    It is absolutely essential to perform regression testing.

Where does the iPhone Simulator store its data?

There is another (faster?) way to find where your app data is without Terminal:

  1. Launch the app in the simulator
  2. Open Activity Monitor
  3. Find the name of your app in the CPU tab
  4. Double-click it and open the "Open Files and Ports"

enter image description here

mysql query result in php variable

Of course there is. Check out mysql_query, and mysql_fetch_row if you use MySQL.
Example from PHP manual:

$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
    echo 'Could not run query: ' . mysql_error();
$row = mysql_fetch_row($result);

echo $row[0]; // 42
echo $row[1]; // the email value

Pure CSS checkbox image replacement

If you are still looking for further more customization,

Check out the following library:


How do I convert an integer to string as part of a PostgreSQL query?

You could do this:

SELECT * FROM table WHERE cast(YOUR_INTEGER_VALUE as varchar) = 'string of numbers'

How to print a dictionary line by line in Python?

A more generalized solution that handles arbitrarily-deeply nested dicts and lists would be:

def dumpclean(obj):
    if isinstance(obj, dict):
        for k, v in obj.items():
            if hasattr(v, '__iter__'):
                print k
                print '%s : %s' % (k, v)
    elif isinstance(obj, list):
        for v in obj:
            if hasattr(v, '__iter__'):
                print v
        print obj

This produces the output:

color : 2
speed : 70
color : 3
speed : 60

I ran into a similar need and developed a more robust function as an exercise for myself. I'm including it here in case it can be of value to another. In running nosetest, I also found it helpful to be able to specify the output stream in the call so that sys.stderr could be used instead.

import sys

def dump(obj, nested_level=0, output=sys.stdout):
    spacing = '   '
    if isinstance(obj, dict):
        print >> output, '%s{' % ((nested_level) * spacing)
        for k, v in obj.items():
            if hasattr(v, '__iter__'):
                print >> output, '%s%s:' % ((nested_level + 1) * spacing, k)
                dump(v, nested_level + 1, output)
                print >> output, '%s%s: %s' % ((nested_level + 1) * spacing, k, v)
        print >> output, '%s}' % (nested_level * spacing)
    elif isinstance(obj, list):
        print >> output, '%s[' % ((nested_level) * spacing)
        for v in obj:
            if hasattr(v, '__iter__'):
                dump(v, nested_level + 1, output)
                print >> output, '%s%s' % ((nested_level + 1) * spacing, v)
        print >> output, '%s]' % ((nested_level) * spacing)
        print >> output, '%s%s' % (nested_level * spacing, obj)

Using this function, the OP's output looks like this:

      color: 2
      speed: 70
      color: 3
      speed: 60

which I personally found to be more useful and descriptive.

Given the slightly less-trivial example of:

{"test": [{1:3}], "test2":[(1,2),(3,4)],"test3": {(1,2):['abc', 'def', 'ghi'],(4,5):'def'}}

The OP's requested solution yields this:

1 : 3
(1, 2)
(4, 5) : def
(1, 2)
(3, 4)

whereas the 'enhanced' version yields this:

         1: 3
      (1, 2):
      (4, 5): def
      (1, 2)
      (3, 4)

I hope this provides some value to the next person looking for this type of functionality.

React Hooks useState() with Object

, do it like this example :

first creat state of the objects:

const [isSelected, setSelection] = useState({ id_1: false }, { id_2: false }, { id_3: false });

then change the value on of them:

// if the id_1 is false make it true or return it false.

onValueChange={() => isSelected.id_1 == false ? setSelection({ ...isSelected, id_1: true }) : setSelection({ ...isSelected, id_1: false })}

React-router v4 this.props.history.push(...) not working

You need to bind handleCustomerClick:

class Customers extends Component {
  constructor() {
    this.handleCustomerClick = this.handleCustomerClick(this)

How to describe table in SQL Server 2008?

You can use keyboard short-cut for Description/ detailed information of Table in SQL Server 2008.

Follow steps:

  1. Write Table Name,
  2. Select it, and press Alt + F1
  3. It will show detailed information/ description of mentioned table as,

    1) Table created date,
    2) Columns Description,
    3) Identity,
    4) Indexes,
    5) Constraints,
    6) References etc. As shown Below [example]:

Alt+F1 Demo

Browser: Identifier X has already been declared

The problem solved when I don't use any declaration like var, let or const

Daemon Threads Explanation

Quoting Chris: "... when your program quits, any daemon threads are killed automatically.". I think that sums it up. You should be careful when you use them as they abruptly terminate when main program executes to completion.

What is an application binary interface (ABI)?

I was also trying to understand ABI and JesperE’s answer was very helpful.

From a very simple perspective, we may try to understand ABI by considering binary compatibility.

KDE wiki defines a library as binary compatible “if a program linked dynamically to a former version of the library continues running with newer versions of the library without the need to recompile.” For more on dynamic linking, refer Static linking vs dynamic linking

Now, let’s try to look at just the most basic aspects needed for a library to be binary compatibility (assuming there are no source code changes to the library):

  1. Same/backward compatible instruction set architecture (processor instructions, register file structure, stack organization, memory access types, along with sizes, layout, and alignment of basic data types the processor can directly access)
  2. Same calling conventions
  3. Same name mangling convention (this might be needed if say a Fortran program needs to call some C++ library function).

Sure, there are many other details but this is mostly what the ABI also covers.

More specifically to answer your question, from the above, we can deduce:

ABI functionality: binary compatibility

existing entities: existing program/libraries/OS

consumer: libraries, OS

Hope this helps!

How to check if spark dataframe is empty?

I had the same question, and I tested 3 main solution :

  1. (df != null) && (df.count > 0)
  2. df.head(1).isEmpty() as @hulin003 suggest
  3. df.rdd.isEmpty() as @Justin Pihony suggest

and of course the 3 works, however in term of perfermance, here is what I found, when executing the these methods on the same DF in my machine, in terme of execution time :

  1. it takes ~9366ms
  2. it takes ~5607ms
  3. it takes ~1921ms

therefore I think that the best solution is df.rdd.isEmpty() as @Justin Pihony suggest

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 23: ordinal not in range(128)

You are encoding to UTF-8, then re-encoding to UTF-8. Python can only do this if it first decodes again to Unicode, but it has to use the default ASCII codec:

>>> u'ñ'
>>> u'ñ'.encode('utf8')
>>> u'ñ'.encode('utf8').encode('utf8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)

Don't keep encoding; leave encoding to UTF-8 to the last possible moment instead. Concatenate Unicode values instead.

You can use str.join() (or, rather, unicode.join()) here to concatenate the three values with dashes in between:

nombre = u'-'.join(fabrica, sector, unidad)
return nombre.encode('utf-8')

but even encoding here might be too early.

Rule of thumb: decode the moment you receive the value (if not Unicode values supplied by an API already), encode only when you have to (if the destination API does not handle Unicode values directly).

Python: get key of index in dictionary

You could do something like this:

i={'foo':'bar', 'baz':'huh?'}
keys=i.keys()  #in python 3, you'll need `list(i.keys())`
print keys[values.index("bar")]  #'foo'

However, any time you change your dictionary, you'll need to update your keys,values because dictionaries are not ordered in versions of Python prior to 3.7. In these versions, any time you insert a new key/value pair, the order you thought you had goes away and is replaced by a new (more or less random) order. Therefore, asking for the index in a dictionary doesn't make sense.

As of Python 3.6, for the CPython implementation of Python, dictionaries remember the order of items inserted. As of Python 3.7+ dictionaries are ordered by order of insertion.

Also note that what you're asking is probably not what you actually want. There is no guarantee that the inverse mapping in a dictionary is unique. In other words, you could have the following dictionary:

d={'i':1, 'j':1}

In that case, it is impossible to know whether you want i or j and in fact no answer here will be able to tell you which ('i' or 'j') will be picked (again, because dictionaries are unordered). What do you want to happen in that situation? You could get a list of acceptable keys ... but I'm guessing your fundamental understanding of dictionaries isn't quite right.

How can I do an UPDATE statement with JOIN in SQL Server?


You'll get the best performance if you forget the where clause and place all conditions in the ON expression.

I think this is because the query first has to join the tables then runs the where clause on that, so if you can reduce what is required to join then that's the fasted way to get the results/do the udpate.



You have a table of users. They can log in using their username or email or account_number. These accounts can be active (1) or inactive (0). This table has 50000 rows

You then have a table of users to disable at one go because you find out they've all done something bad. This table however, has one column with usernames, emails and account numbers mixed. It also has a "has_run" indicator which needs to be set to 1 (true) when it has been run


UPDATE users User
        blacklist_users BlacklistUser
            User.username = BlacklistUser.account_ref
   = BlacklistedUser.account_ref
            User.phone_number = BlacklistUser.account_ref
            User.is_active = 1
            BlacklistUser.has_run = 0
        User.is_active = 0,
        BlacklistUser.has_run = 1;


If we had to join on just the OR conditions it would essentially need to check each row 4 times to see if it should join, and potentially return a lot more rows. However, by giving it more conditions it can "skip" a lot of rows if they don't meet all the conditions when joining.


It's more readable. All the conditions are in one place and the rows to update are in one place

Using ng-if as a switch inside ng-repeat?

Try to surround strings (hoot, story, article) with quotes ':

<div ng-repeat = "data in comments">
    <div ng-if="data.type == 'hoot' ">
        //different template with hoot data
    <div ng-if="data.type == 'story' ">
        //different template with story data
    <div ng-if="data.type == 'article' ">
        //different template with article data