Programs & Examples On #Rest client

REST Client is an open-source HTTP and REST client for Ruby.

How to download excel (.xls) file from API in postman?

You can Just save the response(pdf,doc etc..) by option on the right side of the response in postman check this image postman save response

For more Details check this

how to generate web service out of wsdl

How about using the wsdl /server or wsdl /serverinterface switches? As far as I understand the wsdl.exe command line properties, that's what you're looking for.



Server switch has been deprecated. Please use /serverInterface instead.
Generate an abstract class for an xml web service implementation using
ASP.NET based on the contracts. The default is to generate client proxy

On the other hand: why do you want to create obsolete technology solutions? Why not create this web service as a WCF service. That's the current and more modern, much more flexible way to do this!



When I use wsdl /server on a WSDL file, I get this file created:

public abstract partial class OneCrmServiceType : System.Web.Services.WebService 
    /// <remarks/>
    public abstract void OrderCreated(......);

This is basically almost exactly the same code that gets generated when you add an ASMX file to your solution (in the code behind file - "yourservice.asmx.cs"). I don't think you can get any closer to creating an ASMX file from a WSDL file.

You can always add the "yourservice.asmx" manually - it doesn't really contain much:

<%@ WebService Language="C#" CodeBehind="YourService.asmx.cs" 
      Class="YourServiceNamespace.YourServiceClass" %>

Why do I get a "Null value was assigned to a property of primitive type setter of" error message when using HibernateCriteriaBuilder in Grails

I'll try to make you understand with the help of an example. Suppose you had a relational table (STUDENT) with two columns and ID(int) and NAME(String). Now as ORM you would've made an entity class somewhat like as follows:-

package com.kashyap.default;


import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

 * @author vaibhav.kashyap
@Table(name = "STUDENT")
public class Student implements Serializable {

    private static final long serialVersionUID = -1354919370115428781L;

    @Column(name = "ID")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @Column(name = "NAME")
    private String name;

    public Student(){


    public int getId() {
        return id;

    public void setId(int id) { = id;

    public String getName() {
        return name;

    public void setName(String name) { = name;


Lets assume table already had entries. Now if somebody asks you add another column of "AGE" (int)


You'll have to set default values as NULL to add another column in a pre-filled table. This makes you add another field in the class. Now the question arises whether you'll be using a primitive data type or non primitive wrapper data type for declaring the field.

@Column(name = "AGE")
private int age;


@Column(name = "AGE")
private INTEGER age;

you'll have to declare the field as non primitive wrapper data type because the container will try to map the table with the entity. Hence it wouldn't able to map NULL values (default) if you won't declare field as wrapper & would eventually throw "Null value was assigned to a property of primitive type setter" Exception.

Is there a C++ gdb GUI for Linux?

I used KDbg (only works under KDE).

Run script on mac prompt "Permission denied"

You should run the script as 'superuser', just add 'sudo' in front of the command and type your password when prompted.

So try:

sudo /dvtcolorconvert.rb ~/Themes/ObsidianCode.xccolortheme

If this doesn't work, try adapting the permissions:

sudo chmod 755 /dvtcolorconvert.rb
sudo chmod 755 ~/Themes/ObsidianCode.xccolortheme

Creating a timer in python

mins = minutes + 1

should be

minutes = minutes + 1


minutes = 0

needs to be outside of the while loop.

How do you easily horizontally center a <div> using CSS?

Add this class to your css file it will work perfectly steps to do:

1) create this first

<div class="center-role-form">
  <!--your div (contrent) place here-->

2) add this to your css

.center-role-form {
    width: fit-content;
    text-align: center;
    margin: 1em auto;
    display: table;

Using both Python 2.x and Python 3.x in IPython Notebook

From my Linux installation I did:

sudo ipython2 kernelspec install-self

And now my python 2 is back on the list.



The method above is now deprecated and will be dropped in the future. The new method should be:

sudo ipython2 kernel install

When and how should I use a ThreadLocal variable?

There is very good example in book Java Concurrency in Practice. Where author (Joshua Bloch) explains how Thread confinement is one of the simplest ways to achieve thread safety and ThreadLocal is more formal means of maintaining thread confinement. In the end he also explain how people can abuse it by using it as global variables.

I have copied the text from the mentioned book but code 3.10 is missing as it is not much important to understand where ThreadLocal should be use.

Thread-local variables are often used to prevent sharing in designs based on mutable Singletons or global variables. For example, a single-threaded application might maintain a global database connection that is initialized at startup to avoid having to pass a Connection to every method. Since JDBC connections may not be thread-safe, a multithreaded application that uses a global connection without additional coordination is not thread-safe either. By using a ThreadLocal to store the JDBC connection, as in ConnectionHolder in Listing 3.10, each thread will have its own connection.

ThreadLocal is widely used in implementing application frameworks. For example, J2EE containers associate a transaction context with an executing thread for the duration of an EJB call. This is easily implemented using a static Thread-Local holding the transaction context: when framework code needs to determine what transaction is currently running, it fetches the transaction context from this ThreadLocal. This is convenient in that it reduces the need to pass execution context information into every method, but couples any code that uses this mechanism to the framework.

It is easy to abuse ThreadLocal by treating its thread confinement property as a license to use global variables or as a means of creating “hidden” method arguments. Like global variables, thread-local variables can detract from reusability and introduce hidden couplings among classes, and should therefore be used with care.

How to convert object array to string array in Java

System.arraycopy is probably the most efficient way, but for aesthetics, I'd prefer:

 Arrays.asList(Object_Array).toArray(new String[Object_Array.length]);

How to automatically close cmd window after batch file execution?

You normally end a batch file with a line that just says exit. If you want to make sure the file has run and the DOS window closes after 2 seconds, you can add the lines:

timeout 2 >nul

But the exit command will not work if your batch file opens another window, because while ever the second window is open the old DOS window will also be displayed.

SOLUTION: For example there's a great little free program called BgInfo which will display all the info about your computer. Assuming it's in a directory called C:\BgInfo, to run it from a batch file with the /popup switch and to close the DOS window while it still runs, use:

start "" "C:\BgInfo\BgInfo.exe" /popup

How to change Android usb connect mode to charge only?

I have been searching for this for ages on my CM 11 android phone, running kitkat.

Well.. finally I found it. It's hidden in a totally unintuitive location:

  1. Go to settings
  2. Go to storage
  3. Open the menu and choose USB computer connection

Here you can choose between Media Device (MTP), Camera (PTP) and Mass storage (UMS). Turn them all off to get it to charge only.

Sadly, if the option is not there, it is not supported by the phone. This seems to be the case for my HTC One (M7).

What does `ValueError: cannot reindex from a duplicate axis` mean?

This can also be a cause for this[:) I solved my problem like this]

It may happen even if you are trying to insert a dataframe type column inside dataframe

you can try this


Google Android USB Driver and ADB

You need to modify 3 things in order to make Google USB driver work for any android phone on any Windows:

  1. Add your device's ID to android_winusb.inf file
  2. Digitally sign the modified driver
  3. Add your device's vendor ID to adb_usb.ini whitelist (no longer required)

and here are the details:

1. Add your device's ID to android_winusb.inf file

the format to add is:

;Comment usually the device name
%SingleAdbInterface% = USB_Install, USB\; here you put VID and PID
%CompositeAdbInterface% = USB_Install, USB\; same as above but add the MI

before I go on, VID is the USB Vendor ID.

How to get the vid and pid : they are in drivers you are merging; but if you don’t have a driver for the device you can get it by opening device manager; then right-click the device – select properties-in new dialog go to Details tab >in property drop menu select hardware ids. for example you see something like:



take this value for composite adb device and remove MI for single adb device, you get

;MSI WindPad Enjoy 7 plus
%SingleAdbInterface%        = USB_Install, USB\VID_2207&PID_0000
%CompositeAdbInterface%     = USB_Install, USB\VID_2207&PID_0000&REV_0222&MI_01

copy this 2 line TWICE , once to [Google.NTx86] section and another to [Google.NTamd64] section

REPEAT for every device you want to support

Now an optional edit for [Strings] Section: edit

ProviderName                = “Google, Inc.”
SingleAdbInterface          = “Android ADB Interface”
CompositeAdbInterface       = “Android Composite ADB Interface”
SingleBootLoaderInterface   = “Android Bootloader Interface”
WinUSB_SvcDesc              = “Android USB Driver”
DISK_NAME                   = “Android WinUsb installation disk”
ClassName                   = “Android Device”


ProviderName                = “Google, Inc.”
SingleAdbInterface          = “MSI ADB Interface”
CompositeAdbInterface       = “MSI Composite ADB Interface”
SingleBootLoaderInterface   = “MSI Bootloader Interface”
WinUSB_SvcDesc              = “MSI USB Driver”
DISK_NAME                   = “MSI WinUsb installation disk”
ClassName                   = “MSI Tablet”

2. Digitally sign the modified driver:

Although the original google usb driver was signed by google , modifying android_winusb.inf will prevent installing it on windows 8 showning an error message hasherror

The hash file is not present in the specified catalog file. The file is likely
corrupt    or the    victim of tampering.

This is only in Windows 8. Windows 7 or earlier do not show this error message. You have to regenerate catalog file (probably with Windows SDK) and sign

Workaround: A workaround for internal tesing is to diable windows signature verification : either temporarily or permanently:


Go to left upper or lower corner of screen to open charms bar and click settings charm.

choose Change PC settings

choose General

Scroll down, and click ‘Restart now’ under ‘Advanced startup’.

Click ‘Troubleshoot’. Click ‘Advanced Options’ Click ‘Windows Startup Settings’ Click Restart.


run cmd and type:

shutdown -o -r -t 0

then after restarting choose ‘Disable driver signature enforcement‘ from the list . install your driver before restarting.


press Window+Q

search for cmd

right click cmd

choose run as administrator from action bar

type in cmd:

bcdedit -set loadoptions DISABLE_INTEGRITY_CHECKS
bcdedit -set TESTSIGNING ON

3. Add your device's vendor ID to adb_usb.ini whitelist (no longer required):

adb used to have a hard-coded whitelist of supported Vendor IDs. If your device's vendor was not on the list - the adb was ignoring it completely. To make adb recognize such devices users had to manually add their vendor IDs to %USERPROFILE%\.android\adb_usb.ini - one ID per line.

in the command line:

echo 0x2207 >> "%USERPROFILE%\.android\adb_usb.ini"

Fortunately, Google has removed the VendorID filtering in more recent adb versions. So this step is no longer required.

Finally you can test installation by :

adb kill-server
adb start-server
adb devices

and enabling debugging in developer options on android device

This should restart ADB Server and list devices. If driver is working ok, the device should be listed.

How to rotate x-axis tick labels in Pandas barplot

The question is clear but the title is not as precise as it could be. My answer is for those who came looking to change the axis label, as opposed to the tick labels, which is what the accepted answer is about. (The title has now been corrected).

for ax in plt.gcf().axes:
    plt.xlabel(ax.get_xlabel(), rotation=90)

How to stop a setTimeout loop?

Try something like this in case you want to stop the loop from inside the function:

let timer = setInterval(function(){
  // Have some code to do something


You can also wrap this inside a another function, just make sure you have a timer variable and use clearInterval(theTimerVariable) to stop the loop

Installing TensorFlow on Windows (Python 3.6.x)

Follow these steps to install ternsorflow:

(step 1)   conda create -n py35 python=3.5
(step 2)   activate py35
(step 3)   conda create -n tensorflow
(step 4,only for GPU)   pip install --ignore-installed --upgrade

bootstrap.min.js:6 Uncaught Error: Bootstrap dropdown require Popper.js

I had the same error and just wanted to share my solution. In turned out that the minified version of popper had the code in the same line as the comment and so the entire code was commented out. I just pressed enter after the actual comment so the code was on a new line and then it worked fine.

'React' must be in scope when using JSX react/react-in-jsx-scope?

For those who still don't get the accepted solution :


import React from 'react'
import ReactDOM from 'react-dom'

at the top of the file.

Get current directory name (without full path) in a Bash script

You can use the basename utility which deletes any prefix ending in / and the suffix (if present in string) from string, and prints the result on the standard output.

$basename <path-of-directory>

Accessing nested JavaScript objects and arrays by string path

You can use ramda library.

Learning ramda also helps you to work with immutable objects easily.

var obj = {
    b: {
        d: 1000

var lens = R.lensPath('a.b.c.2.d'.split('.'));
var result = R.view(lens, obj);

How to return an array from an AJAX call?

Use JSON to transfer data types (arrays and objects) between client and server.


In JavaScript:


echo json_encode($id_numbers);


id_numbers = JSON.parse(msg);

As Wolfgang mentioned, you can give a fourth parameter to jQuery to automatically decode JSON for you.

id_numbers = new Array();
        id_numbers = msg;

How to place div side by side

CSS3 introduced flexible boxes (aka. flex box) which can also achieve this behavior.

Simply define the width of the first div, and then give the second a flex-grow value of 1 which will allow it to fill the remaining width of the parent.

    display: flex;
    width: 200px;
    flex-grow: 1;
<div class="container">
  <div class="fixed"></div>
  <div class="flex-item"></div>


div {
    color: #fff;
    font-family: Tahoma, Verdana, Segoe, sans-serif;
    padding: 10px;
.container {
.fixed {
    width: 200px;
.flex-item {
    flex-grow: 1;
<div class="container">
    <div class="fixed">Fixed width</div>
    <div class="flex-item">Dynamically sized content</div>

Note that flex boxes are not backwards compatible with old browsers, but is a great option for targeting modern browsers (see also Caniuse and MDN). A great comprehensive guide on how to use flex boxes is available on CSS Tricks.

How to add option to select list in jQuery

Doing it this way has always worked for me, I hope this helps.

var ddl = $("#dropListBuilding");   
for (k = 0; k < buildings.length; k++)
   ddl.append("<option value='" + buildings[k]+ "'>" + buildings[k] + "</option>");

How to add a char/int to an char array in C?

strcat has the declaration:

char *strcat(char *dest, const char *src)

It expects 2 strings. While this compiles:

char str[1024] = "Hello World";
char tmp = '.';

strcat(str, tmp);

It will cause bad memory issues because strcat is looking for a null terminated cstring. You can do this:

char str[1024] = "Hello World";
char tmp[2] = ".";

strcat(str, tmp);

Live example.

If you really want to append a char you will need to make your own function. Something like this:

void append(char* s, char c) {
        int len = strlen(s);
        s[len] = c;
        s[len+1] = '\0';

append(str, tmp)

Of course you may also want to check your string size etc to make it memory safe.

How do I use arrays in C++?

Programmers often confuse multidimensional arrays with arrays of pointers.

Multidimensional arrays

Most programmers are familiar with named multidimensional arrays, but many are unaware of the fact that multidimensional array can also be created anonymously. Multidimensional arrays are often referred to as "arrays of arrays" or "true multidimensional arrays".

Named multidimensional arrays

When using named multidimensional arrays, all dimensions must be known at compile time:

int H = read_int();
int W = read_int();

int connect_four[6][7];   // okay

int connect_four[H][7];   // ISO C++ forbids variable length array
int connect_four[6][W];   // ISO C++ forbids variable length array
int connect_four[H][W];   // ISO C++ forbids variable length array

This is how a named multidimensional array looks like in memory:

connect_four: |   |   |   |   |   |   |   |
              |   |   |   |   |   |   |   |
              |   |   |   |   |   |   |   |
              |   |   |   |   |   |   |   |
              |   |   |   |   |   |   |   |
              |   |   |   |   |   |   |   |

Note that 2D grids such as the above are merely helpful visualizations. From the point of view of C++, memory is a "flat" sequence of bytes. The elements of a multidimensional array are stored in row-major order. That is, connect_four[0][6] and connect_four[1][0] are neighbors in memory. In fact, connect_four[0][7] and connect_four[1][0] denote the same element! This means that you can take multi-dimensional arrays and treat them as large, one-dimensional arrays:

int* p = &connect_four[0][0];
int* q = p + 42;
some_int_sequence_algorithm(p, q);

Anonymous multidimensional arrays

With anonymous multidimensional arrays, all dimensions except the first must be known at compile time:

int (*p)[7] = new int[6][7];   // okay
int (*p)[7] = new int[H][7];   // okay

int (*p)[W] = new int[6][W];   // ISO C++ forbids variable length array
int (*p)[W] = new int[H][W];   // ISO C++ forbids variable length array

This is how an anonymous multidimensional array looks like in memory:

        +---> |   |   |   |   |   |   |   |
        |     +---+---+---+---+---+---+---+
        |     |   |   |   |   |   |   |   |
        |     +---+---+---+---+---+---+---+
        |     |   |   |   |   |   |   |   |
        |     +---+---+---+---+---+---+---+
        |     |   |   |   |   |   |   |   |
        |     +---+---+---+---+---+---+---+
        |     |   |   |   |   |   |   |   |
        |     +---+---+---+---+---+---+---+
        |     |   |   |   |   |   |   |   |
        |     +---+---+---+---+---+---+---+
   p: | | |

Note that the array itself is still allocated as a single block in memory.

Arrays of pointers

You can overcome the restriction of fixed width by introducing another level of indirection.

Named arrays of pointers

Here is a named array of five pointers which are initialized with anonymous arrays of different lengths:

int* triangle[5];
for (int i = 0; i < 5; ++i)
    triangle[i] = new int[5 - i];

// ...

for (int i = 0; i < 5; ++i)
    delete[] triangle[i];

And here is how it looks like in memory:

          |   |   |   |   |   |
            | +---+---+---+---+
            | |   |   |   |   |
            | +---+---+---+---+
            |   ^
            |   | +---+---+---+
            |   | |   |   |   |
            |   | +---+---+---+
            |   |   ^
            |   |   | +---+---+
            |   |   | |   |   |
            |   |   | +---+---+
            |   |   |   ^
            |   |   |   | +---+
            |   |   |   | |   |
            |   |   |   | +---+
            |   |   |   |   ^
            |   |   |   |   |
            |   |   |   |   |
triangle: | | | | | | | | | | |

Since each line is allocated individually now, viewing 2D arrays as 1D arrays does not work anymore.

Anonymous arrays of pointers

Here is an anonymous array of 5 (or any other number of) pointers which are initialized with anonymous arrays of different lengths:

int n = calculate_five();   // or any other number
int** p = new int*[n];
for (int i = 0; i < n; ++i)
    p[i] = new int[n - i];

// ...

for (int i = 0; i < n; ++i)
    delete[] p[i];
delete[] p;   // note the extra delete[] !

And here is how it looks like in memory:

          |   |   |   |   |   |
            | +---+---+---+---+
            | |   |   |   |   |
            | +---+---+---+---+
            |   ^
            |   | +---+---+---+
            |   | |   |   |   |
            |   | +---+---+---+
            |   |   ^
            |   |   | +---+---+
            |   |   | |   |   |
            |   |   | +---+---+
            |   |   |   ^
            |   |   |   | +---+
            |   |   |   | |   |
            |   |   |   | +---+
            |   |   |   |   ^
            |   |   |   |   |
            |   |   |   |   |
          | | | | | | | | | | |
       p: | | |


Array-to-pointer decay naturally extends to arrays of arrays and arrays of pointers:

int array_of_arrays[6][7];
int (*pointer_to_array)[7] = array_of_arrays;

int* array_of_pointers[6];
int** pointer_to_pointer = array_of_pointers;

However, there is no implicit conversion from T[h][w] to T**. If such an implicit conversion did exist, the result would be a pointer to the first element of an array of h pointers to T (each pointing to the first element of a line in the original 2D array), but that pointer array does not exist anywhere in memory yet. If you want such a conversion, you must create and fill the required pointer array manually:

int connect_four[6][7];

int** p = new int*[6];
for (int i = 0; i < 6; ++i)
    p[i] = connect_four[i];

// ...

delete[] p;

Note that this generates a view of the original multidimensional array. If you need a copy instead, you must create extra arrays and copy the data yourself:

int connect_four[6][7];

int** p = new int*[6];
for (int i = 0; i < 6; ++i)
    p[i] = new int[7];
    std::copy(connect_four[i], connect_four[i + 1], p[i]);

// ...

for (int i = 0; i < 6; ++i)
    delete[] p[i];
delete[] p;

Response.Redirect with POST instead of Get?

In PHP, you can send POST data with cURL. Is there something comparable for .NET?

Yes, HttpWebRequest, see my post below.

Create PDF from a list of images

The best answer already exists !!! I am just improving the answer a little bit. Here's the code :

from fpdf import FPDF
pdf = FPDF()
# imagelist is the list with all image filenames you can create using os module by iterating all the files in a folder or by specifying their name
for image in imagelist:
    pdf.image(image,x=0,y=0,w=210,h=297) # for A4 size because some people said that every other page is blank
pdf.output("yourfile.pdf", "F")

You'll need to install FPDF for this purpose.

pip install FPDF

How do I get the path of the assembly the code is in?

All of the proposed answers work when the developer can change the code to include the required snippet, but if you wanted to do this without changing any code you could use Process Explorer.

It will list all executing dlls on the system, you may need to determine the process id of your running application, but that is usually not too difficult.

I've written a full description of how do this for a dll inside II -

Hash String via SHA-256 in Java

When using hashcodes with any jce provider you first try to get an instance of the algorithm, then update it with the data you want to be hashed and when you are finished you call digest to get the hash value.

MessageDigest sha = MessageDigest.getInstance("SHA-256");
byte[] digest = sha.digest();

you can use the digest to get a base64 or hex encoded version according to your needs

How to show the Project Explorer window in Eclipse

I had encountered the same problem as well. The following solution helped me to get over it:

Window -> Show View -> Package Explorer.

You can use the shortcut as well. It's Alt + Shift + Q, P

NullPointerException in eclipse in Eclipse itself at PartServiceImpl.internalFixContext

I faced the same error, but only with files cloned from git that were assigned to a proprietary plugin. I realized that even after cloning the files from git, I needed to create a new project or import a project in eclipse and this resolved the error.

TypeError: unhashable type: 'numpy.ndarray'

numpy.ndarray can contain any type of element, e.g. int, float, string etc. Check the type an do a conversion if neccessary.

How to extract extension from filename string in Javascript?

Better to use the following; Works always!

var ext =  fileName.split('.').pop();

This will return the extension without a dot prefix. You can add "." + ext to check against the extensions you wish to support!

Using media breakpoints in Bootstrap 4-alpha

Bootstrap has a way of using media queries to define the different task for different sites. It uses four breakpoints.

we have extra small screen sizes which are less than 576 pixels that small in which I mean it's size from 576 to 768 pixels.

medium screen sizes take up screen size from 768 pixels up to 992 pixels large screen size from 992 pixels up to 1200 pixels.

E.g Small Text

This means that at the small screen between 576px and 768px, center the text For medium screen, change "sm" to "md" and same goes to large "lg"

How to enable file upload on React's Material UI simple input?

Here's an example using an IconButton to capture input (photo/video capture) using v3.9.2:

import React, { Component, Fragment } from 'react';
import PropTypes from 'prop-types';

import { withStyles } from '@material-ui/core/styles';
import IconButton from '@material-ui/core/IconButton';
import PhotoCamera from '@material-ui/icons/PhotoCamera';
import Videocam from '@material-ui/icons/Videocam';

const styles = (theme) => ({
    input: {
        display: 'none'

class MediaCapture extends Component {
    static propTypes = {
        classes: PropTypes.object.isRequired

    state: {
        images: [],
        videos: []

    handleCapture = ({ target }) => {
        const fileReader = new FileReader();
        const name = target.accept.includes('image') ? 'images' : 'videos';

        fileReader.onload = (e) => {
            this.setState((prevState) => ({
                [name]: [...prevState[name],]

    render() {
        const { classes } = this.props;

        return (
                <label htmlFor="icon-button-photo">
                    <IconButton color="primary" component="span">
                        <PhotoCamera />

                <label htmlFor="icon-button-video">
                    <IconButton color="primary" component="span">
                        <Videocam />

export default withStyles(styles, { withTheme: true })(MediaCapture);

How to Fill an array from user input C#?

readline is for string.. just use read

Renaming a directory in C#

You should move it:

Directory.Move(source, destination);

How to convert an image to base64 encoding?

I think that it should be:

$path = 'myfolder/myimage.png';
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);

How do you run JavaScript script through the Terminal?

It is crude, but you can open up the Javascript console in Chrome (Ctrl+Shift+J) and paste the text contents of the *.js file and hit Enter.

How to get Enum Value from index in Java?

I recently had the same problem and used the solution provided by Harry Joy. That solution only works with with zero-based enumaration though. I also wouldn't consider it save as it doesn't deal with indexes that are out of range.

The solution I ended up using might not be as simple but it's completely save and won't hurt the performance of your code even with big enums:

public enum Example {

    UNKNOWN(0, "unknown"), ENUM1(1, "enum1"), ENUM2(2, "enum2"), ENUM3(3, "enum3");

    private static HashMap<Integer, Example> enumById = new HashMap<>();
    static { -> enumById.put(e.getId(), e));

    public static Example getById(int id) {
        return enumById.getOrDefault(id, UNKNOWN);

    private int id;
    private String description;

    private Example(int id, String description) { = id;
        this.description= description;

    public String getDescription() {
        return description;

    public int getId() {
        return id;

If you are sure that you will never be out of range with your index and you don't want to use UNKNOWN like I did above you can of course also do:

public static Example getById(int id) {
        return enumById.get(id);

What is the reason for a red exclamation mark next to my project in Eclipse?

i was having the same problem....the actual issue was missing .jar file which took palce coz of changing my workspace. i just deleted the appcompat folder(which has the".jar" file) from my new workspace and copied it from my old workspace. this solved my problem.

Java Can't connect to X11 window server using 'localhost:10.0' as the value of the DISPLAY variable

For Ubuntu 17.10 Install X virtual frame buffer (xvfb)

apt install xvfb

And added these lines to the /etc/profile file...

# Start the X virtual frame buffer (Xvfb)
if [ -f /usr/X11R6/bin/Xvfb ]; then
/usr/X11R6/bin/Xvfb :1 -screen 0 1366x768x32

# Set the DISPLAY variable for the X virtual frame buffer (Xvfb)
export DISPLAY=localhost:1.0

Angular js init ng-model from default values

If you like Kevin Stone's approach above consider an easier approach by writing directives for specific tags such as 'input'.

app.directive('input', function ($parse) {
    return {
        restrict: 'E',
        require: '?ngModel',
        link: function (scope, element, attrs) {
            if (attrs.ngModel) {
                val = attrs.value || element.text();
                $parse(attrs.ngModel).assign(scope, val);
    }; });

If you go this route you won't have to worry about adding ng-initial to every tag. It automatically sets the value of the model to the tag's value attribute. If you do not set the value attribute it will default to an empty string.

Limit the length of a string with AngularJS

If you have two bindings {{}} and {{}}.

And want to show the data as a directory followed by the name, assuming '/root' as the directory and 'Machine' as the name (/root-machine).

{{[]+[isLast ? '': '/'] + []  | limitTo:5}}

Refresh a page using PHP

You sure can refresh a page periodically using PHP:

    header("refresh: 3;");

This will refresh the page every three seconds.

TypeError: argument of type 'NoneType' is not iterable

The python error says that wordInput is not an iterable -> it is of NoneType.

If you print wordInput before the offending line, you will see that wordInput is None.

Since wordInput is None, that means that the argument passed to the function is also None. In this case word. You assign the result of pickEasy to word.

The problem is that your pickEasy function does not return anything. In Python, a method that didn't return anything returns a NoneType.

I think you wanted to return a word, so this will suffice:

def pickEasy():
    word = random.choice(easyWords)
    word = str(word)
    for i in range(1, len(word) + 1):
    return word

What does the "assert" keyword do?

It ensures that the expression returns true. Otherwise, it throws a java.lang.AssertionError.

Format Date time in AngularJS

Inside a controller the format can be filtered by injecting $filter.

var date = $filter('date')(new Date(),'MMM dd, yyyy');

How to convert float to int with Java

If you want to convert a float value into an integer value, you have several ways to do it that depends on how do you want to round the float value.

First way is floor rounding the float value:

float myFloat = 3.14f;
int myInteger = (int)myFloat;

The output of this code will be 3, even if the myFloat value is closer to 4.

The second way is ceil rounding the float value:

float myFloat = 3.14f;
int myInteger = Math.ceil(myFloat);

The output of this code will be 4, because the rounding mode is always looking for the highest value.

Why can't I have abstract static methods in C#?

The abstract methods are implicitly virtual. Abstract methods require an instance, but static methods do not have an instance. So, you can have a static method in an abstract class, it just cannot be static abstract (or abstract static).

How to compare two object variables in EL expression language?

In Expression Language you can just use the == or eq operator to compare object values. Behind the scenes they will actually use the Object#equals(). This way is done so, because until with the current EL 2.1 version you cannot invoke methods with other signatures than standard getter (and setter) methods (in the upcoming EL 2.2 it would be possible).

So the particular line

<c:when test="${lang}.equals(${pageLang})">

should be written as (note that the whole expression is inside the { and })

<c:when test="${lang == pageLang}">

or, equivalently

<c:when test="${lang eq pageLang}">

Both are behind the scenes roughly interpreted as


If you want to compare constant String values, then you need to quote it

<c:when test="${lang == 'en'}">

or, equivalently

<c:when test="${lang eq 'en'}">

which is behind the scenes roughly interpreted as


generate random string for div id

I would suggest that you start with some sort of placeholder, you may have this already, but its somewhere to append the div.

<div id="placeholder"></div>

Now, the idea is to dynamically create a new div, with your random id:

var rndId = randomString(8); 
var div = document.createElement('div'); = rndId
div.innerHTML = "Whatever you want the content of your div to be";

this can be apended to your placeholder as follows:


You can then use that in your jwplayer code:


Live example:

Sidenote: Im pretty sure id's must start with an alpha character (ie, no numbers) - you might want to change your implementation of randomstring to enforce this rule. (ref)

Programmatically trigger "select file" dialog box

Just for the record, there is an alternative solution that does not require javascript. It is a bit of a hack, exploiting the fact that clicking on a label sets the focus on the associated input.

You need a <label> with a proper for attribute (points to the input), optionnaly styled like a button (with bootstrap, use btn btn-default). When the user clicks the label, the dialog opens, example :

<!-- optionnal, to add a bit of style -->_x000D_
<link href="" rel="stylesheet"/>_x000D_
<!-- minimal setup -->_x000D_
<label for="exampleInput" class="btn btn-default">_x000D_
  Click me_x000D_
<input type="file" id="exampleInput" style="display: none" />

How to convert a hex string to hex number

Use format string

intNum = 123
print "0x%x"%(intNum)

or hex function.

intNum = 123
print hex(intNum)

Test for non-zero length string in Bash: [ -n "$var" ] or [ "$var" ]

An alternative and perhaps more transparent way of evaluating an empty environment variable is to use...

  if [ "x$ENV_VARIABLE" != "x" ] ; then
      echo 'ENV_VARIABLE contains something'

How to know function return type and argument types?

Yes it is.

In Python a function doesn't always have to return a variable of the same type (although your code will be more readable if your functions do always return the same type). That means that you can't specify a single return type for the function.

In the same way, the parameters don't always have to be the same type too.

535-5.7.8 Username and Password not accepted

First, You need to use a valid Gmail account with your credentials.

Second, In my app I don't use TLS auto, try without this line:

config.action_mailer.smtp_settings = {
  address:              '',
  port:                 587,
  domain:               '',
  user_name:            '[email protected]',
  password:             'YOUR_PASSWORD',
  authentication:       'plain'
  # enable_starttls_auto: true
  # ^ ^ remove this option ^ ^

UPDATE: (See answer below for details) now you need to enable "less secure apps" on your Google Account

Difference between parameter and argument

Argument is often used in the sense of actual argument vs. formal parameter.

The formal parameter is what is given in the function declaration/definition/prototype, while the actual argument is what is passed when calling the function — an instance of a formal parameter, if you will.

That being said, they are often used interchangeably, their exact use depending on different programming languages and their communities. For example, I have also heard actual parameter etc.

So here, x and y would be formal parameters:

int foo(int x, int y) {

Whereas here, in the function call, 5 and z are the actual arguments:

foo(5, z);

Adding elements to a C# array

You can use a generic collection, like List<>

List<string> list = new List<string>();

// add

// remove

How to check variable type at runtime in Go language

The answer by @Darius is the most idiomatic (and probably more performant) method. One limitation is that the type you are checking has to be of type interface{}. If you use a concrete type it will fail.

An alternative way to determine the type of something at run-time, including concrete types, is to use the Go reflect package. Chaining TypeOf(x).Kind() together you can get a reflect.Kind value which is a uint type:

You can then do checks for types outside of a switch block, like so:

import (

// ....

x := 42
y := float32(43.3)
z := "hello"

xt := reflect.TypeOf(x).Kind()
yt := reflect.TypeOf(y).Kind()
zt := reflect.TypeOf(z).Kind()

fmt.Printf("%T: %s\n", xt, xt)
fmt.Printf("%T: %s\n", yt, yt)
fmt.Printf("%T: %s\n", zt, zt)

if xt == reflect.Int {
    println(">> x is int")
if yt == reflect.Float32 {
    println(">> y is float32")
if zt == reflect.String {
    println(">> z is string")

Which prints outs:

reflect.Kind: int
reflect.Kind: float32
reflect.Kind: string
>> x is int
>> y is float32
>> z is string

Again, this is probably not the preferred way to do it, but it's good to know alternative options.

How to wait for a process to terminate to execute another process in batch file

'start /w' does NOT work in all cases. The original solution works great. However, on some machines, it is wise to put a delay immediately after starting the executable. Otherwise, the task name may not appear in the task list yet, and the loop will not work as expected (someone pointed that out). The 2 delays can be combined and put at the top of the loop. Can also get rid of the 'else' just to shorten. Example of 2 programs running sequentially:

timeout /t 1 /nobreak >nul 2>&1
tasklist | find /i "prog1.exe" >nul 2>&1
if errorlevel 1 goto cont1
goto loop1

timeout /t 1 /nobreak >nul 2>&1
tasklist | find /i "prog2.exe" >nul 2>&1
if errorlevel 1 goto cont2
goto loop2

john refling

How to select from subquery using Laravel Query Builder?

The solution of @JarekTkaczyk it is exactly what I was looking for. The only thing I miss is how to do it when you are using DB::table() queries. In this case, this is how I do it:

$other = DB::table( DB::raw("({$sub->toSql()}) as sub") )->select(
    DB::raw('sum( qty ) as qty'), 
$other->mergeBindings( $sub );
print $other->toSql();

Special atention how to make the mergeBindings without using the getQuery() method

What is AndroidX?

AndroidX is the open-source project that the Android team uses to develop, test, package, version and release libraries within Jetpack.

AndroidX is a major improvement to the original Android Support Library. Like the Support Library, AndroidX ships separately from the Android OS and provides backward-compatibility across Android releases. AndroidX fully replaces the Support Library by providing feature parity and new libraries.

AndroidX includes the following features:

  • All packages in AndroidX live in a consistent namespace starting with the string androidx. The Support Library packages have been mapped into the corresponding androidx.* packages. For a full mapping of all the old classes and build artifacts to the new ones, see the Package Refactoring page.

  • Unlike the Support Library, AndroidX packages are separately maintained and updated. The androidx packages use strict Semantic Versioning starting with version 1.0.0. You can update AndroidX libraries in your project independently.

  • All new Support Library development will occur in the AndroidX library. This includes maintenance of the original Support Library artifacts and introduction of new Jetpack components.

Using AndroidX

See Migrating to AndroidX to learn how to migrate an existing project.

If you want to use AndroidX in a new project, you need to set the compile SDK to Android 9.0 (API level 28) or higher and set both of the following Android Gradle plugin flags to true in your file.

  • android.useAndroidX: When set to true, the Android plugin uses the appropriate AndroidX library instead of a Support Library. The flag is false by default if it is not specified.

  • android.enableJetifier: When set to true, the Android plugin automatically migrates existing third-party libraries to use AndroidX by rewriting their binaries. The flag is false by default if it is not specified.

For Artifact mappings see this

PHP Warning Permission denied (13) on session_start()

do a phpinfo(), and look for session.save_path. the directory there needs to have the correct permissions for the user and/or group that your webserver runs as

Use of ~ (tilde) in R programming Language

The thing on the right of <- is a formula object. It is often used to denote a statistical model, where the thing on the left of the ~ is the response and the things on the right of the ~ are the explanatory variables. So in English you'd say something like "Species depends on Sepal Length, Sepal Width, Petal Length and Petal Width".

The myFormula <- part of that line stores the formula in an object called myFormula so you can use it in other parts of your R code.

Other common uses of formula objects in R

The lattice package uses them to specify the variables to plot.
The ggplot2 package uses them to specify panels for plotting.
The dplyr package uses them for non-standard evaulation.

Creating Unicode character from its number

Unfortunatelly, to remove one backlash as mentioned in first comment (newbiedoodle) don't lead to good result. Most (if not all) IDE issues syntax error. The reason is in this, that Java Escaped Unicode format expects syntax "\uXXXX", where XXXX are 4 hexadecimal digits, which are mandatory. Attempts to fold this string from pieces fails. Of course, "\u" is not the same as "\\u". The first syntax means escaped 'u', second means escaped backlash (which is backlash) followed by 'u'. It is strange, that on the Apache pages is presented utility, which doing exactly this behavior. But in reality, it is Escape mimic utility. Apache has some its own utilities (i didn't testet them), which do this work for you. May be, it is still not that, what you want to have. Apache Escape Unicode utilities But this utility 1 have good approach to the solution. With combination described above (MeraNaamJoker). My solution is create this Escaped mimic string and then convert it back to unicode (to avoid real Escaped Unicode restriction). I used it for copying text, so it is possible, that in uencode method will be better to use '\\u' except '\\\\u'. Try it.

   * Converts character to the mimic unicode format i.e. '\\u0020'.
   * This format is the Java source code format.
   *   CharUtils.unicodeEscaped(' ') = "\\u0020"
   *   CharUtils.unicodeEscaped('A') = "\\u0041"
   * @param ch  the character to convert
   * @return is in the mimic of escaped unicode string, 
  public static String unicodeEscaped(char ch) {
    String returnStr;
    //String uniTemplate = "\u0000";
    final static String charEsc = "\\u";

    if (ch < 0x10) {
      returnStr = "000" + Integer.toHexString(ch);
    else if (ch < 0x100) {
      returnStr = "00" + Integer.toHexString(ch);
    else if (ch < 0x1000) {
      returnStr = "0" + Integer.toHexString(ch);
      returnStr = "" + Integer.toHexString(ch);

    return charEsc + returnStr;

   * Converts the string from UTF8 to mimic unicode format i.e. '\\u0020'.
   * notice: i cannot use real unicode format, because this is immediately translated
   * to the character in time of compiling and editor (i.e. netbeans) checking it
   * instead reaal unicode format i.e. '\u0020' i using mimic unicode format '\\u0020'
   * as a string, but it doesn't gives the same results, of course
   * This format is the Java source code format.
   *   CharUtils.unicodeEscaped(' ') = "\\u0020"
   *   CharUtils.unicodeEscaped('A') = "\\u0041"
   * @param String - nationalString in the UTF8 string to convert
   * @return is the string in JAVA unicode mimic escaped
  public String encodeStr(String nationalString) throws UnsupportedEncodingException {
    String convertedString = "";

    for (int i = 0; i < nationalString.length(); i++) {
      Character chs = nationalString.charAt(i);
      convertedString += unicodeEscaped(chs);
    return convertedString;

   * Converts the string from mimic unicode format i.e. '\\u0020' back to UTF8.
   * This format is the Java source code format.
   *   CharUtils.unicodeEscaped(' ') = "\\u0020"
   *   CharUtils.unicodeEscaped('A') = "\\u0041"
   * @param String - nationalString in the JAVA unicode mimic escaped
   * @return is the string in UTF8 string
  public String uencodeStr(String escapedString) throws UnsupportedEncodingException {
    String convertedString = "";

    String[] arrStr = escapedString.split("\\\\u");
    String str, istr;
    for (int i = 1; i < arrStr.length; i++) {
      str = arrStr[i];
      if (!str.isEmpty()) {
        Integer iI = Integer.parseInt(str, 16);
        char[] chaCha = Character.toChars(iI);
        convertedString += String.valueOf(chaCha);
    return convertedString;

Triangle Draw Method

There is not a drawTriangle method neither in Graphics nor Graphics2D. You need to do it by yourself. You can draw three lines using the drawLine method or use one these methods:

These methods work with polygons. You may change the prefix draw to fill when you want to fill the polygon defined by the point set. I inserted the documentation links. Take a look to learn how to use them.

There is the GeneralPath class too. It can be used with Graphics2D, which is capable to draw Shapes. Take a look:

Add regression line equation and R^2 on graph

I changed a few lines of the source of stat_smooth and related functions to make a new function that adds the fit equation and R squared value. This will work on facet plots too!

df = data.frame(x = c(1:100))
df$y = 2 + 5 * df$x + rnorm(100, sd = 40)
df$class = rep(1:2,50)
ggplot(data = df, aes(x = x, y = y, label=y)) +
  stat_smooth_func(geom="text",method="lm",hjust=0,parse=TRUE) +
  geom_smooth(method="lm",se=FALSE) +
  geom_point() + facet_wrap(~class)

enter image description here

I used the code in @Ramnath's answer to format the equation. The stat_smooth_func function isn't very robust, but it shouldn't be hard to play around with it. Try updating ggplot2 if you get an error.

How do I show the value of a #define at compile-time?

You could write a program that prints out BOOST_VERSION and compile and run it as part of your build system. Otherwise, I think you're out of luck.

How are ssl certificates verified?

It's worth noting that in addition to purchasing a certificate (as mentioned above), you can also create your own for free; this is referred to as a "self-signed certificate". The difference between a self-signed certificate and one that's purchased is simple: the purchased one has been signed by a Certificate Authority that your browser already knows about. In other words, your browser can easily validate the authenticity of a purchased certificate.

Unfortunately this has led to a common misconception that self-signed certificates are inherently less secure than those sold by commercial CA's like GoDaddy and Verisign, and that you have to live with browser warnings/exceptions if you use them; this is incorrect.

If you securely distribute a self-signed certificate (or CA cert, as bobince suggested) and install it in the browsers that will use your site, it's just as secure as one that's purchased and is not vulnerable to man-in-the-middle attacks and cert forgery. Obviously this means that it's only feasible if only a few people need secure access to your site (e.g., internal apps, personal blogs, etc.).

How to create a new text file using Python

# Method 1
f = open("Path/To/Your/File.txt", "w")   # 'r' for reading and 'w' for writing
f.write("Hello World from " +    # Write inside file 
f.close()                                # Close file 

# Method 2
with open("Path/To/Your/File.txt", "w") as f:   # Opens file and casts as f 
    f.write("Hello World form " +       # Writing
    # File closed automatically

There are many more methods but these two are most common. Hope this helped!

How do I convert a float to an int in Objective C?

int myInt = (int) myFloat;

Worked fine for me.

int myInt = [[NSNumber numberWithFloat:myFloat] intValue];

Well, that is one option. If you like the detour, I could think of some using NSString. Why easy, when there is a complicated alternative? :)

add/remove active class for ul list with jquery?

this will point to the <ul> selected by .nav-list. You can use delegation instead!

$('.nav-list').on('click', 'li', function() {

SSIS Excel Import Forcing Incorrect Column Type

  1. Click File on the ribbon menu, and then click on Options.
  2. Click Advanced, and then under When calculating this workbook, select the Set precision as displayed check box, and then click OK.

  3. Click OK.

  4. In the worksheet, select the cells that you want to format.

  5. On the Home tab, click the Dialog Box Launcher Button image next to Number.

  6. In the Category box, click Number.

  7. In the Decimal places box, enter the number of decimal places that you want to display.

What is the difference between .yaml and .yml extension?

As @David Heffeman indicates the recommendation is to use .yaml when possible, and the recommendation has been that way since September 2006.

That some projects use .yml is mostly because of ignorance of the implementers/documenters: they wanted to use YAML because of readability, or some other feature not available in other formats, were not familiar with the recommendation and and just implemented what worked, maybe after looking at some other project/library (without questioning whether what was done is correct).

The best way to approach this is to be rigorous when creating new files (i.e. use .yaml) and be permissive when accepting input (i.e. allow .yml when you encounter it), possible automatically upgrading/correcting these errors when possible.

The other recommendation I have is to document the argument(s) why you have to use .yml, when you think you have to. That way you don't look like an ignoramus, and give others the opportunity to understand your reasoning. Of course "everybody else is doing it" and "On Google .yml has more pages than .yaml" are not arguments, they are just statistics about the popularity of project(s) that have it wrong or right (with regards to the extension of YAML files). You can try to prove that some projects are popular, just because they use a .yml extension instead of the correct .yaml, but I think you will be hard pressed to do so.

Some projects realize (too late) that they use the incorrect extension (e.g. originally docker-compose used .yml, but in later versions started to use .yaml, although they still support .yml). Others still seem ignorant about the correct extension, like AppVeyor early 2019, but allow you to specify the configuration file for a project, including extension. This allows you to get the configuration file out of your face as well as giving it the proper extension: I use .appveyor.yaml instead of appveyor.yml for building the windows wheels of my YAML parser for Python).

On the other hand:

The Yaml (sic!) component of Symfony2 implements a selected subset of features defined in the YAML 1.2 version specification.

So it seems fitting that they also use a subset of the recommended extension.

Objective-C - Remove last character from string

In your controller class, create an action method you will hook the button up to in Interface Builder. Inside that method you can trim your string like this:

if ([string length] > 0) {
    string = [string substringToIndex:[string length] - 1];
} else {
    //no characters to delete... attempting to do so will result in a crash

If you want a fancy way of doing this in just one line of code you could write it as:

string = [string substringToIndex:string.length-(string.length>0)];

*Explanation of fancy one-line code snippet:

If there is a character to delete (i.e. the length of the string is greater than 0)
     (string.length>0) returns 1 thus making the code return:
          string = [string substringToIndex:string.length-1];

If there is NOT a character to delete (i.e. the length of the string is NOT greater than 0)
     (string.length>0) returns 0 thus making the code return:
          string = [string substringToIndex:string.length-0];
     Which prevents crashes.

Plot two histograms on single chart with matplotlib

This question has been answered before, but wanted to add another quick/easy workaround that might help other visitors to this question.

import seasborn as sns 

Some helpful examples are here for kde vs histogram comparison.

get current date with 'yyyy-MM-dd' format in Angular 4

Here is the example:

function MethodName($scope)
    $ = new Date();

You can change the format in view here we have a code

<div ng-app ng-controller="MethodName">
    My current date is {{date | date:'yyyy-MM-dd'}} . 

I hope it helps.

How can I force browsers to print background images in CSS?

You have very little control over a browser's printing methods. At most you can SUGGEST, but if the browser's print settings have "don't print background images", there's nothing you can do without rewriting your page to turn the background images into floating "foreground" images that happen to be behind other content.

C non-blocking keyboard input

select() is a bit too low-level for convenience. I suggest you use the ncurses library to put the terminal in cbreak mode and delay mode, then call getch(), which will return ERR if no character is ready:

WINDOW *w = initscr();
nodelay(w, TRUE);

At that point you can call getch without blocking.

How to set limits for axes in ggplot2 R plots?

Quick note: if you're also using coord_flip() to flip the x and the y axis, you won't be able to set range limits using coord_cartesian() because those two functions are exclusive (see here).

Fortunately, this is an easy fix; set your limits within coord_flip() like so:

p + coord_flip(ylim = c(3,5), xlim = c(100, 400))

This just alters the visible range (i.e. doesn't remove data points).

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

There are several ways to check the existence of a column. I would strongly recommend to use INFORMATION_SCHEMA.COLUMNS as it is created in order to communicate with user. Consider following tables:


and even some other access methods available to check system catalog.

Also, no need to use SELECT *, simply test it by NULL value

           SELECT NULL 
             TABLE_NAME = 'myTableName'
             AND COLUMN_NAME = 'myColumnName'

LINQ Inner-Join vs Left-Join

You need to get the joined objects into a set and then apply DefaultIfEmpty as JPunyon said:

Person magnus = new Person { Name = "Hedlund, Magnus" };
Person terry = new Person { Name = "Adams, Terry" };
Person charlotte = new Person { Name = "Weiss, Charlotte" };

Pet barley = new Pet { Name = "Barley", Owner = terry };
List<Person> people = new List<Person> { magnus, terry, charlotte };
List<Pet> pets = new List<Pet>{barley};

var results =
    from person in people
    join pet in pets on person.Name equals pet.Owner.Name into ownedPets
    from ownedPet in ownedPets.DefaultIfEmpty(new Pet())
    orderby person.Name
    select new { OwnerName = person.Name, ownedPet.Name };

foreach (var item in results)
        String.Format("{0,-25} has {1}", item.OwnerName, item.Name ) );


Adams, Terry              has Barley
Hedlund, Magnus           has
Weiss, Charlotte          has

Extension methods must be defined in a non-generic static class

if you do not intend to have static functions just get rid of the "this" keyword in the arguments.

how to get vlc logs?

I found the following command to run from command line:

vlc.exe --extraintf=http:logger --verbose=2 --file-logging --logfile=vlc-log.txt

How to convert a unix timestamp (seconds since epoch) to Ruby DateTime?

Sorry, brief moment of synapse failure. Here's the real answer.

require 'date'

Brief example (this takes into account the current system timezone):

$ date +%s

$ irb

ruby-1.9.2-p180 :001 > require 'date'
 => true 

ruby-1.9.2-p180 :002 >
 => #<DateTime: 2011-10-18T23:01:52-05:00 (13261609807/5400,-5/24,2299161)> 

Further update (for UTC):

ruby-1.9.2-p180 :003 >
 => #<DateTime: 2011-10-19T04:01:52+00:00 (13261609807/5400,0/1,2299161)>

Recent Update: I benchmarked the top solutions in this thread while working on a HA service a week or two ago, and was surprised to find that outperforms DateTime.strptime(..) (update: added more benchmarks).

# ~ % ruby -v
#  => ruby 2.1.5p273 (2014-11-13 revision 48405) [x86_64-darwin13.0]

irb(main):038:0> Benchmark.measure do
irb(main):039:1*   ["1318996912", "1318496912"].each do |s|
irb(main):040:2*     DateTime.strptime(s, '%s')
irb(main):041:2>   end
irb(main):042:1> end

=> #<Benchmark ... @real=2.9e-05 ... @total=0.0>

irb(main):044:0> Benchmark.measure do
irb(main):045:1>   [1318996912, 1318496912].each do |i|
irb(main):046:2>     DateTime.strptime(i.to_s, '%s')
irb(main):047:2>   end
irb(main):048:1> end

=> #<Benchmark ... @real=2.0e-05 ... @total=0.0>

irb(main):050:0* Benchmark.measure do
irb(main):051:1*   ["1318996912", "1318496912"].each do |s|
irb(main):053:2>   end
irb(main):054:1> end

=> #<Benchmark ... @real=1.5e-05 ... @total=0.0>

irb(main):056:0* Benchmark.measure do
irb(main):057:1*   [1318996912, 1318496912].each do |i|
irb(main):059:2>   end
irb(main):060:1> end

=> #<Benchmark ... @real=2.0e-05 ... @total=0.0>

C# 4.0: Convert pdf to byte[] and vice versa

Easiest way:

byte[] buffer;
using (Stream stream = new IO.FileStream("file.pdf"))
   buffer = new byte[stream.Length - 1];
   stream.Read(buffer, 0, buffer.Length);

using (Stream stream = new IO.FileStream("newFile.pdf"))
   stream.Write(buffer, 0, buffer.Length);

Or something along these lines...

Adding onClick event dynamically using jQuery

You can use the click event and call your function or move your logic into the handler:

$("#bfCaptchaEntry").click(function(){ myFunction(); });

You can use the click event and set your function as the handler:



Bind an event handler to the "click" JavaScript event, or trigger that event on an element.

You can use the on event bound to "click" and call your function or move your logic into the handler:

$("#bfCaptchaEntry").on("click", function(){ myFunction(); });

You can use the on event bound to "click" and set your function as the handler:

$("#bfCaptchaEntry").on("click", myFunction);


Attach an event handler function for one or more events to the selected elements.

using setTimeout on promise chain

If you are inside a .then() block and you want to execute a settimeout()

            .then(() => {
                console.log('wait for 10 seconds . . . . ');
                return new Promise(function(resolve, reject) { 
                    setTimeout(() => {
                        console.log('10 seconds Timer expired!!!');
                    }, 10000)
            .then(() => {
                console.log('promise resolved!!!');


output will as shown below

wait for 10 seconds . . . .
10 seconds Timer expired!!!
promise resolved!!!

Happy Coding!

jQuery UI themes and HTML tables

Why noy just use the theme styles in the table? i.e.

  <thead class="ui-widget-header">
  <tbody class="ui-widget-content">

And you don't need to use any code...

This app won't run unless you update Google Play Services (via Bazaar)

This app won't run unless you update Google Play Services. I have tried it for such a long much time, but still I didn't get the map... Only a blank screen is appearing, even if I modified my Google Play Service given by the below comment..

Check your play services manifest file and check the version code for the APK file In the below, it is "3136110". Download these APK files and install from a DOS prompt, but before installation run your target emulator.

android:versionName="3.1.36 (673201-10)

I got these APK files from this link.

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

The 'u' in front of the string values means the string is a Unicode string. Unicode is a way to represent more characters than normal ASCII can manage. The fact that you're seeing the u means you're on Python 2 - strings are Unicode by default on Python 3, but on Python 2, the u in front distinguishes Unicode strings. The rest of this answer will focus on Python 2.

You can create a Unicode string multiple ways:

>>> u'foo'
>>> unicode('foo') # Python 2 only

But the real reason is to represent something like this (translation here):

>>> val = u'???????????? ? ?????????????'
>>> val
u'\u041e\u0437\u043d\u0430\u043a\u043e\u043c\u044c\u0442\u0435\u0441\u044c \u0441 \u0434\u043e\u043a\u0443\u043c\u0435\u043d\u0442\u0430\u0446\u0438\u0435\u0439'
>>> print val
???????????? ? ?????????????

For the most part, Unicode and non-Unicode strings are interoperable on Python 2.

There are other symbols you will see, such as the "raw" symbol r for telling a string not to interpret backslashes. This is extremely useful for writing regular expressions.

>>> 'foo\"'
>>> r'foo\"'

Unicode and non-Unicode strings can be equal on Python 2:

>>> bird1 = unicode('unladen swallow')
>>> bird2 = 'unladen swallow'
>>> bird1 == bird2

but not on Python 3:

>>> x = u'asdf' # Python 3
>>> y = b'asdf' # b indicates bytestring
>>> x == y

Why is my JQuery selector returning a n.fn.init[0], and what is it?

Here is how to do a quick check to see if n.fn.init[0] is caused by your DOM-elements not loading in time. Delay your selector function by wrapping it in setTimeout function like this:

function timeout(){ 

    ...your selector function that returns n.fn.init[0] goes here...


setTimeout(timeout, 5000)

This will cause your selector function to execute with a 5 second delay, which should be enough for pretty much anything to load.

This is just a coarse hack to check if DOM is ready for your selector function or not. This is not a (permanent) solution.

The preferred ways to check if the DOM is loaded before executing your function are as follows:

1) Wrap your selector function in

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

2) If that doesn't work, use DOMContentLoaded

3) Try window.onload, which waits for all the images to load first, so its least preferred

window.onload = function () {  ... your selector function...  }

4) If you are waiting for a library to load that loads in several steps or has some sort of delay of its own, then you might need some complicated custom solution. This is what happened to me with "MathJax" library. This question discusses how to check when MathJax library loaded its DOM elements, if it is of any help.

5) Finally, you can stick with hard-coded setTimeout function, making it maybe 1-3 seconds. This is actually the very least preferred method in my opinion.

This list of fixes is probably far from perfect so everyone is welcome to edit it.

Maven and Spring Boot - non resolvable parent pom - (Unknown host)

As people already mentioned, it could be internet problems or proxy configuration.
I found this question when I was searching about the same problem. In my case, it was proxy configuration.
Answers posted here didn't solve my issue, because every link suggest a configuration that shows the username and passoword and I can't use it.
I was searching about it elsewere and I found a configuration to be made on settings.xml, I needed to make some changes. Here is the final code:



I hope be useful.

Detect if Visual C++ Redistributable for Visual Studio 2012 is installed

It is hard to get all registry values for VC 2012 so I have written a small function which will go through all dependencies and match on specified version.

public static bool IsVC2012Installed()
    string dependenciesPath = @"SOFTWARE\Classes\Installer\Dependencies";

    using (RegistryKey dependencies = Registry.LocalMachine.OpenSubKey(dependenciesPath))
        if (dependencies == null) return false;

        foreach (string subKeyName in dependencies.GetSubKeyNames().Where(n => !n.ToLower().Contains("dotnet") && !n.ToLower().Contains("microsoft")))
            using (RegistryKey subDir = Registry.LocalMachine.OpenSubKey(dependenciesPath + "\\" + subKeyName))
                var value = subDir.GetValue("DisplayName")?.ToString() ?? null;
                if (string.IsNullOrEmpty(value)) continue;

                if (Regex.IsMatch(value, @"C\+\+ 2012")) //here u can specify your version.
                    return true;

    return false;


using System.Text.RegularExpressions;
using Microsoft.Win32;
using System.Linq;

How to recognize vehicle license / number plate (ANPR) from an image?

There is a new, open source library on GitHub that does ANPR for US and European plates. It looks pretty accurate and it should do exactly what you need (recognize the plate regions). Here is the GitHub project:

Push eclipse project to GitHub with EGit

Simple Steps:

-Open Eclipse.

  • Select Project which you want to push on github->rightclick.
  • select Team->share Project->Git->Create repository->finish.(it will ask to login in Git account(popup).
  • Right click again to Project->Team->commit. you are done

Python "TypeError: unhashable type: 'slice'" for encoding categorical data

While creating the matrix X and Y vector use values.


It will definitely solve your problem.

Detect enter press in JTextField

If you want to set a default button action in a JTextField enter, you have to do this:

//put this after initComponents();


It is [0] because a button can has a lot of actions, but normally just has one (ActionPerformed).

How to create a DB for MongoDB container on start up?

UPD Today I avoid Docker Swarm, secrets, and configs. I'd run it with docker-compose and the .env file. As long as I don't need autoscaling. If I do, I'd probably choose k8s. And database passwords, root account or not... Do they really matter when you're running a single database in a container not connected to the outside world?.. I'd like to know what you think about it, but Stack Overflow is probably not well suited for this sort of communication.

Mongo image can be affected by MONGO_INITDB_DATABASE variable, but it won't create the database. This variable determines current database when running /docker-entrypoint-initdb.d/* scripts. Since you can't use environment variables in scripts executed by Mongo, I went with a shell script:


version: '3.1'

    file: mongo-root-passwd
    file: mongo-user-passwd

    image: mongo:3.2
      MONGO_INITDB_ROOT_PASSWORD_FILE: /run/secrets/mongo-root-passwd
      MONGO_INITDB_PASSWORD_FILE: /run/secrets/mongo-user-passwd
      - ./
      - mongo-root-passwd
      - mongo-user-passwd

    var rootUser = '$MONGO_INITDB_ROOT_USERNAME';
    var rootPassword = '$MONGO_INITDB_ROOT_PASSWORD';
    var admin = db.getSiblingDB('admin');
    admin.auth(rootUser, rootPassword);

    var user = '$MONGO_INITDB_USERNAME';
    var passwd = '$(cat "$MONGO_INITDB_PASSWORD_FILE")';
    db.createUser({user: user, pwd: passwd, roles: ["readWrite"]});

Alternatively, you can store in configs (docker config create) and mount it with:

        external: true
            - source:
              target: /docker-entrypoint-initdb.d/

And secrets can be not stored in a file.

A couple of gists on the matter.

What are 'get' and 'set' in Swift?

You should look at Computed Properties

In your code sample, perimeter is a property not backed up by a class variable, instead its value is computed using the get method and stored via the set method - usually referred to as getter and setter.

When you use that property like this:

var cp = myClass.perimeter

you are invoking the code contained in the get code block, and when you use it like this:

myClass.perimeter = 5.0

you are invoking the code contained in the set code block, where newValue is automatically filled with the value provided at the right of the assignment operator.

Computed properties can be readwrite if both a getter and a setter are specified, or readonly if the getter only is specified.

How do I do base64 encoding on iOS?

As per your requirement i have created a sample demo using Swift 4 in which you can encode/decode string and image as per your requirement.

  • I have also added sample methods of relevant operations.

    //  Base64VC.swift
    //  SOF_SortArrayOfCustomObject
    //  Created by Test User on 09/01/18.
    //  Copyright © 2018 Test User. All rights reserved.
    import UIKit
    import Foundation
    class Base64VC: NSObject {
        // MARK:-
        // MARK:- String to Base64 Encode Methods
        func sampleStringEncodingAndDecoding() {
            if let base64String = self.base64Encode(string: "TestString") {
                print("Base64 Encoded String: \n\(base64String)")
                if let originalString = self.base64Decode(base64String: base64String) {
                    print("Base64 Decoded String: \n\(originalString)")
        func base64Encode(string: String) -> String? {
            if let stringData = .utf8) {
                return stringData.base64EncodedString()
            return nil
        func base64Decode(base64String: String) -> String? {
            if let base64Data = Data(base64Encoded: base64String) {
                return String(data: base64Data, encoding: .utf8)
            return nil
        // MARK:-
        // MARK:- Image to Base64 Encode  Methods
        func sampleImageEncodingAndDecoding() {
            if let base64ImageString = self.base64Encode(image: UIImage.init(named: "yourImageName")!) {
                print("Base64 Encoded Image: \n\(base64ImageString)")
                if let originaImage = self.base64Decode(base64ImageString: base64ImageString) {
                    print("originalImageData \n\(originaImage)")
        func base64Encode(image: UIImage) -> String? {
            if let imageData = UIImagePNGRepresentation(image) {
                return imageData.base64EncodedString()
            return nil
        func base64Decode(base64ImageString: String) -> UIImage? {
            if let base64Data = Data(base64Encoded: base64ImageString) {
                return UIImage(data: base64Data)!
            return nil

How can I use grep to find a word inside a folder?

The following sample looks recursively for your search string in the *.xml and *.js files located somewhere inside the folders path1, path2 and path3.

grep -r --include=*.xml --include=*.js "your search string" path1 path2 path3

So you can search in a subset of the files for many directories, just providing the paths at the end.

Check for special characters in string

You can try this:

regex = [\W_]

It will definitely help you.

How can I change the default credentials used to connect to Visual Studio Online (TFSPreview) when loading Visual Studio up?

I had a very similiar problem as I was not able to connect to TFS with my own credentials. Turned out that the user who had created the image (I was using Hyper-V) stored his account in Credential Manager. There was no way to change this in Visual Studio. To solve the issue, I opened Credential Manager in Control Panel and edited the Generic Credentials to be my own account. I closed and opened Visual Studio 2012, and reconnected to TFS. It prompted me for my credentials, but it connected with my account from then on.

hope this helps, sivilian

Select query to get data from SQL Server

According to MSDN

result is the number of lines affected, and since your query is select no lines are affected (i.e. inserted, deleted or updated) anyhow.

If you want to return a single row of the query, use ExecuteScalar() instead of ExecuteNonQuery():

  int result = (int) (command.ExecuteScalar());

However, if you expect many rows to be returned, ExecuteReader() is the only option:

  using (SqlDataReader reader = command.ExecuteReader()) {
    while (reader.Read()) {
      int result = reader.GetInt32(0);


What does "var" mean in C#?

Did you ever hated to write such variable initializers?

XmlSerializer xmlSerializer = new XmlSerialzer(typeof(int))

So, starting with C# 3.0, you can replace it with

var xmlSerializer = new XmlSerialzer(typeof(int))

One notice: Type is resolved during compilation, so no problems with performance. But Compiler should be able to detect type during build step, so code like var xmlSerializer; won't compile at all.

How do you detect the clearing of a "search" HTML5 input?

Found this post and I realize it's a bit old, but I think I might have an answer. This handles the click on the cross, backspacing and hitting the ESC key. I am sure it could probably be written better - I'm still relatively new to javascript. Here is what I ended up doing - I am using jQuery (v1.6.4):

var searchVal = ""; //create a global var to capture the value in the search box, for comparison later
$(document).ready(function() {
  $("input[type=search]").keyup(function(e) {
    if (e.which == 27) {  // catch ESC key and clear input
    if (($(this).val() === "" && searchVal != "") || e.which == 27) {
      // do something
      searchVal = "";
    searchVal = $(this).val();
  $("input[type=search]").click(function() {
    if ($(this).val() != filterVal) {
      // do something
      searchVal = "";

Split output of command by columns using Bash?

Getting the correct line (example for line no. 6) is done with head and tail and the correct word (word no. 4) can be captured with awk:

command|head -n 6|tail -n 1|awk '{print $4}'

Detect if an element is visible with jQuery

You're looking for:


Although you should probably change your selector to use jQuery considering you're using it in other places anyway:

if($('#testElement').is(':visible')) {
    // Code

It is important to note that if any one of a target element's parent elements are hidden, then .is(':visible') on the child will return false (which makes sense).

jQuery 3

:visible has had a reputation for being quite a slow selector as it has to traverse up the DOM tree inspecting a bunch of elements. There's good news for jQuery 3, however, as this post explains (Ctrl + F for :visible):

Thanks to some detective work by Paul Irish at Google, we identified some cases where we could skip a bunch of extra work when custom selectors like :visible are used many times in the same document. That particular case is up to 17 times faster now!

Keep in mind that even with this improvement, selectors like :visible and :hidden can be expensive because they depend on the browser to determine whether elements are actually displaying on the page. That may require, in the worst case, a complete recalculation of CSS styles and page layout! While we don’t discourage their use in most cases, we recommend testing your pages to determine if these selectors are causing performance issues.

Expanding even further to your specific use case, there is a built in jQuery function called $.fadeToggle():

function toggleTestElement() {

Understanding the basics of Git and GitHub

  1. What is the difference between Git and GitHub?

    Linus Torvalds would kill you for this. Git is the name of the version manager program he wrote. GitHub is a website on which there are source code repositories manageable by Git. Thus, GitHub is completely unrelated to the original Git tool.

  2. Is git saving every repository locally (in the user's machine) and in GitHub?

    If you commit changes, it stores locally. Then, if you push the commits, it also sotres them remotely.

  3. Can you use Git without GitHub? If yes, what would be the benefit for using GitHub?

    You can, but I'm sure you don't want to manually set up a git server for yourself. Benefits of GitHub? Well, easy to use, lot of people know it so others may find your code and follow/fork it to make improvements as well.

  4. How does Git compare to a backup system such as Time Machine?

    Git is specifically designed and optimized for source code.

  5. Is this a manual process, in other words if you don't commit you wont have a new version of the changes made?


  6. If are not collaborating and you are already using a backup system why would you use Git?

    See #4.

Parsing JSON using C

Json isn't a huge language to start with, so libraries for it are likely to be small(er than Xml libraries, at least).

There are a whole ton of C libraries linked at Maybe one of them will work well for you.

regular expression to validate datetime format (MM/DD/YYYY)

you can look into this link and I hope this may be of great help as its was for me.

If you are using the regex given in the above link in Java code then use the following regex

"^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\\d\\d$"

As I noticed in your example you are using js function then this use regex

"^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d$"

This will match a date in mm/dd/yyyy format from between 1900-01-01 and 2099-12-31, with a choice of four separators. and not to forget the

return regex.test(testdate);

How can I get zoom functionality for images?

You can try using the LayoutParams for this

public void zoom(boolean flag){
        int width=40;
        int height=40;
        int width=20;
        int height=20;
    RelativeLayout.LayoutParams param=new RelativeLayout.LayoutParams(width,height); //use the parent layout of the ImageView;
    imageView.setLayoutParams(param); //imageView is the view which needs zooming.

ZoomIn = zoom(true); ZoomOut = zoom(false);

Guid is all 0's (zeros)?

Try this instead:

var responseObject = proxy.CallService(new RequestObject
    Data = "misc. data",
    Guid = new Guid.NewGuid()

This will generate a 'real' Guid value. When you new a reference type, it will give you the default value (which in this case, is all zeroes for a Guid).

When you create a new Guid, it will initialize it to all zeroes, which is the default value for Guid. It's basically the same as creating a "new" int (which is a value type but you can do this anyways):

Guid g1;                    // g1 is 00000000-0000-0000-0000-000000000000
Guid g2 = new Guid();       // g2 is 00000000-0000-0000-0000-000000000000
Guid g3 = default(Guid);    // g3 is 00000000-0000-0000-0000-000000000000
Guid g4 = Guid.NewGuid();   // g4 is not all zeroes

Compare this to doing the same thing with an int:

int i1;                     // i1 is 0
int i2 = new int();         // i2 is 0
int i3 = default(int);      // i3 is 0

How to test if a string is JSON or not?

There are probably tests you can do, for instance if you know that the JSON returned is always going to be surrounded by { and } then you could test for those characters, or some other hacky method. Or you could use the JS library to try and parse it and test if it succeeds.

I would however suggest a different approach. Your PHP script currently returns JSON if the call is successful, but something else if it is not. Why not always return JSON?


Successful call:

{ "status": "success", "data": [ <your data here> ] }

Erroneous call:

{ "status": "error", "error": "Database not found" }

This would make writing your client side JS much easier - all you have to do is check the "status" member and the act accordingly.

How to specify a port number in SQL Server connection string?

The correct SQL connection string for SQL with specify port is use comma between ip address and port number like following pattern:,yyyy

Unable to verify leaf signature

Note: the following is dangerous, and will allow API content to be intercepted and modified between the client and the server.

This also worked

process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = '0';

PHP remove all characters before specific string


$string="We have www/audio path where the audio files are stored";  //Considering the string like this

Either you can use

strstr($string, 'www/audio');



Automatically plot different colored lines

If all vectors have equal size, create a matrix and plot it. Each column is plotted with a different color automatically Then you can use legend to indicate columns:

data = randn(100, 5);



Or, if you have a cell with kernels names, use


loading json data from local file into React JS

The simplest and most effective way to make a file available to your component is this:

var data = require('json!./data.json');

Note the json! before the path

How to measure time elapsed on Javascript?

var seconds = 0;
setInterval(function () {
}, 1000);

There you go, now you have a variable counting seconds elapsed. Since I don't know the context, you'll have to decide whether you want to attach that variable to an object or make it global.

Set interval is simply a function that takes a function as it's first parameter and a number of milliseconds to repeat the function as it's second parameter.

You could also solve this by saving and comparing times.

EDIT: This answer will provide very inconsistent results due to things such as the event loop and the way browsers may choose to pause or delay processing when a page is in a background tab. I strongly recommend using the accepted answer.

How do I determine the current operating system with Node.js

The variable to use would be process.platform

On Mac the variable returns darwin. On Windows, it returns win32 (even on 64 bit).

Current possible values are:

  • aix
  • darwin
  • freebsd
  • linux
  • openbsd
  • sunos
  • win32

I just set this at the top of my jakeFile:

var isWin = process.platform === "win32";

Have border wrap around text

Try this and see if you get what you are aiming for:

<div id='page' style='width: 600px'>_x000D_
  <h1 style='border:2px black solid; font-size:42px; width:fit-content; width:-webkit-fit-content; width:-moz-fit-content;'>Title</h1>_x000D_

How do I split a string into an array of characters?

The split() method in javascript accepts two parameters: a separator and a limit. The separator specifies the character to use for splitting the string. If you don't specify a separator, the entire string is returned, non-separated. But, if you specify the empty string as a separator, the string is split between each character.



will have the effect you seek.

More information here

Uncaught ReferenceError: React is not defined

I got this error because in my code I misspelled a component definition with lowercase react.createClass instead of uppercase React.createClass.

Get Cell Value from Excel Sheet with Apache Poi

May be by:-

    for(Row row : sheet) {          
        for(Cell cell : row) {              


For specific type of cell you can try:

switch (cell.getCellType()) {
    cellValue = cell.getStringCellValue();

    cellValue = cell.getCellFormula();

    if (DateUtil.isCellDateFormatted(cell)) {
        cellValue = cell.getDateCellValue().toString();
    } else {
        cellValue = Double.toString(cell.getNumericCellValue());

    cellValue = "";

    cellValue = Boolean.toString(cell.getBooleanCellValue());


Rails: How can I rename a database column in a Ruby on Rails migration?

For Ruby on Rails 4:

def change
    rename_column :table_name, :column_name_old, :column_name_new

ReferenceError: event is not defined error in Firefox

It is because you forgot to pass in event into the click function:

$('.menuOption').on('click', function (e) { // <-- the "e" for event

    e.preventDefault(); // now it'll work

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

On a side note, e is more commonly used as opposed to the word event since Event is a global variable in most browsers.

how can I login anonymously with ftp (/usr/bin/ftp)?

As others point out, the user name is usually anonymous, and the password is usually your e-mail address, but this is not universally true, and has been found not to work for certain anonymous FTP sites. For example, at least some cPanel sites seem to deviate from the norm, and if given the traditional user name without domain, one of various errors may result:

If the server uses Pure-FTP as the FTP server:

421 Can't change directory to /var/ftp/ error message.

If the server uses ProFTP as the FTP server:

530 Login Authentication Failed error message.

When one of the aforementioned errors occurs when attempting anonymous access, try including a domain with the username. For example, where is the domain used in your e-mail address:

User name: [email protected]

In the specific case of a cPanel site, the password value is unimportant, and may be left blank, but there is no harm in providing a "traditional" anonymous password formatted as an e-mail address.

For reference, this answer is based on content found on a Anonymous FTP page. At the time of this writing, it stated:

When users log in to FTP anonymously, they must format usernames as [email protected], where represents the user's domain name. This requirement directs your server to the correct public_ftp directory.

How do I change the default library path for R packages

See help(Startup) and help(.libPaths) as you have several possibilities where this may have gotten set. Among them are

  • setting R_LIBS_USER
  • assigning .libPaths() in .Rprofile or

and more.

In this particular case you need to go backwards and unset whereever \\\\The library/path/I/don't/want is set.

To otherwise ignore it you need to override it use explicitly i.e. via

library("somePackage", lib.loc=.libPaths()[-1])

when loading a package.

Django set default form values

As explained in Django docs, initial is not default.

  • The initial value of a field is intended to be displayed in an HTML . But if the user delete this value, and finally send back a blank value for this field, the initial value is lost. So you do not obtain what is expected by a default behaviour.

  • The default behaviour is : the value that validation process will take if data argument do not contain any value for the field.

To implement that, a straightforward way is to combine initial and clean_<field>():

class JournalForm(ModelForm):
    tank = forms.IntegerField(widget=forms.HiddenInput(), initial=123) 


    def clean_tank(self):
        if not self['tank'].html_name in
            return self.fields['tank'].initial
        return self.cleaned_data['tank']

Typescript ReferenceError: exports is not defined

I solved the issue by removing "type": "module" field from package.json.

How to install python-dateutil on Windows?

Just run command prompt as administrator and type this in.

easy_install python-dateutil

Arguments to main in C

Imagine it this way

*main() is also a function which is called by something else (like another FunctioN)

*the arguments to it is decided by the FunctioN

*the second argument is an array of strings

*the first argument is a number representing the number of strings

*do something with the strings

Maybe a example program woluld help.

int main(int argc,char *argv[])

    printf("you entered in reverse order:\n");


return 0;

it just prints everything you enter as args in reverse order but YOU should make new programs that do something more useful.

compile it (as say hello) run it from the terminal with the arguments like

./hello am i here

then try to modify it so that it tries to check if two strings are reverses of each other or not then you will need to check if argc parameter is exactly three if anything else print an error

if(argc!=3)/*3 because even the executables name string is on argc*/
    printf("unexpected number of arguments\n");
    return -1;

then check if argv[2] is the reverse of argv[1] and print the result

./hello asdf fdsa

should output

they are exact reverses of each other

the best example is a file copy program try it it's like cp

cp file1 file2

cp is the first argument (argv[0] not argv[1]) and mostly you should ignore the first argument unless you need to reference or something

if you made the cp program you understood the main args really...

fetch gives an empty response body

I just ran into this. As mentioned in this answer, using mode: "no-cors" will give you an opaque response, which doesn't seem to return data in the body.

opaque: Response for “no-cors” request to cross-origin resource. Severely restricted.

In my case I was using Express. After I installed cors for Express and configured it and removed mode: "no-cors", I was returned a promise. The response data will be in the promise, e.g.

fetch('', {
  // mode: 'no-cors',
  method: 'GET',
  headers: {
    Accept: 'application/json',
).then(response => {
  if (response.ok) {
    response.json().then(json => {

How do I set vertical space between list items?

setting padding-bottom for each list using pseudo class is a viable method. Also line height can be used. Remember that font properties such as font-family, Font-weight, etc. plays a role for uneven heights.

Print range of numbers on same line

n = int(input())
for i in range(1,n+1):

Batch Files - Error Handling

I generally find the conditional command concatenation operators much more convenient than ERRORLEVEL.

yourCommand && (
  echo yourCommand was successful
) || (
  echo yourCommand failed

There is one complication you should be aware of. The error branch will fire if the last command in the success branch raises an error.

yourCommand && (
) || (
  echo This will fire if yourCommand or someCommandThatMayFail raises an error

The fix is to insert a harmless command that is guaranteed to succeed at the end of the success branch. I like to use (call ), which does nothing except set the ERRORLEVEL to 0. There is a corollary (call) that does nothing except set the ERRORLEVEL to 1.

yourCommand && (
  (call )
) || (
  echo This can only fire if yourCommand raises an error

See Foolproof way to check for nonzero (error) return code in windows batch file for examples of the intricacies needed when using ERRORLEVEL to detect errors.

How to refresh an access form

No, it is like I want to run Form_Load of Form A,if it is possible

-- Varun Mahajan

The usual way to do this is to put the relevant code in a procedure that can be called by both forms. It is best put the code in a standard module, but you could have it on Form a:

Form B:

Sub RunFormALoad()
End Sub

Form A:

Public Sub Form_Load()
End Sub    

Sub ToDoOnLoad()
    txtText = "Hi"
End Sub

possible EventEmitter memory leak detected

As pointed out by others, increasing the limit is not the best answer. I was facing the same issue, but in my code I was nowhere using any event listener. When I closely looked into the code, I was creating a lot of promises at times. Each promise had some code of scraping the provided URL (using some third-party library). If you are doing something like that, then it may be the cause.

Refer this thread on how to prevent that: What is the best way to limit concurrency when using ES6's Promise.all()?

Removing multiple keys from a dictionary safely

It would be nice to have full support for set methods for dictionaries (and not the unholy mess we're getting with Python 3.9) so that you could simply "remove" a set of keys. However, as long as that's not the case, and you have a large dictionary with potentially a large number of keys to remove, you might want to know about the performance. So, I've created some code that creates something large enough for meaningful comparisons: a 100,000 x 1000 matrix, so 10,000,00 items in total.

from itertools import product
from time import perf_counter

# make a complete worksheet 100000 * 1000
start = perf_counter()
prod = product(range(1, 100000), range(1, 1000))
cells = {(x,y):x for x,y in prod}

print(f"Create time {perf_counter()-start:.2f}s")
clock = perf_counter()
# remove everything above row 50,000

keys = product(range(50000, 100000), range(1, 100))

# for x,y in keys:
#     del cells[x, y]

for n in map(cells.pop, keys):

stop = perf_counter()
print(f"Removal time {stop-clock:.2f}s")

10 million items or more is not unusual in some settings. Comparing the two methods on my local machine I see a slight improvement when using map and pop, presumably because of fewer function calls, but both take around 2.5s on my machine. But this pales in comparison to the time required to create the dictionary in the first place (55s), or including checks within the loop. If this is likely then its best to create a set that is a intersection of the dictionary keys and your filter:

keys = cells.keys() & keys

In summary: del is already heavily optimised, so don't worry about using it.

Removing "NUL" characters

Try Find and Replace. type \x00 in Find text box, check the Regular expression option. Leave Replace textbox blank and click on replace all. short cut key for find and replace is ctrl+H.

Could not find a part of the path ... bin\roslyn\csc.exe

A lot of these answers are referring to the Nuget packages and/or cleaning and reloading your project.

If you have WCF service references and invalid endpoints, you can also get this error message. Make sure your endpoints are correct and update the service configuration with the correct endpoint in the .config and when you configure the service reference from the GUI.

Image of Service Reference Configuration GUI

JQuery Validate Dropdown list

I have modified your code a little. Here's a working version (for me):

    <select name="dd1" id="dd1">
       <option value="none">None</option>
       <option value="o1">option 1</option>
       <option value="o2">option 2</option>
       <option value="o3">option 3</option>
    <div style="color:red;" id="msg_id"></div>

        var department = $("#msg_id");
        var msg = "Please select Department";
            if ($('#dd1').val() == "") {
                return false;

Find number of decimal places in decimal value regardless of culture

Most people here seem to be unaware that decimal considers trailing zeroes as significant for storage and printing.

So 0.1m, 0.10m and 0.100m may compare as equal, they are stored differently (as value/scale 1/1, 10/2 and 100/3, respectively), and will be printed as 0.1, 0.10 and 0.100, respectively, by ToString().

As such, the solutions that report "too high a precision" are actually reporting the correct precision, on decimal's terms.

In addition, math-based solutions (like multiplying by powers of 10) will likely be very slow (decimal is ~40x slower than double for arithmetic, and you don't want to mix in floating-point either because that's likely to introduce imprecision). Similarly, casting to int or long as a means of truncating is error-prone (decimal has a much greater range than either of those - it's based around a 96-bit integer).

While not elegant as such, the following will likely be one of the fastest way to get the precision (when defined as "decimal places excluding trailing zeroes"):

public static int PrecisionOf(decimal d) {
  var text = d.ToString(System.Globalization.CultureInfo.InvariantCulture).TrimEnd('0');
  var decpoint = text.IndexOf('.');
  if (decpoint < 0)
    return 0;
  return text.Length - decpoint - 1;

The invariant culture guarantees a '.' as decimal point, trailing zeroes are trimmed, and then it's just a matter of seeing of how many positions remain after the decimal point (if there even is one).

Edit: changed return type to int

How to obfuscate Python code effectively?

Maybe you can try on pyconcrete

encrypt .pyc to .pye and decrypt when import it

encrypt & decrypt by library OpenAES


Full encrypted

  • convert all of your .py to *.pye

    $ compile --source={your py script}  --pye
    $ compile --source={your py module dir} --pye
  • remove *.py *.pyc or copy *.pye to other folder

  • encrypted as main.pye, it can't be executed by normal python. You must use pyconcrete to process the main.pye script. pyconcrete(exe) will be installed in your system path (ex: /usr/local/bin)

    pyconcrete main.pye
    src/*.pye  # your libs

Partial encrypted (pyconcrete as lib)

  • download pyconcrete source and install by

    $ python install \
      --install-lib={your project path} \
      --install-scripts={where you want to execute and pyconcrete(exe)}
  • import pyconcrete in your main script

  • recommendation project layout       # import pyconcrete and your lib
    pyconcrete/*  # put pyconcrete lib in project root, keep it as original files
    src/*.pye     # your libs

Microsoft.Jet.OLEDB.4.0' provider is not registered on the local machine

We have come across this issue in desktop app.

Dev Environment: Windows 7 Ultimate - 64 bit .Net Framework 4.5 Provider=Microsoft.Jet.OLEDB.4.0

It has been resolved by changing Platform target to X86 from Any CPU. Project Properties >> Build >> Platform Target.

enter image description here

SQL: Alias Column Name for Use in CASE Statement

Yes, you just need to add a parenthesis :

SELECT col1 as a, (CASE WHEN a = 'test' THEN 'yes' END) as value FROM table;

Set the text in a span


TSQL Pivot without aggregate function

Here is a great way to build dynamic fields for a pivot query:

--summarize values to a tmp table

declare @STR varchar(1000)
SELECT  @STr =  COALESCE(@STr +', ', '') 
+ QUOTENAME(DateRange) 
from (select distinct DateRange, ID from ##pivot)d order by ID

---see the fields generated

print @STr

exec('  .... pivot code ...
pivot (avg(SalesAmt) for DateRange IN (' + @Str +')) AS P
order by Decile')

Array slices in C#

Starting from C# 8.0/.Net Core 3.0

Array slicing will be supported, along with the new types Index and Range being added.

Range Struct docs
Index Struct docs

Index i1 = 3;  // number 3 from beginning
Index i2 = ^4; // number 4 from end
int[] a = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
Console.WriteLine($"{a[i1]}, {a[i2]}"); // "3, 6"

var slice = a[i1..i2]; // { 3, 4, 5 }

Above code sample taken from the C# 8.0 blog.

note that the ^ prefix indicates counting from the end of the array. As shown in the docs example

var words = new string[]
                // index from start    index from end
    "The",      // 0                   ^9
    "quick",    // 1                   ^8
    "brown",    // 2                   ^7
    "fox",      // 3                   ^6
    "jumped",   // 4                   ^5
    "over",     // 5                   ^4
    "the",      // 6                   ^3
    "lazy",     // 7                   ^2
    "dog"       // 8                   ^1
};              // 9 (or words.Length) ^0

Range and Index also work outside of slicing arrays, for example with loops

Range range = 1..4; 
foreach (var name in names[range])

Will loop through the entries 1 through 4

note that at the time of writing this answer, C# 8.0 is not yet officially released
C# 8.x and .Net Core 3.x are now available in Visual Studio 2019 and onwards

Execute Insert command and return inserted Id in Sql

SQL Server stored procedure:

    @na varchar(50),
    @occ varchar(50),

    INSERT INTO Mem_Basic
    VALUES (@na, @occ)


C# code:

public int CreateNewMember(string Mem_NA, string Mem_Occ )
    // values 0 --> -99 are SQL reserved.
    int new_MEM_BASIC_ID = -1971;   
    SqlConnection SQLconn = new SqlConnection(Config.ConnectionString);
    SqlCommand cmd = new SqlCommand("INS_MEM_BASIC", SQLconn);

    cmd.CommandType = CommandType.StoredProcedure;

    SqlParameter outPutVal = new SqlParameter("@New_MEM_BASIC_ID", SqlDbType.Int);

    outPutVal.Direction = ParameterDirection.Output;
    cmd.Parameters.Add("@na", SqlDbType.Int).Value = Mem_NA;
    cmd.Parameters.Add("@occ", SqlDbType.Int).Value = Mem_Occ;


    if (outPutVal.Value != DBNull.Value) new_MEM_BASIC_ID = Convert.ToInt32(outPutVal.Value);
        return new_MEM_BASIC_ID;

I hope these will help to you ....

You can also use this if you want ...

public int CreateNewMember(string Mem_NA, string Mem_Occ )
    using (SqlConnection con=new SqlConnection(Config.ConnectionString))
        int newID;
        var cmd = "INSERT INTO Mem_Basic(Mem_Na,Mem_Occ) VALUES(@na,@occ);SELECT CAST(scope_identity() AS int)";

        using(SqlCommand cmd=new SqlCommand(cmd, con))
            cmd.Parameters.AddWithValue("@na", Mem_NA);
            cmd.Parameters.AddWithValue("@occ", Mem_Occ);

            newID = (int)insertCommand.ExecuteScalar();

            if (con.State == System.Data.ConnectionState.Open) con.Close();
                return newID;

Is there a portable way to get the current username in Python?

I wrote the plx module some time ago to get the user name in a portable way on Unix and Windows (among other things):


import plx

username = plx.get_username()

(it requires win32 extensions on Windows)

Make selected block of text uppercase

Creator of the change-case extension here. I've updated the extension to support spanning lines.

To map the upper case command to a keybinding (e.g. CTRL+T+U), click File -> Preferences -> Keyboard shortcuts, and insert the following into the json config:

  "key": "ctrl+t ctrl+u",
  "command": "extension.changeCase.upper",
  "when": "editorTextFocus"


With the November 2016 (release notes) update of VSCode, there is built-in support for converting to upper case and lower case via the commands editor.action.transformToUppercase and editor.action.transformToLowercase. These don't have default keybindings. They also work with multi-line blocks.

The change-case extension is still useful for other text transformations, e.g. camelCase, PascalCase, snake_case, kebab-case, etc.

Python os.path.join on Windows

For a system-agnostic solution that works on both Windows and Linux, no matter what the input path, one could use os.path.join(os.sep, rootdir + os.sep, targetdir)

On WIndows:

>>> os.path.join(os.sep, "C:" + os.sep, "Windows")

On Linux:

>>> os.path.join(os.sep, "usr" + os.sep, "lib")

difference between css height : 100% vs height : auto

height: 100% gives the element 100% height of its parent container.

height: auto means the element height will depend upon the height of its children.

Consider these examples:

height: 100%

<div style="height: 50px">
    <div id="innerDiv" style="height: 100%">

#innerDiv is going to have height: 50px

height: auto

<div style="height: 50px">
    <div id="innerDiv" style="height: auto">
          <div id="evenInner" style="height: 10px">

#innerDiv is going to have height: 10px

How do I install Python packages in Google's Colab?

  1. Upload to drive.
  2. Mount the drive.
  3. Get the path of
  4. !python PATH install.

No mapping found for HTTP request with URI Spring MVC

First check whether the java classes are compiled or not in your [PROJECT_NAME]\target\classes directory.

If not you have some compilation errors in your java classes.

How to wait for a number of threads to complete?

As an alternative to CountDownLatch you can also use CyclicBarrier e.g.

public class ThreadWaitEx {
    static CyclicBarrier barrier = new CyclicBarrier(100, new Runnable(){
        public void run(){
            System.out.println("clean up job after all tasks are done.");
    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            Thread t = new Thread(new MyCallable(barrier));


class MyCallable implements Runnable{
    private CyclicBarrier b = null;
    public MyCallable(CyclicBarrier b){
        this.b = b;
    public void run(){
        try {
            //do something
            System.out.println(Thread.currentThread().getName()+" is waiting for barrier after completing his job.");
        } catch (InterruptedException e) {
        } catch (BrokenBarrierException e) {

To use CyclicBarrier in this case barrier.await() should be the last statement i.e. when your thread is done with its job. CyclicBarrier can be used again with its reset() method. To quote javadocs:

A CyclicBarrier supports an optional Runnable command that is run once per barrier point, after the last thread in the party arrives, but before any threads are released. This barrier action is useful for updating shared-state before any of the parties continue.

find first sequence item that matches a criterion

If you don't have any other indexes or sorted information for your objects, then you will have to iterate until such an object is found:

next(obj for obj in objs if obj.val == 5)

This is however faster than a complete list comprehension. Compare these two:

[i for i in xrange(100000) if i == 1000][0]

next(i for i in xrange(100000) if i == 1000)

The first one needs 5.75ms, the second one 58.3µs (100 times faster because the loop 100 times shorter).

disable Bootstrap's Collapse open/close animation

Bootstrap 2 CSS solution:

.collapse {  transition: height 0.01s; }  

NB: setting transition: none disables the collapse functionnality.

Bootstrap 4 solution:

.collapsing {
  transition: none !important;

Can you animate a height change on a UITableViewCell when selected?

Get the indexpath of the row selected. Reload the table. In the heightForRowAtIndexPath method of UITableViewDelegate, set the height of the row selected to a different height and for the others return the normal row height

How can I control the speed that bootstrap carousel slides in items?

In your CSS:

.carousel-item {
    transition-duration: 1.5s, 1.5s;

Take care, the time is included in data-interval defined for the carousel.

Hope it helps... :)

How to use subprocess popen Python

In the recent Python version, subprocess has a big change. It offers a brand-new class Popen to handle os.popen1|2|3|4.

The new subprocess.Popen()

import subprocess
subprocess.Popen('ls -la', shell=True)

Its arguments:

                stdin=None, stdout=None, stderr=None, 
                preexec_fn=None, close_fds=False, 
                cwd=None, env=None, 

Simply put, the new Popen includes all the features which were split into 4 separate old popen.

The old popen:

Method  Arguments
popen   stdout
popen2  stdin, stdout
popen3  stdin, stdout, stderr
popen4  stdin, stdout and stderr

You could get more information in Stack Abuse - Robert Robinson. Thank him for his devotion.

Search in lists of lists by given index

Here's the Pythonic way to do it:

data = [['a','b'], ['a','c'], ['b','d']]
search = 'c'
any(e[1] == search for e in data)

Or... well, I'm not going to claim this is the "one true Pythonic way" to do it because at some point it becomes a little subjective what is Pythonic and what isn't, or which method is more Pythonic than another. But using any() is definitely more typical Python style than a for loop as in e.g. RichieHindle's answer,

Of course there is a hidden loop in the implementation of any, although it breaks out of the loop as soon as it finds a match.

Since I was bored I made a timing script to compare performance of the different suggestions, modifying some of them as necessary to make the API the same. Now, we should bear in mind that fastest is not always best, and being fast is definitely not the same thing as being Pythonic. That being said, the results are... strange. Apparently for loops are very fast, which is not what I expected, so I'd take these with a grain of salt without understanding why they've come out the way they do.

Anyway, when I used the list defined in the question with three sublists of two elements each, from fastest to slowest I get these results:

  1. RichieHindle's answer with the for loop, clocking in at 0.22 µs
  2. Terence Honles' first suggestion which creates a list, at 0.36 µs
  3. Pierre-Luc Bedard's answer (last code block), at 0.43 µs
  4. Essentially tied between Markus's answer and the for loop from the original question, at 0.48 µs
  5. Coady's answer using operator.itemgetter(), at 0.53 µs
  6. Close enough to count as a tie between Alex Martelli's answer with ifilter() and Anon's answer, at 0.67 µs (Alex's is consistently about half a microsecond faster)
  7. Another close-enough tie between jojo's answer, mine, Brandon E Taylor's (which is identical to mine), and Terence Honles' second suggestion using any(), all coming in at 0.81-0.82 µs
  8. And then user27221's answer using nested list comprehensions, at 0.95 µs

Obviously the actual timings are not meaningful on anyone else's hardware, but the differences between them should give some idea of how close the different methods are.

When I use a longer list, things change a bit. I started with the list in the question, with three sublists, and appended another 197 sublists, for a total of 200 sublists each of length two. Using this longer list, here are the results:

  1. RichieHindle's answer, at the same 0.22 µs as with the shorter list
  2. Coady's answer using operator.itemgetter(), again at 0.53 µs
  3. Terence Honles' first suggestion which creates a list, at 0.36 µs
  4. Another virtual tie between Alex Martelli's answer with ifilter() and Anon's answer, at 0.67 µs
  5. Again a close-enough tie between my answer, Brandon E Taylor's identical method, and Terence Honles' second suggestion using any(), all coming in at 0.81-0.82 µs

Those are the ones that keep their original timing when the list is extended. The rest, which don't, are

  1. The for loop from the original question, at 1.24 µs
  2. Terence Honles' first suggestion which creates a list, at 7.49 µs
  3. Pierre-Luc Bedard's answer (last code block), at 8.12 µs
  4. Markus's answer, at 10.27 µs
  5. jojo's answer, at 19.87 µs
  6. And finally user27221's answer using nested list comprehensions, at 60.59 µs

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

Consider using <span> to isolate small segments of markup to be styled without breaking up layout. This would seem to be more idiomatic than trying to force a <div> not to display itself--if in fact the checkbox itself cannot be styled in the way you want.

CSS ''background-color" attribute not working on checkbox inside <div>

The Best solution to change background checkbox color

input[type=checkbox] {_x000D_
    margin-right: 5px;_x000D_
    cursor: pointer;_x000D_
    font-size: 14px;_x000D_
    width: 15px;_x000D_
    height: 12px;_x000D_
    position: relative;_x000D_
  input[type=checkbox]:after {_x000D_
    position: absolute;_x000D_
    width: 10px;_x000D_
    height: 15px;_x000D_
    top: 0;_x000D_
    content: " ";_x000D_
    background-color: #ff0000;_x000D_
    color: #fff;_x000D_
    display: inline-block;_x000D_
    visibility: visible;_x000D_
    padding: 0px 3px;_x000D_
    border-radius: 3px;_x000D_
  input[type=checkbox]:checked:after {_x000D_
   content: "?";_x000D_
   font-size: 12px;_x000D_
  <input type="checkbox" name="vehicle" value="Bike"> I have a bike<br>_x000D_
  <input type="checkbox" name="vehicle" value="Car" checked> I have a car<br>_x000D_
  <input type="checkbox" name="vehicle" value="Car" checked> I have a bus<br>

How can I easily view the contents of a datatable or dataview in the immediate window

What I do is have a static class with the following code in my project:

    #region Dataset -> Immediate Window
public static void printTbl(DataSet myDataset)
public static void printTbl(DataTable mytable)
    for (int i = 0; i < mytable.Columns.Count; i++)
        Debug.Write(mytable.Columns[i].ToString() + " | ");
    Debug.Write(Environment.NewLine + "=======" + Environment.NewLine);
    for (int rrr = 0; rrr < mytable.Rows.Count; rrr++)
        for (int ccc = 0; ccc < mytable.Columns.Count; ccc++)
            Debug.Write(mytable.Rows[rrr][ccc] + " | ");
public static void ResponsePrintTbl(DataTable mytable)
    for (int i = 0; i < mytable.Columns.Count; i++)
        HttpContext.Current.Response.Write(mytable.Columns[i].ToString() + " | ");
    HttpContext.Current.Response.Write("<BR>" + "=======" + "<BR>");
    for (int rrr = 0; rrr < mytable.Rows.Count; rrr++)
        for (int ccc = 0; ccc < mytable.Columns.Count; ccc++)
            HttpContext.Current.Response.Write(mytable.Rows[rrr][ccc] + " | ");

public static void printTblRow(DataSet myDataset, int RowNum)
    printTblRow(myDataset.Tables[0], RowNum);
public static void printTblRow(DataTable mytable, int RowNum)
    for (int ccc = 0; ccc < mytable.Columns.Count; ccc++)
        Debug.Write(mytable.Columns[ccc].ToString() + " : ");

I then I will call one of the above functions in the immediate window and the results will appear there as well. For example if I want to see the contents of a variable 'myDataset' I will call printTbl(myDataset). After hitting enter, the results will be printed to the immediate window

What are the rules for JavaScript's automatic semicolon insertion (ASI)?

Regarding semicolon insertion and the var statement, beware forgetting the comma when using var but spanning multiple lines. Somebody found this in my code yesterday:

    var srcRecords = src.records
        srcIds = [];

It ran but the effect was that the srcIds declaration/assignment was global because the local declaration with var on the previous line no longer applied as that statement was considered finished due to automatic semi-colon insertion.

How to assign a heredoc value to a variable in Bash?

this bash trick
should preserve
newlines $TEST
long live perl
echo -e $MYTEXT

What is the --save option for npm install?

according to NPM Doc

enter image description here

So it seems that by running npm install package_name, the package dependency should be automatically added to package.json right?

Embed Youtube video inside an Android app

It works like this:

String item = "";

String ss = "your url";
ss = ss.substring(ss.indexOf("v=") + 2);
item += ss;
DisplayMetrics metrics = getResources().getDisplayMetrics();
int w1 = (int) (metrics.widthPixels / metrics.density), h1 = w1 * 3 / 5;

try {
    "<html><body><iframe class=\"youtube-player\" type=\"text/html5\" width=\""
    + (w1 - 20)
    + "\" height=\""
    + h1
    + "\" src=\""
    + item
    + "\" frameborder=\"0\"\"allowfullscreen\"></iframe></body></html>",
                            "text/html5", "utf-8");
} catch (Exception e) {

private WebChromeClient chromeClient = new WebChromeClient() {

    public void onShowCustomView(View view, CustomViewCallback callback) {
        super.onShowCustomView(view, callback);
        if (view instanceof FrameLayout) {
            FrameLayout frame = (FrameLayout) view;
            if (frame.getFocusedChild() instanceof VideoView) {
                VideoView video = (VideoView) frame.getFocusedChild();


Global Variable from a different file Python

When you write

from file2 import *

it actually copies the names defined in file2 into the namespace of file1. So if you reassign those names in file1, by writing

foo = "bar"

for example, it will only make that change in file1, not file2. Note that if you were to change an attribute of foo, say by doing

foo.blah = "bar"

then that change would be reflected in file2, because you are modifying the existing object referred to by the name foo, not replacing it with a new object.

You can get the effect you want by doing this in

import file2 = "bar"
test = SomeClass()

(note that you should delete from foo import *) although I would suggest thinking carefully about whether you really need to do this. It's not very common that changing one module's variables from within another module is really justified.

How To Upload Files on GitHub

Here are the steps (in-short), since I don't know what exactly you have done:
1. Download and install Git on your system:
2. Using the Git Bash (a command prompt for Git) or your system's native command prompt, set up a local git repository.
3. Use the same console to checkout, commit, push, etc. the files on the Git.

Hope this helps to those who come searching here.

Disable Drag and Drop on HTML elements?

You can disable dragging simply by using draggable="false" attribute.

How to turn on front flash light programmatically in Android?

I Got AutoFlash light with below simple Three Steps.

  • I just added Camera and Flash Permission in Manifest.xml file
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="" />

<uses-permission android:name="android.permission.FLASHLIGHT"/>
<uses-feature android:name="" android:required="false" />
  • In your Camera Code do this way.

    //Open Camera
    Camera  mCamera =; 
    //Get Camera Params for customisation
    Camera.Parameters parameters = mCamera.getParameters();
    //Check Whether device supports AutoFlash, If you YES then set AutoFlash
    List<String> flashModes = parameters.getSupportedFlashModes();
    if (flashModes.contains(android.hardware.Camera.Parameters.FLASH_MODE_AUTO))
  • Build + Run —> Now Go to Dim light area and Snap photo, you should get auto flash light if device supports.

How do I print the elements of a C++ vector in GDB?

'Watching' STL containers while debugging is somewhat of a problem. Here are 3 different solutions I have used in the past, none of them is perfect.

1) Use GDB scripts from These scripts allow you to print the contents of almost all STL containers. The problem is that this does not work for nested containers like a stack of sets.

2) Visual Studio 2005 has fantastic support for watching STL containers. This works for nested containers but this is for their implementation for STL only and does not work if you are putting a STL container in a Boost container.

3) Write your own 'print' function (or method) for the specific item you want to print while debugging and use 'call' while in GDB to print the item. Note that if your print function is not being called anywhere in the code g++ will do dead code elimination and the 'print' function will not be found by GDB (you will get a message saying that the function is inlined). So compile with -fkeep-inline-functions

What is SuppressWarnings ("unchecked") in Java?

It could also mean that the current Java type system version isn't good enough for your case. There were several JSR propositions / hacks to fix this: Type tokens, Super Type Tokens, Class.cast().

If you really need this supression, narrow it down as much as possible (e.g. don't put it onto the class itself or onto a long method). An example:

public List<String> getALegacyListReversed() {
   @SuppressWarnings("unchecked") List<String> list =

   return list;

Chrome Fullscreen API

The following test works in Chrome 16 (dev branch) on X86 and Chrome 15 on Mac OSX Lion

m2e error in MavenArchiver.getManifest()

I had also faced the same issue and it got resolved by commenting the version element in POM.xml as show.

org.apache.maven.archiver.[MavenArchiver](, org.apache.maven.archiver.MavenArchiveConfiguration)

    <!-- <version>3.5.1</version> -->
    <!-- <version>3.1.0</version> -->

How do I properly force a Git push?

And if push --force doesn't work you can do push --delete. Look at 2nd line on this instance:

git reset --hard HEAD~3  # reset current branch to 3 commits ago
git push origin master --delete  # do a very very bad bad thing
git push origin master  # regular push

But beware...

Never ever go back on a public git history!

In other words:

  • Don't ever force push on a public repository.
  • Don't do this or anything that can break someone's pull.
  • Don't ever reset or rewrite history in a repo someone might have already pulled.

Of course there are exceptionally rare exceptions even to this rule, but in most cases it's not needed to do it and it will generate problems to everyone else.

Do a revert instead.

And always be careful with what you push to a public repo. Reverting:

git revert -n HEAD~3..HEAD  # prepare a new commit reverting last 3 commits
git commit -m "sorry - revert last 3 commits because I was not careful"
git push origin master  # regular push

In effect, both origin HEADs (from the revert and from the evil reset) will contain the same files.

edit to add updated info and more arguments around push --force

Consider pushing force with lease instead of push, but still prefer revert

Another problem push --force may bring is when someone push anything before you do, but after you've already fetched. If you push force your rebased version now you will replace work from others.

git push --force-with-lease introduced in the git 1.8.5 (thanks to @VonC comment on the question) tries to address this specific issue. Basically, it will bring an error and not push if the remote was modified since your latest fetch.

This is good if you're really sure a push --force is needed, but still want to prevent more problems. I'd go as far to say it should be the default push --force behaviour. But it's still far from being an excuse to force a push. People who fetched before your rebase will still have lots of troubles, which could be easily avoided if you had reverted instead.

And since we're talking about git --push instances...

Why would anyone want to force push?

@linquize brought a good push force example on the comments: sensitive data. You've wrongly leaked data that shouldn't be pushed. If you're fast enough, you can "fix"* it by forcing a push on top.

* The data will still be on the remote unless you also do a garbage collect, or clean it somehow. There is also the obvious potential for it to be spread by others who'd fetched it already, but you get the idea.

Detect if a page has a vertical scrollbar?

I found vanila solution

var hasScrollbar = function() {_x000D_
  // The Modern solution_x000D_
  if (typeof window.innerWidth === 'number')_x000D_
    return window.innerWidth > document.documentElement.clientWidth_x000D_
  // rootElem for quirksmode_x000D_
  var rootElem = document.documentElement || document.body_x000D_
  // Check overflow style property on body for fauxscrollbars_x000D_
  var overflowStyle_x000D_
  if (typeof rootElem.currentStyle !== 'undefined')_x000D_
    overflowStyle = rootElem.currentStyle.overflow_x000D_
  overflowStyle = overflowStyle || window.getComputedStyle(rootElem, '').overflow_x000D_
    // Also need to check the Y axis overflow_x000D_
  var overflowYStyle_x000D_
  if (typeof rootElem.currentStyle !== 'undefined')_x000D_
    overflowYStyle = rootElem.currentStyle.overflowY_x000D_
  overflowYStyle = overflowYStyle || window.getComputedStyle(rootElem, '').overflowY_x000D_
  var contentOverflows = rootElem.scrollHeight > rootElem.clientHeight_x000D_
  var overflowShown    = /^(visible|auto)$/.test(overflowStyle) || /^(visible|auto)$/.test(overflowYStyle)_x000D_
  var alwaysShowScroll = overflowStyle === 'scroll' || overflowYStyle === 'scroll'_x000D_
  return (contentOverflows && overflowShown) || (alwaysShowScroll)_x000D_

HTML Table cellspacing or padding just top / bottom

This might be a little better:

td {
  padding:2px 0;

Script not served by static file handler on IIS7.5

Navigate to your flavor of .Net and CPU architecture directory using CMD or powershell

Enter this command: aspnet_regiis –r

Can my enums have friendly names?

One problem with this trick is that description attribute cannot be localized. I do like a technique by Sacha Barber where he creates his own version of Description attribute which would pick up values from the corresponding resource manager.

Although the article is around a problem that's generally faced by WPF developers when binding to enums, you can jump directly to the part where he creates the LocalizableDescriptionAttribute.

multiple where condition codeigniter

Try this

$data = array(
               'email' =>$email,
               'last_ip' => $last_ip

$where = array('username ' => $username , 'status ' => $status);
$this->db->update('table_user ', $data); 

How to directly initialize a HashMap (in a literal way)?


In plain java 8 you also have the possibility of using Streams/Collectors to do the job.

Map<String, String> myMap = Stream.of(
         new SimpleEntry<>("key1", "value1"),
         new SimpleEntry<>("key2", "value2"),
         new SimpleEntry<>("key3", "value3"))
        .collect(toMap(SimpleEntry::getKey, SimpleEntry::getValue));

This has the advantage of not creating an Anonymous class.

Note that the imports are:

import static;
import java.util.AbstractMap.SimpleEntry;

Of course, as noted in other answers, in java 9 onwards you have simpler ways of doing the same.

How to call a stored procedure from Java and JPA

JPA 2.0 doesn't support RETURN values, only calls.

My solution was. Create a FUNCTION calling PROCEDURE.

So, inside JAVA code you execute a NATIVE QUERY calling the oracle FUNCTION.

issue ORA-00001: unique constraint violated coming in INSERT/UPDATE

This ORA error is occurred because of violation of unique constraint.

ORA-00001: unique constraint (constraint_name) violated

This is caused because of trying to execute an INSERT or UPDATE statement that has created a duplicate value in a field restricted by a unique index.

You can resolve this either by

  • changing the constraint to allow duplicates, or
  • drop the unique constraint or you can change your SQL to avoid duplicate inserts

How can I remove the outline around hyperlinks images?

You can put overflow:hidden onto the property with the text indent, and that dotted line, that spans out of the page, will dissapear.

I've seen a couple of posts about removing outlines all together. Be careful when doing this as you could lower the accessibility of the site.

a:active { outline: none; }

I personally would use this attribute only, as if the :hover attribute has the same css properties it will prevent the outlines showing for people who are using the keyboard for navigation.

Hope this solves your problem.

html5 audio player - jquery toggle click play/pause?

You can call native methods trough trigger in jQuery. Just do this:


And the same for pause: $('.play').trigger("pause");

EDIT: as F... pointed out in the comments, you can do something similar to access properties: $('.play').prop("paused");

How to add an existing folder with files to SVN?

In Windows 7 I did this:

  1. Have you installed SVN and Tortoise SVN? If not, Google them and do so now.
  2. Go to your SVN folder where you may have other repos (short for repository) (or if you're creating one from scratch, choose a location C drive, D drive, etc or network path).
  3. Create a new folder to store your new repository. Call it the same name as your project title
  4. Right click the folder and choose Tortoise SVN -> Create Repository here
  5. Say yes to Create Folder Structure
  6. Click OK. You should see a new icon looking like a "wave" next to your new folder/repo
  7. Right Click the new repo and choose SVN Repo Browser
  8. Right click 'trunk'
  9. Choose ADD Folder... and point to your folder structure of your project in development.
  10. Click OK and SVN will ADD your folder structure in. Be patient! It looks like SVN has crashed/frozen. Don't worry. It's doing its work.


How to specify the bottom border of a <tr>?

Try the following instead:

  <title>Table row styling</title>
  <style type="text/css">
    .bb td, .bb th {
     border-bottom: 1px solid black !important;
    <tr class="bb">

How to place a file on classpath in Eclipse?

Copy the file into your src folder. Go to the Project Explorer in Eclipse, Right-click on your project, and click on "Refresh". The file should appear on the Project Explorer pane as well.

Converting .NET DateTime to JSON

Thought i'd add my solution that i've been using.

If you're using the System.Web.Script.Serialization.JavaScriptSerializer() then the time returned isn't going to be specific to your timezone. To fix this you'll also want to use dte.getTimezoneOffset() to get it back to your correct time.

String.prototype.toDateFromAspNet = function() {
    var dte = eval("new " + this.replace(/\//g, '') + ";");
    dte.setMinutes(dte.getMinutes() - dte.getTimezoneOffset());
    return dte;

now you'll just call


Fri Jun 19 2009 00:04:53 GMT-0400 (Eastern Daylight Time) {}

How to keep footer at bottom of screen


<div id="footer"></div>


#footer {

Find file in directory from command line

When I was in the UNIX world (using tcsh (sigh...)), I used to have all sorts of "find" aliases/scripts setup for searching for files. I think the default "find" syntax is a little clunky, so I used to have aliases/scripts to pipe "find . -print" into grep, which allows you to use regular expressions for searching:

# finds all .java files starting in current directory
find . -print | grep '\.java'

#finds all .java files whose name contains "Message"
find . -print | grep '.*Message.*\.java'

Of course, the above examples can be done with plain-old find, but if you have a more specific search, grep can help quite a bit. This works pretty well, unless "find . -print" has too many directories to recurse through... then it gets pretty slow. (for example, you wouldn't want to do this starting in root "/")