Programs & Examples On #Linode

Linode (a contraction of Linux Node) is a virtual private server web hosting and cloud computing provider based in Galloway Township, New Jersey.

Downloading MySQL dump from command line

In latest versions of mysql, at least in mine, you cannot put your pass in the command directly.

You have to run:

mysqldump -u [uname] -p db_name > db_backup.sql

and then it will ask for the password.

ssh server connect to host xxx port 22: Connection timed out on linux-ubuntu

I faced a similar issue. I checked for the below:

  1. if ssh is not installed on your machine, you will have to install it firstly. (You will get a message saying ssh is not recognized as a command).
  2. Port 22 is open or not on the server you are trying to ssh.
  3. If the control of remote server is in your hands and you have permissions, try to disable firewall on it.
  4. Try to ssh again.

If port is not an issue then you would have to check for firewall settings as it is the one that is blocking your connection.

For me too it was a firewall issue between my machine and remote server.I disabled the firewall on the remote server and I was able to make a connection using ssh.

How to prevent a double-click using jQuery?

"Easy Peasy"

$(function() {

How to make button fill table cell

For starters:

<p align='center'>
<table width='100%'>
<td align='center'><form><input type=submit value="click me" style="width:100%"></form></td>

Note, if the width of the input button is 100%, you wont need the attribute "align='center'" anymore.

This would be the optimal solution:

<p align='center'>
<table width='100%'>
<td><form><input type=submit value="click me" style="width:100%"></form></td>

Chrome / Safari not filling 100% height of flex parent

I have had a similar issue in iOS 8, 9 and 10 and the info above couldn't fix it, however I did discover a solution after a day of working on this. Granted it won't work for everyone but in my case my items were stacked in a column and had 0 height when it should have been content height. Switching the css to be row and wrap fixed the issue. This only works if you have a single item and they are stacked but since it took me a day to find this out I thought I should share my fix!

.wrapper {
    flex-direction: column; // <-- Remove this line
    flex-direction: row; // <-- replace it with
    flex-wrap: wrap; // <-- Add wrapping

.item {
    width: 100%;

Spring Security redirect to previous page after successful login

I have following solution and it worked for me.

Whenever login page is requested, write the referer value to the session:

@RequestMapping(value="/login", method = RequestMethod.GET)
public String login(ModelMap model,HttpServletRequest request) {

    String referrer = request.getHeader("Referer");
        request.getSession().setAttribute("url_prior_login", referrer);
    return "user/login";

Then, after successful login custom implementation of SavedRequestAwareAuthenticationSuccessHandler will redirect user to the previous page:

HttpSession session = request.getSession(false);
if (session != null) {
    url = (String) request.getSession().getAttribute("url_prior_login");

Redirect the user:

if (url != null) {

receiving json and deserializing as List of object at spring mvc controller

public List<String> savePerson(@RequestBody Person[] personArray) {
    List<String> response = new ArrayList<String>();
    for (Person person: personArray) {;
        response.add("Saved person: " + person.toString());
    return response;

We can use Array as shown above.

How to watch for array changes?

Not sure if this covers absolutely everything, but I use something like this (especially when debugging) to detect when an array has an element added:

var array = [1,2,3,4];
array = new Proxy(array, {
    set: function(target, key, value) {
        if (Number.isInteger(Number(key)) || key === 'length') {
            debugger; //or other code
        target[key] = value;
        return true;

error: expected class-name before ‘{’ token

I got the same error with a different problem,

I used namespaces in my headers and forgot the closing bracket and got this cryptic error instead.

Fitting a density curve to a histogram in R

Here's the way I do it:

foo <- rnorm(100, mean=1, sd=2)
hist(foo, prob=TRUE)
curve(dnorm(x, mean=mean(foo), sd=sd(foo)), add=TRUE)

A bonus exercise is to do this with ggplot2 package ...

How can I toggle word wrap in Visual Studio?


When viewing a document: Edit / Advanced / Word Wrap (Ctrl+E, Ctrl+W)

General settings: Tools / Options / Text Editor / All Languages / Word wrap

Or search for 'word wrap' in the Quick Launch box.

Known issues:

If you're familiar with word wrap in Notepad++, Sublime Text, or Visual Studio Code, be aware of the following issues where Visual Studio behaves differently to other editors:

  1. Triple click doesn't select whole line
  2. Cut command doesn't delete whole line
  3. Pressing End key twice does not move cursor to end of line

Unfortunately these bugs have been closed "lower priority". If you'd like these bugs fixed, please vote for the feature request Fix known issues with word wrap.

Compare dates with javascript

You can do this way, it will work fine:

var date1 = new Date('2013-07-30');
var date2 = new Date('2013-07-30');

if(date1 === date2){ console.log("both are equal");}  //it does not work 
==>undefined  //result
if(+date1 === +date2){ console.log("both are equal");} //do it this way! 
//(use + prefix for a variable that holds a date value)
==> both are equal //result

Note :- don't forget to use a + prefix

when do you need .ascx files and how would you use them?

One more use of .ascx files is, they can be used for Partial Page caching in ASP.NET pages. What we have to do is to create an ascx file and then move the controls or portion of the page we need to cache into that control. Then add the @OutputCache directive in the ascx control and it will be cached separately from the parent page. It is used when you don't want to cache the whole page but only a specific portion of the page.

What is difference between XML Schema and DTD?

Differences between an XML Schema Definition (XSD) and Document Type Definition (DTD) include:

  • XML schemas are written in XML while DTD are derived from SGML syntax.
  • XML schemas define datatypes for elements and attributes while DTD doesn't support datatypes.
  • XML schemas allow support for namespaces while DTD does not.
  • XML schemas define number and order of child elements, while DTD does not.
  • XML schemas can be manipulated on your own with XML DOM but it is not possible in case of DTD.
  • using XML schema user need not to learn a new language but working with DTD is difficult for a user.
  • XML schema provides secure data communication i.e sender can describe the data in a way that receiver will understand, but in case of DTD data can be misunderstood by the receiver.
  • XML schemas are extensible while DTD is not extensible.

Not all these bullet points are 100% accurate, but you get the gist.

On the other hand:

  • DTD lets you define new ENTITY values for use in your XML file.
  • DTD lets you extend it local to an individual XML file.

find path of current folder - cmd

for /f "delims=" %%i in ("%0") do set "curpath=%%~dpi"
echo "%curpath%"


echo "%cd%"

The double quotes are needed if the path contains any & characters.

How to remove a field completely from a MongoDB document?

you can also do this in aggregation by using project at 3.4

{$project: {"tags.words": 0} }

Why should I use a container div in HTML?

Certain browsers (<cough> Internet Explorer) don't support certain properties on the body, notably width and max-width.

Attempted to read or write protected memory

The problem may be due to mixed build platforms DLLs in the project. i.e You build your project to Any CPU but have some DLLs in the project already built for x86 platform. These will cause random crashes because of different memory mapping of 32bit and 64bit architecture. If all the DLLs are built for one platform the problem can be solved. For safety try bulinding for 32bit x86 architecture because it is the most compatible.

How to call a shell script from python code?

Subprocess is good but some people may like scriptine better. Scriptine has more high-level set of methods like, path.rename(new_name) and path.move(src,dst). Scriptine is based on subprocess and others.

Two drawbacks of scriptine:

  • Current documentation level would be more comprehensive even though it is sufficient.
  • Unlike subprocess, scriptine package is currently not installed by default.

How to index into a dictionary?

Addressing an element of dictionary is like sitting on donkey and enjoy the ride.

As a rule of Python, a DICTIONARY is orderless

If there is

dic = {1: "a", 2: "aa", 3: "aaa"}

Now suppose if I go like dic[10] = "b", then it will not add like this always

dic = {1:"a",2:"aa",3:"aaa",10:"b"}

It may be like

dic = {1: "a", 2: "aa", 3: "aaa", 10: "b"}


dic = {1: "a", 2: "aa", 10: "b", 3: "aaa"}


dic = {1: "a", 10: "b", 2: "aa", 3: "aaa"}

Or any such combination.

So a rule of thumb is that a DICTIONARY is orderless!

Handling exceptions from Java ExecutorService tasks

This is because of AbstractExecutorService :: submit is wrapping your runnable into RunnableFuture (nothing but FutureTask) like below

public Future<?> submit(Runnable task) {
    if (task == null) throw new NullPointerException();
    RunnableFuture<Void> ftask = newTaskFor(task, null); /////////HERE////////
    return ftask;

Then execute will pass it to Worker and will call the below.

final void runWorker(Worker w) {
    Thread wt = Thread.currentThread();
    Runnable task = w.firstTask;
    w.firstTask = null;
    w.unlock(); // allow interrupts
    boolean completedAbruptly = true;
    try {
        while (task != null || (task = getTask()) != null) {
            // If pool is stopping, ensure thread is interrupted;
            // if not, ensure thread is not interrupted.  This
            // requires a recheck in second case to deal with
            // shutdownNow race while clearing interrupt
            if ((runStateAtLeast(ctl.get(), STOP) ||
                 (Thread.interrupted() &&
                  runStateAtLeast(ctl.get(), STOP))) &&
            try {
                beforeExecute(wt, task);
                Throwable thrown = null;
                try {
          ;           /////////HERE////////
                } catch (RuntimeException x) {
                    thrown = x; throw x;
                } catch (Error x) {
                    thrown = x; throw x;
                } catch (Throwable x) {
                    thrown = x; throw new Error(x);
                } finally {
                    afterExecute(task, thrown);
            } finally {
                task = null;
        completedAbruptly = false;
    } finally {
        processWorkerExit(w, completedAbruptly);

Finally; in the above code call will call Here is the exception handler code, because of this you are NOT getting the expected exception.

class FutureTask<V> implements RunnableFuture<V>

public void run() {
    if (state != NEW ||
        !UNSAFE.compareAndSwapObject(this, runnerOffset,
                                     null, Thread.currentThread()))
    try {
        Callable<V> c = callable;
        if (c != null && state == NEW) {
            V result;
            boolean ran;
            try {
                result =;
                ran = true;
            } catch (Throwable ex) {   /////////HERE////////
                result = null;
                ran = false;
            if (ran)
    } finally {
        // runner must be non-null until state is settled to
        // prevent concurrent calls to run()
        runner = null;
        // state must be re-read after nulling runner to prevent
        // leaked interrupts
        int s = state;
        if (s >= INTERRUPTING)

How to get size in bytes of a CLOB column in Oracle?

I'm adding my comment as an answer because it solves the original problem for a wider range of cases than the accepted answer. Note: you must still know the maximum length and the approximate proportion of multi-byte characters that your data will have.

If you have a CLOB greater than 4000 bytes, you need to use DBMS_LOB.SUBSTR rather than SUBSTR. Note that the amount and offset parameters are reversed in DBMS_LOB.SUBSTR.

Next, you may need to substring an amount less than 4000, because this parameter is the number of characters, and if you have multi-byte characters then 4000 characters will be more than 4000 bytes long, and you'll get ORA-06502: PL/SQL: numeric or value error: character string buffer too small because the substring result needs to fit in a VARCHAR2 which has a 4000 byte limit. Exactly how many characters you can retrieve depends on the average number of bytes per character in your data.

So my answer is:


where you add as many chunks as you need to cover your longest CLOB, and adjust the chunk size according to average bytes-per-character of your data.

How to remove blank lines from a Unix file

with awk

awk 'NF > 0' filename

Converting dictionary to JSON

No need to convert it in a string by using json.dumps()

r = {'is_claimed': 'True', 'rating': 3.5}

You can get the values directly from the dict object.

Rails has_many with alias name

You could also use alias_attribute if you still want to be able to refer to them as tasks as well:

class User < ActiveRecord::Base
  alias_attribute :jobs, :tasks

  has_many :tasks

How to analyze a JMeter summary report?

Sample: Number of requests sent.

The Throughput: is the number of requests per unit of time (seconds, minutes, hours) that are sent to your server during the test.

The Response time: is the elapsed time from the moment when a given request is sent to the server until the moment when the last bit of information has returned to the client.

The throughput is the real load processed by your server during a run but it does not tell you anything about the performance of your server during this same run. This is the reason why you need both measures in order to get a real idea about your server’s performance during a run. The response time tells you how fast your server is handling a given load.

Average: This is the Average (Arithmetic mean µ = 1/n * Si=1…n xi) Response time of your total samples.

Min and Max are the minimum and maximum response time.

An important thing to understand is that the mean value can be very misleading as it does not show you how close (or far) your values are from the average.For this purpose, we need the Deviation value since Average value can be the Same for different response time of the samples!!

Deviation: The standard deviation (s) measures the mean distance of the values to their average (µ).It gives you a good idea of the dispersion or variability of the measures to their mean value.

The following equation show how the standard deviation (s) is calculated:

s = 1/n * v Si=1…n (xi-µ)2

For Details, see here!!

So, if the deviation value is low compared to the mean value, it will indicate you that your measures are not dispersed (or mostly close to the mean value) and that the mean value is significant.

Kb/sec: The throughput measured in Kilobytes per second.

Error % : Percent of requests with errors.

An example is always better to understand!!! I think, this article will help you.

What does the PHP error message "Notice: Use of undefined constant" mean?

Looks like the predefined fetch constants went away with the MySQL extension, so we need to add them before the first function...

//predifined fetch constants


I tested and succeeded.

Passing dynamic javascript values using Url.action()

In my case it worked great just by doing the following:

The Controller:

public ActionResult DoSomething(int custNum)
    // Some magic code here...

Create the form with no action:

<form id="frmSomething" method="post">
        <!-- Some magic html here... -->
    <button id="btnSubmit" type="submit">Submit</button>

Set button click event to trigger submit after adding the action to the form:

var frmSomething= $("#frmSomething");
var btnSubmit= $("#btnSubmit");
var custNum = 100;
        frmSomething.attr("action", "/Home/DoSomething?custNum=" + custNum);


Hope this helps vatos!

How to get the Display Name Attribute of an Enum member via MVC Razor code?

    @foreach (int aPromotion in @Enum.GetValues(typeof(UserPromotion)))
        var currentPromotion = (int)Model.JobSeeker.Promotion;
        if ((currentPromotion & aPromotion) == aPromotion)
        <li>@Html.DisplayFor(e => currentPromotion)</li>

How to send list of file in a folder to a txt file in Linux

you can just use

ls > filenames.txt

(usually, start a shell by using "Terminal", or "shell", or "Bash".) You may need to use cd to go to that folder first, or you can ls ~/docs > filenames.txt

Print out the values of a (Mat) matrix in OpenCV C++

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

#include <iostream>
#include <iomanip>

using namespace cv;
using namespace std;

int main(int argc, char** argv)
    double data[4] = {-0.0000000077898273846583732, -0.03749374753019832, -0.0374787251930463, -0.000000000077893623846343843};
    Mat src = Mat(1, 4, CV_64F, &data);
    for(int i=0; i<4; i++)
        cout << setprecision(3) <<<double>(0,i) << endl;

    return 0;

How to delete mysql database through shell command

You can remove database directly as:

$ mysqladmin -h [host] -u [user] -p drop [database_name]

[Enter Password]

Do you really want to drop the 'hairfree' database [y/N]: y

How to force a line break on a Javascript concatenated string?

Using Backtick

Backticks are commonly used for multi-line strings or when you want to interpolate an expression within your string

let title = 'John';_x000D_
let address = 'address';_x000D_
let address2 = 'address2222';_x000D_
let address3 = 'address33333';_x000D_
let address4 = 'address44444';_x000D_
document.getElementById("address_box").innerText = `${title} _x000D_
${address3} _x000D_
<div id="address_box">_x000D_

How to switch between python 2.7 to python 3 from command line?

No need for "tricks". Python 3.3 comes with PyLauncher "py.exe", installs it in the path, and registers it as the ".py" extension handler. With it, a special comment at the top of a script tells the launcher which version of Python to run:

print "hello"



From the command line:

py -3


py -2

py by itself will choose the latest Python installed, or consult the PY_PYTHON environment variable, e.g. set PY_PYTHON=3.6.

See Python Launcher for Windows

How to check if a line is blank using regex

Here Blank mean what you are meaning.
A line contains full of whitespaces or a line contains nothing.
If you want to match a line which contains nothing then use '/^$/'.

How can I generate random number in specific range in Android?

int min = 65;
int max = 80;

Random r = new Random();
int i1 = r.nextInt(max - min + 1) + min;

Note that nextInt(int max) returns an int between 0 inclusive and max exclusive. Hence the +1.

Looping over elements in jQuery

This is the simplest way to loop through a form accessing only the form elements. Inside the each function you can check and build whatever you want. When building objects note that you will want to declare it outside of the each function.


The below will work

$('form[name=formName]').find('input, textarea, select').each(function() {
}); cannot open shared object file: No such file or directory

For Red Hat :

sudo yum install libstdc++.i686
sudo yum install libstdc++-devel.i686

How to see indexes for a database or table in MySQL?

To get all indexed columns per index in one column in the sequence order.

SELECT table_name AS `Table`,
       index_name AS `Index`,
       GROUP_CONCAT(column_name ORDER BY seq_in_index) AS `Columns`
FROM information_schema.statistics
WHERE table_schema = 'sakila'


How to split large text file in windows?

Set Arg = WScript.Arguments
set WshShell = createObject("Wscript.Shell")
Set Inp = WScript.Stdin
Set Outp = Wscript.Stdout
    Set rs = CreateObject("ADODB.Recordset")
    With rs
        .Fields.Append "LineNumber", 4 

        .Fields.Append "Txt", 201, 5000 
        LineCount = 0
        Do Until Inp.AtEndOfStream
            LineCount = LineCount + 1
            .Fields("LineNumber").value = LineCount
            .Fields("Txt").value = Inp.readline

        .Sort = "LineNumber ASC"

        If LCase(Arg(1)) = "t" then
            If LCase(Arg(2)) = "i" then
                .filter = "LineNumber < " & LCase(Arg(3)) + 1
            ElseIf LCase(Arg(2)) = "x" then
                .filter = "LineNumber > " & LCase(Arg(3))
            End If
        ElseIf LCase(Arg(1)) = "b" then
            If LCase(Arg(2)) = "i" then
                .filter = "LineNumber > " & LineCount - LCase(Arg(3))
            ElseIf LCase(Arg(2)) = "x" then
                .filter = "LineNumber < " & LineCount - LCase(Arg(3)) + 1
            End If
        End If

        Do While not .EOF
            Outp.writeline .Fields("Txt").Value

    End With


filter cut {t|b} {i|x} NumOfLines

Cuts the number of lines from the top or bottom of file.

t - top of the file
b - bottom of the file
i - include n lines
x - exclude n lines


cscript /nologo filter.vbs cut t i 5 < "%systemroot%\win.ini"

Another way This outputs lines 5001+, adapt for your use. This uses almost no memory.

Do Until Inp.AtEndOfStream
         Count = Count + 1
         If count > 5000 then
            OutP.WriteLine Inp.Readline
         End If

MySQL - SELECT all columns WHERE one column is DISTINCT

  SELECT DISTINCT link FROM posted WHERE ad='$key' )
  ORDER BY day, month

How to export the Html Tables data into PDF using Jspdf

"How to properly use jsPDF library" might give you a little more of what you need. The table won't render correctly (no css, per this answer), but you could do some parsing of the html table with jquery and manually style it yourself.

Another option would be to use screenshots of the HTML with HTML2Canvas or Casper.js.


Here's a basic example using the jspdf cell plugin. It uses jquery and the tableToJson() function from HTML Table to JSON.

Be sure to include the Deflate lib (two js files) and jspdf.plugin.cell.js.

var table = tableToJson($('#table-id').get(0))
var doc = new jsPDF('p', 'pt', 'a4', true);
$.each(table, function (i, row){
  $.each(row, function (j, cell){
    doc.cell(10, 200, 100, 20, cell, i);

how to remove "," from a string in javascript

You aren't assigning the result of the replace method back to your variable. When you call replace, it returns a new string without modifying the old one.

For example, load this into your favorite browser:

    <script type="text/javascript">
        var str1 = "a,d,k";
        var str2 = str1.replace(/\,/g,"");
        alert (str1);
        alert (str2);

In this case, str1 will still be "a,d,k" and str2 will be "adk".

If you want to change str1, you should be doing:

var str1 = "a,d,k";
str1 = str1.replace (/,/g, "");

Objective-C Static Class Level variables

As of Xcode 8, you can define class properties in Obj-C. This has been added to interoperate with Swift's static properties.

Objective-C now supports class properties, which interoperate with Swift type properties. They are declared as: @property (class) NSString *someStringProperty;. They are never synthesized. (23891898)

Here is an example

@interface YourClass : NSObject

@property (class, nonatomic, assign) NSInteger currentId;


@implementation YourClass

static NSInteger _currentId = 0;

+ (NSInteger)currentId {
    return _currentId;

+ (void)setCurrentId:(NSInteger)newValue {
    _currentId = newValue;


Then you can access it like this:

YourClass.currentId = 1;
val = YourClass.currentId;

Here is a very interesting explanatory post I used as a reference to edit this old answer.

2011 Answer: (don't use this, it's terrible)

If you really really don't want to declare a global variable, there another option, maybe not very orthodox :-), but works... You can declare a "get&set" method like this, with an static variable inside:

+ (NSString*)testHolder:(NSString*)_test {
    static NSString *test;

    if(_test != nil) {
        if(test != nil)
            [test release];
        test = [_test retain];

    // if(test == nil)
    //     test = @"Initialize the var here if you need to";

    return test;

So, if you need to get the value, just call:

NSString *testVal = [MyClass testHolder:nil]

And then, when you want to set it:

[MyClass testHolder:testVal]

In the case you want to be able to set this pseudo-static-var to nil, you can declare testHolder as this:

+ (NSString*)testHolderSet:(BOOL)shouldSet newValue:(NSString*)_test {
    static NSString *test;

    if(shouldSet) {
        if(test != nil)
            [test release];
        test = [_test retain];

    return test;

And two handy methods:

+ (NSString*)test {
    return [MyClass testHolderSet:NO newValue:nil];

+ (void)setTest:(NSString*)_test {
    [MyClass testHolderSet:YES newValue:_test];

Hope it helps! Good luck.

How can I pass data from Flask to JavaScript in a template?

Alternatively you could add an endpoint to return your variable:

def geo_code():
    return jsonify(geocode)

Then do an XHR to retrieve it:

  .then((res)=>{ console.log(res) })

Add bottom line to view in SwiftUI / Swift / Objective-C / Xamarin

You can create this extension outside class and replace width with whatever borderWidth you want.

Swift 4

extension UITextField
    func setBottomBorder(withColor color: UIColor)
        self.borderStyle = UITextBorderStyle.none
        self.backgroundColor = UIColor.clear
        let width: CGFloat = 1.0

        let borderLine = UIView(frame: CGRect(x: 0, y: self.frame.height - width, width: self.frame.width, height: width))
        borderLine.backgroundColor = color


extension UITextField
    func setBottomBorder(borderColor: UIColor)
        self.borderStyle = UITextBorderStyle.None
        self.backgroundColor = UIColor.clearColor()
        let width = 1.0

        let borderLine = UIView(frame: CGRectMake(0, self.frame.height - width, self.frame.width, width))
        borderLine.backgroundColor = borderColor

and then add this to your viewDidLoad replacing yourTextField with your UITextField variable and with any color you want in the border


This basically adds a view with that color at the bottom of the text field.

Appending a vector to a vector

std::copy (b.begin(), b.end(), std::back_inserter(a));

This can be used in case the items in vector a have no assignment operator (e.g. const member).

In all other cases this solution is ineffiecent compared to the above insert solution.

How to exit from ForEach-Object in PowerShell

Below is a suggested approach to Question #1 which I use if I wish to use the ForEach-Object cmdlet. It does not directly answer the question because it does not EXIT the pipeline. However, it may achieve the desired effect in Q#1. The only drawback an amateur like myself can see is when processing large pipeline iterations.

    $zStop = $false
    (97..122) | Where-Object {$zStop -eq $false} | ForEach-Object {
    $zNumeric = $_
    $zAlpha = [char]$zNumeric
    Write-Host -ForegroundColor Yellow ("{0,4} = {1}" -f ($zNumeric, $zAlpha))
    if ($zAlpha -eq "m") {$zStop = $true}
    Write-Host -ForegroundColor Green "My PSVersion = 5.1.18362.145"

I hope this is of use. Happy New Year to all.

How schedule build in Jenkins?

Jenkins uses Cron Expressions.

You can simply schedule hourly builds by just typing@hourly.

How to enable cross-origin resource sharing (CORS) in the express.js framework on node.js

Check out the example from

In your ExpressJS app on node.js, do the following with your routes:

app.all('/', function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");

app.get('/', function(req, res, next) {
  // Handle the get for this route
});'/', function(req, res, next) {
 // Handle the post for this route

The first call (app.all) should be made before all the other routes in your app (or at least the ones you want to be CORS enabled).


If you want the headers to show up for static files as well, try this (make sure it's before the call to use(express.static()):

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");

I tested this with your code, and got the headers on assets from the public directory:

var express = require('express')
  , app = express.createServer();

app.configure(function () {
    app.use(function(req, res, next) {
      res.header("Access-Control-Allow-Origin", "*");
      res.header("Access-Control-Allow-Headers", "X-Requested-With");

app.configure('development', function () {
    app.use(express.static(__dirname + '/public'));
    app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));

app.configure('production', function () {
    app.use(express.static(__dirname + '/public'));

console.log('express running at http://localhost:%d', 8888);

You could, of course, package the function up into a module so you can do something like

// cors.js

module.exports = function() {
  return function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");

// server.js

cors = require('./cors');

How to view query error in PDO PHP

a quick way to see your errors whilst testing:

$error= $st->errorInfo();
echo $error[2];

How is the AND/OR operator represented as in Regular Expressions?


does it work?

Difference between os.getenv and os.environ.get

In addition to the answers above:

$ python3 -m timeit -s 'import os' 'os.environ.get("TERM_PROGRAM")'
200000 loops, best of 5: 1.65 usec per loop

$ python3 -m timeit -s 'import os' 'os.getenv("TERM_PROGRAM")'
200000 loops, best of 5: 1.83 usec per loop


It means that the delegate you pass is executed on the thread that created the Control object (which is the UI thread).

You need to call this method when your application is multi-threaded and you want do some UI operation from a thread other than the UI thread, because if you just try to call a method on a Control from a different thread you'll get a System.InvalidOperationException.

How to tell if a JavaScript function is defined

typeof(callback) == "function"

Can I grep only the first n lines of a file?

head -10 log.txt | grep -A 2 -B 2 pattern_to_search

-A 2: print two lines before the pattern.

-B 2: print two lines after the pattern.

head -10 log.txt # read the first 10 lines of the file.

Call PHP function from Twig template

I am surprised the code answer is not posted already, it's a one liner.

You could just {{ categeory_id | getVariations }}

It's a one-liner:

$twig->addFilter('getVariations', new Twig_Filter_Function('getVariations'));

Get characters after last / in url

$str = "";
$s = explode("/",$str);
print end($s);

Inserting into Oracle and retrieving the generated sequence ID

You can use the below statement to get the inserted Id to a variable-like thing.

INSERT INTO  YOUR_TABLE(ID) VALUES ('10') returning ID into :Inserted_Value;

Now you can retrieve the value using the below statement

SELECT :Inserted_Value FROM DUAL;

git returns http error 407 from proxy after CONNECT

The following command is needed to force git to send the credentials and authentication method to the proxy:

git config --global http.proxyAuthMethod 'basic'


How to right align widget in horizontal linear layout Android?

Do not change the gravity of the LinearLayout to "right" if you don't want everything to be to the right.


  1. Change TextView's width to fill_parent
  2. Change TextView's gravity to right



ImportError: No module named - Python

Make sure if root project directory is coming up in sys.path output. If not, please add path of root project directory to sys.path.

How to check if an integer is in a given range?

If you are confident that numbers are stored in 2's complement form:

return  ((x-low) <= (high-low));

A more general and safer solution would be:

return ((x-high)*(x-low) <= 0);

Generating random, unique values C#

Depending on what you are really after you can do something like this:

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

namespace SO14473321
    class Program
        static void Main()
            UniqueRandom u = new UniqueRandom(Enumerable.Range(1,10));
            for (int i = 0; i < 10; i++)
                Console.Write("{0} ",u.Next());

    class UniqueRandom
        private readonly List<int> _currentList;
        private readonly Random _random = new Random();

        public UniqueRandom(IEnumerable<int> seed)
            _currentList = new List<int>(seed);

        public int Next()
            if (_currentList.Count == 0)
                throw new ApplicationException("No more numbers");

            int i = _random.Next(_currentList.Count);
            int result = _currentList[i];
            return result;

iOS Simulator to test website on Mac

If you are on Mac OS X just use Simulator. I don't know if it is available by default but it looks like it is a part of the Xcode suite.

Anyway it is free and really useful, it allows you to simulate many popular Apple devices:

enter image description here

Adding header for HttpURLConnection

Your code is fine.You can also use the same thing in this way.

public static String getResponseFromJsonURL(String url) {
    String jsonResponse = null;
    if (CommonUtility.isNotEmpty(url)) {
        try {
            /************** For getting response from HTTP URL start ***************/
            URL object = new URL(url);

            HttpURLConnection connection = (HttpURLConnection) object
            // int timeOut = connection.getReadTimeout();
            connection.setReadTimeout(60 * 1000);
            connection.setConnectTimeout(60 * 1000);
            String authorization="xyz:xyz$123";
            String encodedAuth="Basic "+Base64.encode(authorization.getBytes());
            connection.setRequestProperty("Authorization", encodedAuth);
            int responseCode = connection.getResponseCode();
            //String responseMsg = connection.getResponseMessage();

            if (responseCode == 200) {
                InputStream inputStr = connection.getInputStream();
                String encoding = connection.getContentEncoding() == null ? "UTF-8"
                        : connection.getContentEncoding();
                jsonResponse = IOUtils.toString(inputStr, encoding);
                /************** For getting response from HTTP URL end ***************/

        } catch (Exception e) {

    return jsonResponse;

Its Return response code 200 if authorizationis success

MongoDB - admin user not authorized

I know this answer is coming really late on in this thread but I hope you check it out.

The reason you get that error is based on the specific role that you granted to the user, which you have gathered by now, and yes giving that user the role root will solve your problem but you must first understand what these roles do exactly before granting them to users.

In tutorial you granted the user the userAdminAnyDatabase role which basically give the user the ability to manage users of all your databases. What you were trying to do with your user was outside its role definition.

The root role has this role included in it definition as well as the readWriteAnyDatabase, dbAdminAnyDatabase and other roles making it a superuser (basically because you can do anything with it).

You can check out the role definitions to see which roles you will need to give you users to complete certain tasks. Its not advisable to make all your users super ones :)

SQL injection that gets around mysql_real_escape_string()

The short answer is yes, yes there is a way to get around mysql_real_escape_string(). #For Very OBSCURE EDGE CASES!!!

The long answer isn't so easy. It's based off an attack demonstrated here.

The Attack

So, let's start off by showing the attack...

mysql_query('SET NAMES gbk');
$var = mysql_real_escape_string("\xbf\x27 OR 1=1 /*");
mysql_query("SELECT * FROM test WHERE name = '$var' LIMIT 1");

In certain circumstances, that will return more than 1 row. Let's dissect what's going on here:

  1. Selecting a Character Set

    mysql_query('SET NAMES gbk');

    For this attack to work, we need the encoding that the server's expecting on the connection both to encode ' as in ASCII i.e. 0x27 and to have some character whose final byte is an ASCII \ i.e. 0x5c. As it turns out, there are 5 such encodings supported in MySQL 5.6 by default: big5, cp932, gb2312, gbk and sjis. We'll select gbk here.

    Now, it's very important to note the use of SET NAMES here. This sets the character set ON THE SERVER. If we used the call to the C API function mysql_set_charset(), we'd be fine (on MySQL releases since 2006). But more on why in a minute...

  2. The Payload

    The payload we're going to use for this injection starts with the byte sequence 0xbf27. In gbk, that's an invalid multibyte character; in latin1, it's the string ¿'. Note that in latin1 and gbk, 0x27 on its own is a literal ' character.

    We have chosen this payload because, if we called addslashes() on it, we'd insert an ASCII \ i.e. 0x5c, before the ' character. So we'd wind up with 0xbf5c27, which in gbk is a two character sequence: 0xbf5c followed by 0x27. Or in other words, a valid character followed by an unescaped '. But we're not using addslashes(). So on to the next step...

  3. mysql_real_escape_string()

    The C API call to mysql_real_escape_string() differs from addslashes() in that it knows the connection character set. So it can perform the escaping properly for the character set that the server is expecting. However, up to this point, the client thinks that we're still using latin1 for the connection, because we never told it otherwise. We did tell the server we're using gbk, but the client still thinks it's latin1.

    Therefore the call to mysql_real_escape_string() inserts the backslash, and we have a free hanging ' character in our "escaped" content! In fact, if we were to look at $var in the gbk character set, we'd see:

    ?' OR 1=1 /*

    Which is exactly what the attack requires.

  4. The Query

    This part is just a formality, but here's the rendered query:

    SELECT * FROM test WHERE name = '?' OR 1=1 /*' LIMIT 1

Congratulations, you just successfully attacked a program using mysql_real_escape_string()...

The Bad

It gets worse. PDO defaults to emulating prepared statements with MySQL. That means that on the client side, it basically does a sprintf through mysql_real_escape_string() (in the C library), which means the following will result in a successful injection:

$pdo->query('SET NAMES gbk');
$stmt = $pdo->prepare('SELECT * FROM test WHERE name = ? LIMIT 1');
$stmt->execute(array("\xbf\x27 OR 1=1 /*"));

Now, it's worth noting that you can prevent this by disabling emulated prepared statements:

$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

This will usually result in a true prepared statement (i.e. the data being sent over in a separate packet from the query). However, be aware that PDO will silently fallback to emulating statements that MySQL can't prepare natively: those that it can are listed in the manual, but beware to select the appropriate server version).

The Ugly

I said at the very beginning that we could have prevented all of this if we had used mysql_set_charset('gbk') instead of SET NAMES gbk. And that's true provided you are using a MySQL release since 2006.

If you're using an earlier MySQL release, then a bug in mysql_real_escape_string() meant that invalid multibyte characters such as those in our payload were treated as single bytes for escaping purposes even if the client had been correctly informed of the connection encoding and so this attack would still succeed. The bug was fixed in MySQL 4.1.20, 5.0.22 and 5.1.11.

But the worst part is that PDO didn't expose the C API for mysql_set_charset() until 5.3.6, so in prior versions it cannot prevent this attack for every possible command! It's now exposed as a DSN parameter.

The Saving Grace

As we said at the outset, for this attack to work the database connection must be encoded using a vulnerable character set. utf8mb4 is not vulnerable and yet can support every Unicode character: so you could elect to use that instead—but it has only been available since MySQL 5.5.3. An alternative is utf8, which is also not vulnerable and can support the whole of the Unicode Basic Multilingual Plane.

Alternatively, you can enable the NO_BACKSLASH_ESCAPES SQL mode, which (amongst other things) alters the operation of mysql_real_escape_string(). With this mode enabled, 0x27 will be replaced with 0x2727 rather than 0x5c27 and thus the escaping process cannot create valid characters in any of the vulnerable encodings where they did not exist previously (i.e. 0xbf27 is still 0xbf27 etc.)—so the server will still reject the string as invalid. However, see @eggyal's answer for a different vulnerability that can arise from using this SQL mode.

Safe Examples

The following examples are safe:

mysql_query('SET NAMES utf8');
$var = mysql_real_escape_string("\xbf\x27 OR 1=1 /*");
mysql_query("SELECT * FROM test WHERE name = '$var' LIMIT 1");

Because the server's expecting utf8...

$var = mysql_real_escape_string("\xbf\x27 OR 1=1 /*");
mysql_query("SELECT * FROM test WHERE name = '$var' LIMIT 1");

Because we've properly set the character set so the client and the server match.

$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->query('SET NAMES gbk');
$stmt = $pdo->prepare('SELECT * FROM test WHERE name = ? LIMIT 1');
$stmt->execute(array("\xbf\x27 OR 1=1 /*"));

Because we've turned off emulated prepared statements.

$pdo = new PDO('mysql:host=localhost;dbname=testdb;charset=gbk', $user, $password);
$stmt = $pdo->prepare('SELECT * FROM test WHERE name = ? LIMIT 1');
$stmt->execute(array("\xbf\x27 OR 1=1 /*"));

Because we've set the character set properly.

$mysqli->query('SET NAMES gbk');
$stmt = $mysqli->prepare('SELECT * FROM test WHERE name = ? LIMIT 1');
$param = "\xbf\x27 OR 1=1 /*";
$stmt->bind_param('s', $param);

Because MySQLi does true prepared statements all the time.

Wrapping Up

If you:

  • Use Modern Versions of MySQL (late 5.1, all 5.5, 5.6, etc) AND mysql_set_charset() / $mysqli->set_charset() / PDO's DSN charset parameter (in PHP = 5.3.6)


  • Don't use a vulnerable character set for connection encoding (you only use utf8 / latin1 / ascii / etc)

You're 100% safe.

Otherwise, you're vulnerable even though you're using mysql_real_escape_string()...

How can you float: right in React Native?

using flex

 <View style={{ flexDirection: 'row',}}>
                  <Text style={{fontSize: 12, lineHeight: 30, color:'#9394B3' }}>left</Text>
                  <Text style={{ flex:1, fontSize: 16, lineHeight: 30, color:'#1D2359', textAlign:'right' }}>right</Text>

HTML: How to center align a form

Just move align="center" to de form tag

<form align="center" action="advsearcher.php" method="get">
    Search this website:<input type="text" name="search" />
    <input type="submit" value="Search"/>

Clip/Crop background-image with CSS

Another option is to use linear-gradient() to cover up the edges of your image. Note that this is a stupid solution, so I'm not going to put much effort into explaining it...

.flair {_x000D_
  min-width: 50px; /* width larger than sprite */_x000D_
  text-indent: 60px;_x000D_
  height: 25px;_x000D_
  display: inline-block;_x000D_
    linear-gradient(#F00, #F00) 50px 0/999px 1px repeat-y,_x000D_
    url('') #F00;_x000D_
.flair-classic {_x000D_
  background-position: 50px 0, 0 -25px;_x000D_
.flair-r2 {_x000D_
  background-position: 50px 0, -50px -175px;_x000D_
.flair-smite {_x000D_
  text-indent: 35px;_x000D_
  background-position: 25px 0, -50px -25px;_x000D_
<img src="" alt="spritesheet" /><br />_x000D_
<br />_x000D_
<span class="flair flair-classic">classic sprite</span><br /><br />_x000D_
<span class="flair flair-r2">r2 sprite</span><br /><br />_x000D_
<span class="flair flair-smite">smite sprite</span><br /><br />

I'm using this method on this page: and can't use ::before or ::after elements because I'm already using them for another hack.

Android widget: How to change the text of a button

You can use the setText() method. Example:

import android.widget.Button;

Button p1_button = (Button)findViewById(;
p1_button.setText("Some text");

Also, just as a point of reference, Button extends TextView, hence why you can use setText() just like with an ordinary TextView.

How do I remove a MySQL database?

I needed to correct the privileges.REVOKE ALL PRIVILEGES ONlogs.* FROM 'root'@'root'; GRANT ALL PRIVILEGES ONlogs.* TO 'root'@'root'WITH GRANT OPTION;

How can I decrypt a password hash in PHP?

Use the password_verify() function

if (password_vertify($inputpassword, $row['password'])) {
  print "Logged in";
else {
    print "Password Incorrect";

What is the best way to implement constants in Java?

FWIW, a timeout in seconds value should probably be a configuration setting (read in from a properties file or through injection as in Spring) and not a constant.

What does Statement.setFetchSize(nSize) method really do in SQL Server JDBC driver?

In JDBC, the setFetchSize(int) method is very important to performance and memory-management within the JVM as it controls the number of network calls from the JVM to the database and correspondingly the amount of RAM used for ResultSet processing.

Inherently if setFetchSize(10) is being called and the driver is ignoring it, there are probably only two options:

  1. Try a different JDBC driver that will honor the fetch-size hint.
  2. Look at driver-specific properties on the Connection (URL and/or property map when creating the Connection instance).

The RESULT-SET is the number of rows marshalled on the DB in response to the query. The ROW-SET is the chunk of rows that are fetched out of the RESULT-SET per call from the JVM to the DB. The number of these calls and resulting RAM required for processing is dependent on the fetch-size setting.

So if the RESULT-SET has 100 rows and the fetch-size is 10, there will be 10 network calls to retrieve all of the data, using roughly 10*{row-content-size} RAM at any given time.

The default fetch-size is 10, which is rather small. In the case posted, it would appear the driver is ignoring the fetch-size setting, retrieving all data in one call (large RAM requirement, optimum minimal network calls).

What happens underneath is that it doesn't actually fetch one row at a time from the RESULT-SET. It fetches that from the (local) ROW-SET and fetches the next ROW-SET (invisibly) from the server as it becomes exhausted on the local client.

All of this depends on the driver as the setting is just a 'hint' but in practice I have found this is how it works for many drivers and databases (verified in many versions of Oracle, DB2 and MySQL).

How to find all occurrences of a substring?

This thread is a little old but this worked for me:

numberString = "onetwothreefourfivesixseveneightninefiveten"
testString = "five"

marker = 0
while marker < len(numberString):
        marker = numberString.index("five", marker) + 1
    except ValueError:
        print("String not found")
        marker = len(numberString)

Any way to generate ant build.xml file automatically from Eclipse?

I've had the same problem, our work environment is based on Eclipse Java projects, and we needed to build automatically an ANT file so that we could use a continuous integration server (Jenkins, in our case).

We rolled out our own Eclipse Java to Ant tool, which is now available on GitHub:


To use it, call:

java -jar ant-build-for-java.jar <folder with repositories> [<.userlibraries file>]

The first argument is the folder with the repositories. It will search the folder recursively for any .project file. The tool will create a build.xml in the given folder.

Optionally, the second argument can be an exported .userlibraries file, from Eclipse, needed when any of the projects use Eclipse user libraries. The tool was tested only with user libraries using relative paths, it's how we use them in our repo. This implies that JARs and other archives needed by projects are inside an Eclipse project, and referenced from there.

The tool only supports dependencies from other Eclipse projects and from Eclipse user libraries.

PHP Warning Permission denied (13) on session_start()

PHP does not have permissions to write on /tmp directory. You need to use chmod command to open /tmp permissions.

How do I get video durations with YouTube API version 3?

This code extracts the YouTube video duration using the YouTube API v3 by passing a video ID. It worked for me.

    function getDuration($videoID){
       $apikey = "YOUR-Youtube-API-KEY"; // Like this AIcvSyBsLA8znZn-i-aPLWFrsPOlWMkEyVaXAcv
       $dur = file_get_contents("$videoID&key=$apikey");
       $VidDuration =json_decode($dur, true);
       foreach ($VidDuration['items'] as $vidTime)
           $VidDuration= $vidTime['contentDetails']['duration'];
       return $parts[0][0] . ":" .
              $parts[0][1] . ":".
              $parts[0][2]; // Return 1:11:46 (i.e.) HH:MM:SS

    echo getDuration("zyeubYQxHyY"); // Video ID

You can get your domain's own YouTube API key on and generate credentials for your own requirement.

Disable Chrome strict MIME type checking

In my case, I turned off X-Content-Type-Options on nginx then works fine. But make sure this declines your security level a little. Would be a temporally fix.

# Not work
add_header X-Content-Type-Options nosniff;
# OK (comment out)
#add_header X-Content-Type-Options nosniff;

It'll be the same for apache.

<IfModule mod_headers.c>
  #Header set X-Content-Type-Options nosniff

Iterating over each line of ls -l output

As already mentioned, awk is the right tool for this. If you don't want to use awk, instead of parsing output of "ls -l" line by line, you could iterate over all files and do an "ls -l" for each individual file like this:

for x in * ; do echo `ls -ld $x` ; done

download file using an ajax request

I prefer location.assign(url);

Complete syntax example:


Understanding __getitem__ method

The [] syntax for getting item by key or index is just syntax sugar.

When you evaluate a[i] Python calls a.__getitem__(i) (or type(a).__getitem__(a, i), but this distinction is about inheritance models and is not important here). Even if the class of a may not explicitly define this method, it is usually inherited from an ancestor class.

All the (Python 2.7) special method names and their semantics are listed here:

How to handle calendar TimeZones using Java?

You say that the date is used in connection with web services, so I assume that is serialized into a string at some point.

If this is the case, you should take a look at the setTimeZone method of the DateFormat class. This dictates which time zone that will be used when printing the time stamp.

A simple example:

SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");

Calendar cal = Calendar.getInstance();
String timestamp = formatter.format(cal.getTime());

How to convert numbers between hexadecimal and decimal

String stringrep = myintvar.ToString("X");

int num = int.Parse("FF", System.Globalization.NumberStyles.HexNumber);

Convert audio files to mp3 using ffmpeg

Never mind,

I am converting my audio files to mp2 by using the command:

ffmpeg -i input.wav -f mp2 output.mp3

This command works perfectly.

I know that this actually converts the files to mp2 format, but then the resulting file sizes are the same..

Equals(=) vs. LIKE

LIKE and = are different. LIKE is what you would use in a search query. It also allows wildcards like _ (simple character wildcard) and % (multi-character wildcard).

= should be used if you want exact matches and it will be faster.

This site explains LIKE

How to import load a .sql or .csv file into SQLite?

If you are happy to use a (python) script then there is a python script that automates this at:

This will auto-create the table for you as well as do some basic type-guessing and data casting for you (so e.g. it will work out something is a number and set the column type to "real").

Height of an HTML select box (dropdown)

NO. It's not possible to change height of a select dropdown because that property is browser specific.

However if you want that functionality, then there are many options. You can use bootstrap dropdown-menu and define it's max-height property. Something like this.

$('.dropdown-menu').on( 'click', 'a', function() {_x000D_
    var text = $(this).html();_x000D_
    var htmlText = text + ' <span class="caret"></span>';_x000D_
.dropdown-menu {_x000D_
    max-height: 146px;_x000D_
    overflow: scroll;_x000D_
    overflow-x: hidden;_x000D_
    margin-top: 0px;_x000D_
.caret {_x000D_
   float: right;_x000D_
    margin-top: 5%;_x000D_
#menu1 {_x000D_
    width: 160px; _x000D_
    text-align: left;_x000D_
<link rel="stylesheet" href="">_x000D_
  <script src=""></script>_x000D_
  <script src=""></script>_x000D_
<div class="container" style="margin:10px">_x000D_
  <div class="dropdown">_x000D_
    <button class="btn btn-default dropdown-toggle" type="button" id="menu1" data-toggle="dropdown">Tutorials_x000D_
    <span class="caret"></span></button>_x000D_
    <ul class="dropdown-menu" role="menu" aria-labelledby="menu1">_x000D_
      <li><a href="#">HTML</a></li>_x000D_
      <li><a href="#">CSS</a></li>_x000D_
      <li><a href="#">JavaScript</a></li>_x000D_
      <li><a href="#">About Us</a></li>_x000D_
      <li><a href="#">HTML</a></li>_x000D_
      <li><a href="#">CSS</a></li>_x000D_
      <li><a href="#">JavaScript</a></li>_x000D_
      <li><a href="#">About Us</a></li>_x000D_
      <li><a href="#">HTML</a></li>_x000D_
      <li><a href="#">CSS</a></li>_x000D_
      <li><a href="#">JavaScript</a></li>_x000D_
      <li><a href="#">About Us</a></li>_x000D_
      <li><a href="#">HTML</a></li>_x000D_
      <li><a href="#">CSS</a></li>_x000D_
      <li><a href="#">JavaScript</a></li>_x000D_
      <li><a href="#">About Us</a></li>_x000D_
      <li><a href="#">HTML</a></li>_x000D_
      <li><a href="#">CSS</a></li>_x000D_
      <li><a href="#">JavaScript</a></li>_x000D_
      <li><a href="#">About Us</a></li>_x000D_
      <li><a href="#">HTML</a></li>_x000D_
      <li><a href="#">CSS</a></li>_x000D_
      <li><a href="#">JavaScript</a></li>_x000D_
      <li><a href="#">About Us</a></li>_x000D_

CSS: 100% font size - 100% of what?

My understanding is that when the font is set as follows

body {
  font-size: 100%;

the browser will render the font as per the user settings for that browser.

The spec says that % is rendered

relative to parent element's font size

In this case, I take that to mean what the browser is set to.

Violation of PRIMARY KEY constraint. Cannot insert duplicate key in object

What is the value you're passing to the primary key (presumably "pk_OrderID")? You can set it up to auto increment, and then there should never be a problem with duplicating the value - the DB will take care of that. If you need to specify a value yourself, you'll need to write code to determine what the max value for that field is, and then increment that.

If you have a column named "ID" or such that is not shown in the query, that's fine as long as it is set up to autoincrement - but it's probably not, or you shouldn't get that err msg. Also, you would be better off writing an easier-on-the-eye query and using params. As the lad of nine years hence inferred, you're leaving your database open to SQL injection attacks if you simply plop in user-entered values. For example, you could have a method like this:

internal static int GetItemIDForUnitAndItemCode(string qry, string unit, string itemCode)
    int itemId;
    using (SqlConnection sqlConn = new SqlConnection(ReportRunnerConstsAndUtils.CPSConnStr))
        using (SqlCommand cmd = new SqlCommand(qry, sqlConn))
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.Add("@Unit", SqlDbType.VarChar, 25).Value = unit;
            cmd.Parameters.Add("@ItemCode", SqlDbType.VarChar, 25).Value = itemCode;
            itemId = Convert.ToInt32(cmd.ExecuteScalar());
    return itemId;

...that is called like so:

int itemId = SQLDBHelper.GetItemIDForUnitAndItemCode(GetItemIDForUnitAndItemCodeQuery, _unit, itemCode);

You don't have to, but I store the query separately:

public static readonly String GetItemIDForUnitAndItemCodeQuery = "SELECT PoisonToe FROM Platypi WHERE Unit = @Unit AND ItemCode = @ItemCode";

You can verify that you're not about to insert an already-existing value by (pseudocode):

bool alreadyExists = IDAlreadyExists(query, value) > 0;

The query is something like "SELECT COUNT FROM TABLE WHERE BLA = @CANDIDATEIDVAL" and the value is the ID you're potentially about to insert:

if (alreadyExists) // keep inc'ing and checking until false, then use that id value

Justin wants to know if this will work:

string exists = "SELECT 1 from AC_Shipping_Addresses where pk_OrderID = " _Order.OrderNumber; if (exists > 0)...

What seems would work to me is:

string existsQuery = string.format("SELECT 1 from AC_Shipping_Addresses where pk_OrderID = {0}", _Order.OrderNumber); 
// Or, better yet:
string existsQuery = "SELECT COUNT(*) from AC_Shipping_Addresses where pk_OrderID = @OrderNumber"; 
// Now run that query after applying a value to the OrderNumber query param (use code similar to that above); then, if the result is > 0, there is such a record.

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

Found my solution thanks to Error with .htaccess and mod_rewrite
For Apache 2.4 and in all *.conf files (e.g. httpd-vhosts.conf, http.conf, httpd-autoindex.conf ..etc) use

Require all granted

instead of

Order allow,deny
Allow from all

The Order and Allow directives are deprecated in Apache 2.4.

Service will not start: error 1067: the process terminated unexpectedly

In my case the error 1067 was caused with a specific version of Tomcat 7.0.96 32-bit in combination with AdoptOpenJDK. Spent two hours on it, un-installing, re-installing and trying different Java settings but Tomcat would not start. See... ASF Bugzilla – Bug 63625 seems to point at the issue though they refer to seeing a different error.

I tried 7.0.99 32-bit and it started straight away with the same AdoptOpenJDK 32-bit binary install.

bundle install fails with SSL certificate verification error

I had to reinstall openssl:

brew uninstall --force openssl
brew install openssl

How do I get the current mouse screen coordinates in WPF?

Mouse.GetPosition(mWindow) gives you the mouse position relative to the parameter of your choice. mWindow.PointToScreen() convert the position to a point relative to the screen.

So mWindow.PointToScreen(Mouse.GetPosition(mWindow)) gives you the mouse position relative to the screen, assuming that mWindow is a window(actually, any class derived from System.Windows.Media.Visual will have this function), if you are using this inside a WPF window class, this should work.

OnClickListener in Android Studio

you will need to button initilzation inside method instead of trying to initlzing View's at class level do it as:

 Button button;  //<< declare here..

    protected void onCreate(Bundle savedInstanceState) {
        button= (Button) findViewById(; //<< initialize here
         // set OnClickListener for Button here
        button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            startActivity(new Intent(MainActivity.this,StandingsActivity.class));

How to use onClick() or onSelect() on option tag in a JSP page?

The answer you gave above works but it is confusing because you have used two names twice and you have an unnecessary line of code. you are doing a process that is not necessary.

it's a good idea when debugging code to get pen and paper and draw little boxes to represent memory spaces (i.e variables being stored) and then to draw arrows to indicate when a variable goes into a little box and when it comes out, if it gets overwritten or is a copy made etc.

if you do this with the code below you will see that

var selectBox = document.getElementById("selectBox");

gets put in a box and stays there you don't do anything with it afterwards.


var selectBox = document.getElementById("selectBox");

is hard to debug and is confusing when you have a select id of selectBox for the options list . ---- which selectBox do you want to manipulate / query / etc is it the local var selectBox that will disappear or is it the selectBox id you have assigned to the select tag

your code works until you add to it or modify it then you can easily loose track and get all mixed up

<script type="text/javascript">

function changeFunc() {
var selectBox = document.getElementById("selectBox");
var selectedValue = selectBox.options[selectBox.selectedIndex].value;


<select id="selectBox" onchange="changeFunc();">
<option value="1">Option #1</option>
<option value="2">Option #2</option>

a leaner way that works also is:

<script type="text/javascript">

function changeFunc() {

var selectedValue = selectBox.options[selectBox.selectedIndex].value;

<select id="selectBox" onchange="changeFunc();">
<option value="1">Option #1</option>
<option value="2">Option #2</option>

and it's a good idea to use descriptive names that match the program and task you are working on am currently writing a similar program to accept and process postcodes using your code and modifying it with descriptive names the object is to make computer language as close to natural language as possible.

<script type="text/javascript">

function Mapit(){

var actualPostcode=getPostcodes.options[getPostcodes.selectedIndex].value;


// alert is for debugging only next we go on to process and do something
// in this developing program it will placing markers on a map



<select id="getPostcodes" onchange="Mapit();">

<option>London North Inner</option>


<option>London North Outer</option>


// a lot more options follow 
// with text in options to divide into areas and nothing will happen 
// if visitor clicks on the text function Mapit() will ignore
// all clicks on the divider text inserted into option boxes


How do I include a path to libraries in g++

In your MakeFile or CMakeLists.txt you can set CMAKE_CXX_FLAGS as below:

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -I/path/to/your/folder")

How to get full path of a file?

In a similar scenario, I'm launching a cshell script from some other location. For setting the correct absolute path of the script so that it runs in the designated directory only, I'm using the following code:

set script_dir = `pwd`/`dirname $0`

$0 stores the exact string how the script was executed.

For e.g. if the script was launched like this: $> ../../test/test.csh, $script_dir will contain /home/abc/sandbox/v1/../../test

MySQL Daemon Failed to Start - centos 6

Your database was shut down because of insufficient memory! You can edit the file my.cnf base below graph to resolve it


How to Scroll Down - JQuery

This can be used in to solve this problem

<div id='scrol'></div> 

in javascript use this


Difference between Hashing a Password and Encrypting it

As correct as the other answers may be, in the context that the quote was in, hashing is a tool that may be used in securing information, encryption is a process that takes information and makes it very difficult for unauthorized people to read/use.

Calculating distance between two geographic locations

I wanted to implement myself this, i ended up reading the Wikipedia page on Great-circle distance formula, because no code was readable enough for me to use as basis.

C# example

    /// <summary>
    /// Calculates the distance between two locations using the Great Circle Distance algorithm
    /// <see cref=""/>
    /// </summary>
    /// <param name="first"></param>
    /// <param name="second"></param>
    /// <returns></returns>
    private static double DistanceBetween(GeoLocation first, GeoLocation second)
        double longitudeDifferenceInRadians = Math.Abs(ToRadians(first.Longitude) - ToRadians(second.Longitude));

        double centralAngleBetweenLocationsInRadians = Math.Acos(
            Math.Sin(ToRadians(first.Latitude)) * Math.Sin(ToRadians(second.Latitude)) +
            Math.Cos(ToRadians(first.Latitude)) * Math.Cos(ToRadians(second.Latitude)) *

        const double earthRadiusInMeters = 6357 * 1000;

        return earthRadiusInMeters * centralAngleBetweenLocationsInRadians;

    private static double ToRadians(double degrees)
        return degrees * Math.PI / 180;

Adding multiple columns AFTER a specific column in MySQL

This works fine for me:


how to initialize a char array?

You can use a for loop. but don't forget the last char must be a null character !

char * msg = new char[65546];
for(int i=0;i<65545;i++)

Printing the last column of a line in a file

Not the actual issue here, but might help some one: I was doing awk "{print $NF}", note the wrong quotes. Should be awk '{print $NF}', so that the shell doesn't expand $NF.

How can I get the CheckBoxList selected values, what I have doesn't seem to work C#.NET/VisualWebPart

// Page.aspx //

// To count checklist item

  int a = ChkMonth.Items.Count;
        int count = 0;

        for (var i = 0; i < a; i++)
            if (ChkMonth.Items[i].Selected == true)

// Page.aspx.cs //

  // To access checkbox list item's value //
   string YrStrList = "";
        foreach (ListItem listItem in ChkMonth.Items)
            if (listItem.Selected)
                YrStrList = YrStrList + "'" + listItem.Value + "'" + ",";


        sMonthStr = YrStrList.ToString();

Loop through all the resources in a .resx file

With the nuget package System.Resources.ResourceManager (v4.3.0) the ResourceSet and ResourceManager.GetResourceSet are not available.

Using the ResourceReader, as this post suggest: "C# - Cannot getting a string from ResourceManager (from satellite assembly)"

It's still possible to read the key/values of the resource file.

System.Reflection.Assembly resourceAssembly = System.Reflection.Assembly.Load(new System.Reflection.AssemblyName("YourAssemblyName"));
String[] manifests = resourceAssembly.GetManifestResourceNames(); 
using (ResourceReader reader = new ResourceReader(resourceAssembly.GetManifestResourceStream(manifests[0])))
   System.Collections.IDictionaryEnumerator dict = reader.GetEnumerator();
   while (dict.MoveNext())
      String key = dict.Key as String;
      String value = dict.Value as String;

GridView must be placed inside a form tag with runat="server" even after the GridView is within a form tag

Just after your Page_Load add this:

public override void VerifyRenderingInServerForm(Control control)

Note that I don't do anything in the function.

EDIT: Tim answered the same thing. :) You can also find the answer Here

Is it possible to put a ConstraintLayout inside a ScrollView?

I had NestedScrollView inside ConstraintLayout, and this NestedScrollView has one ConstraintLayout.

If you're facing issue with NestedScrollView,

add android:fillViewport="true" to NestedScrollView, worked.

How to programmatically set the ForeColor of a label to its default?

For example summer :

lblSummer.foreColor = color.Yellow;

'float' vs. 'double' precision

Floating point numbers in C use IEEE 754 encoding.

This type of encoding uses a sign, a significand, and an exponent.

Because of this encoding, many numbers will have small changes to allow them to be stored.

Also, the number of significant digits can change slightly since it is a binary representation, not a decimal one.

Single precision (float) gives you 23 bits of significand, 8 bits of exponent, and 1 sign bit.

Double precision (double) gives you 52 bits of significand, 11 bits of exponent, and 1 sign bit.

How to insert current_timestamp into Postgres via python

A timestamp does not have "a format".

The recommended way to deal with timestamps is to use a PreparedStatement where you just pass a placeholder in the SQL and pass a "real" object through the API of your programming language. As I don't know Python, I don't know if it supports PreparedStatements and how the syntax for that would be.

If you want to put a timestamp literal into your generated SQL, you will need to follow some formatting rules when specifying the value (a literal does have a format).

Ivan's method will work, although I'm not 100% sure if it depends on the configuration of the PostgreSQL server.

A configuration (and language) independent solution to specify a timestamp literal is the ANSI SQL standard:

 INSERT INTO some_table 
 (TIMESTAMP '2011-05-16 15:36:38');

Yes, that's the keyword TIMESTAMP followed by a timestamp formatted in ISO style (the TIMESTAMP keyword defines that format)

The other solution would be to use the to_timestamp() function where you can specify the format of the input literal.

 INSERT INTO some_table 
 (to_timestamp('16-05-2011 15:36:38', 'dd-mm-yyyy hh24:mi:ss'));

Send push to Android by C# using FCM (Firebase Cloud Messaging)

I have posted this answer as this question was viewed most and this server side code was written in VS 2015 in C# for sending push notification either single device based on device id or subscribed topic to Xamarin Android app

public class FCMPushNotification
    public FCMPushNotification()
        // TODO: Add constructor logic here

    public bool Successful

    public string Response
    public Exception Error

    public FCMPushNotification SendNotification(string _title, string _message, string _topic)
        FCMPushNotification result = new FCMPushNotification();
            result.Successful = true;
            result.Error = null;
           // var value = message;
            var requestUri = "";

            WebRequest webRequest = WebRequest.Create(requestUri);
            webRequest.Method = "POST";
            webRequest.Headers.Add(string.Format("Authorization: key={0}", YOUR_FCM_SERVER_API_KEY));
            webRequest.Headers.Add(string.Format("Sender: id={0}", YOUR_FCM_SENDER_ID));
            webRequest.ContentType = "application/json";

            var data = new
               // to = YOUR_FCM_DEVICE_ID, // Uncoment this if you want to test for single device
               to="/topics/"+_topic, // this is for topic 
            var serializer = new JavaScriptSerializer();
            var json = serializer.Serialize(data);

            Byte[] byteArray = Encoding.UTF8.GetBytes(json);

            webRequest.ContentLength = byteArray.Length;
            using (Stream dataStream = webRequest.GetRequestStream())
                dataStream.Write(byteArray, 0, byteArray.Length);

                using (WebResponse webResponse = webRequest.GetResponse())
                    using (Stream dataStreamResponse = webResponse.GetResponseStream())
                        using (StreamReader tReader = new StreamReader(dataStreamResponse))
                            String sResponseFromServer = tReader.ReadToEnd();
                            result.Response = sResponseFromServer;

        catch(Exception ex)
            result.Successful = false;
            result.Response = null;
            result.Error = ex;
        return result;

and its uses

// start sending push notification to apps
                FCMPushNotification fcmPush = new FCMPushNotification();                    
                fcmPush.SendNotification("your notificatin title", "Your body message","news");
                // end push notification

How to remove numbers from string using Regex.Replace?

Blow codes could help you...

Fetch Numbers:

return string.Concat(input.Where(char.IsNumber));

Fetch Letters:

return string.Concat(input.Where(char.IsLetter));

Put search icon near textbox using bootstrap

Here are three different ways to do it:


Here's a working Demo in Fiddle Of All Three


You can use native bootstrap validation states (No Custom CSS!):

<div class="form-group has-feedback">
    <label class="control-label" for="inputSuccess2">Name</label>
    <input type="text" class="form-control" id="inputSuccess2"/>
    <span class="glyphicon glyphicon-search form-control-feedback"></span>

For a full discussion, see my answer to Add a Bootstrap Glyphicon to Input Box

Input Group:

You can use the .input-group class like this:

<div class="input-group">
    <input type="text" class="form-control"/>
    <span class="input-group-addon">
        <i class="fa fa-search"></i>

For a full discussion, see my answer to adding Twitter Bootstrap icon to Input box

Unstyled Input Group:

You can still use .input-group for positioning but just override the default styling to make the two elements appear separate.

Use a normal input group but add the class input-group-unstyled:

<div class="input-group input-group-unstyled">
    <input type="text" class="form-control" />
    <span class="input-group-addon">
        <i class="fa fa-search"></i>

Then change the styling with the following css:

.input-group.input-group-unstyled input.form-control {
    -webkit-border-radius: 4px;
       -moz-border-radius: 4px;
            border-radius: 4px;
.input-group-unstyled .input-group-addon {
    border-radius: 4px;
    border: 0px;
    background-color: transparent;

Also, these solutions work for any input size

KERNELBASE.dll Exception 0xe0434352 offset 0x000000000000a49d

0xe0434352 is the SEH code for a CLR exception. If you don't understand what that means, stop and read A Crash Course on the Depths of Win32™ Structured Exception Handling. So your process is not handling a CLR exception. Don't shoot the messenger, KERNELBASE.DLL is just the unfortunate victim. The perpetrator is MyApp.exe.

There should be a minidump of the crash in DrWatson folders with a full stack, it will contain everything you need to root cause the issue.

I suggest you wire up, in your myapp.exe code, AppDomain.UnhandledException and Application.ThreadException, as appropriate.

regular expression for anything but an empty string

You can do one of two things:

  • match against ^\s*$; a match means the string is "empty"
    • ^, $ are the beginning and end of string anchors respectively
    • \s is a whitespace character
    • * is zero-or-more repetition of
  • find a \S; an occurrence means the string is NOT "empty"
    • \S is the negated version of \s (note the case difference)
    • \S therefore matches any non-whitespace character


Related questions

Append text to input field

If you are planning to use appending more then once, you might want to write a function:

//Append text to input element
function jQ_append(id_of_input, text){
    var input_id = '#'+id_of_input;
    $(input_id).val($(input_id).val() + text);

After you can just call it:

jQ_append('my_input_id', 'add this text');

Display an array in a readable/hierarchical format

print_r() is mostly for debugging. If you want to print it in that format, loop through the array, and print the elements out.

foreach($data as $d){
  foreach($d as $v){
    echo $v."\n";

Find the maximum value in a list of tuples in Python

Use max():

Using itemgetter():

In [53]: lis=[(101, 153), (255, 827), (361, 961)]

In [81]: from operator import itemgetter

In [82]: max(lis,key=itemgetter(1))[0]    #faster solution
Out[82]: 361

using lambda:

In [54]: max(lis,key=lambda item:item[1])
Out[54]: (361, 961)

In [55]: max(lis,key=lambda item:item[1])[0]
Out[55]: 361

timeit comparison:

In [30]: %timeit max(lis,key=itemgetter(1))
1000 loops, best of 3: 232 us per loop

In [31]: %timeit max(lis,key=lambda item:item[1])
1000 loops, best of 3: 556 us per loop

How to adjust gutter in Bootstrap 3 grid system?

To define a 3 column grid you could use the customizer or download the source set your less variables and recompile.

To learn more about the grid and the columns / gutter widths, please also read:

In you case with a container of 960px consider the medium grid (see also: This grid will have a max container width of 970px. When setting @grid-columns:3; and setting @grid-gutter-width:15px; in variables.less you will get:

15px | 1st column (298.33) | 15px | 2nd column (298.33) |15px | 3th column (298.33) | 15px

Javascript regular expression password validation having special characters

function validatePassword() {
    var p = document.getElementById('newPassword').value,
        errors = [];
    if (p.length < 8) {
        errors.push("Your password must be at least 8 characters"); 
    if ([a-z]/i) < 0) {
        errors.push("Your password must contain at least one letter.");
    if ([0-9]/) < 0) {
        errors.push("Your password must contain at least one digit."); 
    if (errors.length > 0) {
        return false;
    return true;

There is a certain issue in below answer as it is not checking whole string due to absence of [ ] while checking the characters and numerals, this is correct version

Convert a string to an enum in C#

object Enum.Parse(System.Type enumType, string value, bool ignoreCase);

So if you had an enum named mood it would look like this:

   enum Mood

   // ...
   Mood m = (Mood) Enum.Parse(typeof(Mood), "Happy", true);
   Console.WriteLine("My mood is: {0}", m.ToString());

EF Core add-migration Build Failed

In my case it was failing because an unrelated project in the solution was failing. Unloading that project and running the command again worked.

JSON Java 8 LocalDateTime format in Spring Boot

@JsonDeserialize(using= LocalDateDeserializer.class) does not work for me with the below dependency.

    <version> 2.9.6</version>

I have used the below code converter to deserialize the date into a java.sql.Date.

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;

@Converter(autoApply = true)
public class LocalDateConverter implements AttributeConverter<java.time.LocalDate, java.sql.Date> {

    public java.sql.Date convertToDatabaseColumn(java.time.LocalDate attribute) {

        return attribute == null ? null : java.sql.Date.valueOf(attribute);

    public java.time.LocalDate convertToEntityAttribute(java.sql.Date dbData) {

        return dbData == null ? null : dbData.toLocalDate();

How to set delay in vbscript

if it is VBScript, it should be

WScript.Sleep 100

If it is JavaScript


Time in milliseconds. WScript.Sleep 1000 results in a 1 second sleep.

DataTables: Cannot read property style of undefined

You said any suggestions wold be helpful, so currently I resolved my DataTables "cannot read property 'style' of undefined" problem but my problem was basically using wrong indexes at data table initiation phase's columnDefs section. I got 9 columns and the indexes are 0, 1, 2, .. , 8 but I was using indexes for 9 and 10 so after fixing the wrong index issue the fault has disappeared. I hope this helps.

In short, you got to watch your columns amount and indexes if consistent everywhere.

Buggy Code:

        "ajax": {
            url: "something_url",
            type: 'POST'
        "processing": true,
        "serverSide": true,
        "bPaginate": true,
        "sPaginationType": "full_numbers",
        "columns": [
            { "data": "cl1" },
            { "data": "cl2" },
            { "data": "cl3" },
            { "data": "cl4" },
            { "data": "cl5" },
            { "data": "cl6" },
            { "data": "cl7" },
            { "data": "cl8" },
            { "data": "cl9" }
        columnDefs: [
            { orderable: false, targets: [ 7, 9, 10 ] } //This part was wrong

Fixed Code:

        "ajax": {
            url: "something_url",
            type: 'POST'
        "processing": true,
        "serverSide": true,
        "bPaginate": true,
        "sPaginationType": "full_numbers",
        "columns": [
            { "data": "cl1" },
            { "data": "cl2" },
            { "data": "cl3" },
            { "data": "cl4" },
            { "data": "cl5" },
            { "data": "cl6" },
            { "data": "cl7" },
            { "data": "cl8" },
            { "data": "cl9" }
        columnDefs: [
            { orderable: false, targets: [ 5, 7, 8 ] } //This part is ok now

How to remove gaps between subplots in matplotlib?

The problem is the use of aspect='equal', which prevents the subplots from stretching to an arbitrary aspect ratio and filling up all the empty space.

Normally, this would work:

import matplotlib.pyplot as plt

ax = [plt.subplot(2,2,i+1) for i in range(4)]

for a in ax:

plt.subplots_adjust(wspace=0, hspace=0)

The result is this:

However, with aspect='equal', as in the following code:

import matplotlib.pyplot as plt

ax = [plt.subplot(2,2,i+1) for i in range(4)]

for a in ax:

plt.subplots_adjust(wspace=0, hspace=0)

This is what we get:

The difference in this second case is that you've forced the x- and y-axes to have the same number of units/pixel. Since the axes go from 0 to 1 by default (i.e., before you plot anything), using aspect='equal' forces each axis to be a square. Since the figure is not a square, pyplot adds in extra spacing between the axes horizontally.

To get around this problem, you can set your figure to have the correct aspect ratio. We're going to use the object-oriented pyplot interface here, which I consider to be superior in general:

import matplotlib.pyplot as plt

fig = plt.figure(figsize=(8,8)) # Notice the equal aspect ratio
ax = [fig.add_subplot(2,2,i+1) for i in range(4)]

for a in ax:

fig.subplots_adjust(wspace=0, hspace=0)

Here's the result:

How do I convert a org.w3c.dom.Document object to a String?

use some thing like

import javax.xml.transform.*;
import javax.xml.transform.dom.*;

//method to convert Document to String
public String getStringFromDocument(Document doc)
       DOMSource domSource = new DOMSource(doc);
       StringWriter writer = new StringWriter();
       StreamResult result = new StreamResult(writer);
       TransformerFactory tf = TransformerFactory.newInstance();
       Transformer transformer = tf.newTransformer();
       transformer.transform(domSource, result);
       return writer.toString();
    catch(TransformerException ex)
       return null;

Preventing an image from being draggable or selectable without using JS

Depending on the situation, it is often helpful to make the image a background image of a div with CSS.

<div id='my-image'></div>

Then in CSS:

#my-image {
    background-image: url('/img/foo.png');
    width: ???px;
    height: ???px;

See this JSFiddle for a live example with a button and a different sizing option.

HttpServletRequest to complete URL

I use this method:

public static String getURL(HttpServletRequest req) {

    String scheme = req.getScheme();             // http
    String serverName = req.getServerName();     //
    int serverPort = req.getServerPort();        // 80
    String contextPath = req.getContextPath();   // /mywebapp
    String servletPath = req.getServletPath();   // /servlet/MyServlet
    String pathInfo = req.getPathInfo();         // /a/b;c=123
    String queryString = req.getQueryString();          // d=789

    // Reconstruct original requesting URL
    StringBuilder url = new StringBuilder();

    if (serverPort != 80 && serverPort != 443) {


    if (pathInfo != null) {
    if (queryString != null) {
    return url.toString();

Parse date without timezone javascript

I ran into the same problem and then remembered something wonky about a legacy project I was working on and how they handled this issue. I didn't understand it at the time and didn't really care until I ran into the problem myself

var date = '2014-01-02T00:00:00.000Z'
date = date.substring(0,10).split('-')
date = date[1] + '-' + date[2] + '-' + date[0]

new Date(date) #Thu Jan 02 2014 00:00:00 GMT-0600

For whatever reason passing the date in as '01-02-2014' sets the timezone to zero and ignores the user's timezone. This may be a fluke in the Date class but it existed some time ago and exists today. And it seems to work cross-browser. Try it for yourself.

This code is implemented in a global project where timezones matter a lot but the person looking at the date did not care about the exact moment it was introduced.

How to uncheck checked radio button

Radio buttons are meant to be required options... If you want them to be unchecked, use a checkbox, there is no need to complicate things and allow users to uncheck a radio button; removing the JQuery allows you to select from one of them

Create a folder inside documents folder in iOS apps

Swift 3 Solution:

private func createImagesFolder() {
        // path to documents directory
        let documentDirectoryPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first
        if let documentDirectoryPath = documentDirectoryPath {
            // create the custom folder path
            let imagesDirectoryPath = documentDirectoryPath.appending("/images")
            let fileManager = FileManager.default
            if !fileManager.fileExists(atPath: imagesDirectoryPath) {
                do {
                    try fileManager.createDirectory(atPath: imagesDirectoryPath,
                                                    withIntermediateDirectories: false,
                                                    attributes: nil)
                } catch {
                    print("Error creating images folder in documents dir: \(error)")

Set a cookie to never expire

Maximum value: 2147483647

setcookie("CookieName", "CookieValue", 2147483647);

To avoid integer overflow the timestamp should be set to:

2^31 - 1 = 2147483647 = 2038-01-19 04:14:07

Setting a higher value might cause problems with older browsers.

Also see the RFC about cookies:

  OPTIONAL.  The value of the Max-Age attribute is delta-seconds,
  the lifetime of the cookie in seconds, a decimal non-negative
  integer.  To handle cached cookies correctly, a client SHOULD
  calculate the age of the cookie according to the age calculation
  rules in the HTTP/1.1 specification [RFC2616].  When the age is
  greater than delta-seconds seconds, the client SHOULD discard the
  cookie.  A value of zero means the cookie SHOULD be discarded

and RFC 2616, 14.6 Age:

If a cache receives a value larger than the largest positive integer it can represent, or if any of its age calculations overflows, it MUST transmit an Age header with a value of 2147483648 (2^31).

Get current cursor position in a textbox

It looks OK apart from the space in your ID attribute, which is not valid, and the fact that you're replacing the value of your input before checking the selection.

function textbox()_x000D_
        var ctl = document.getElementById('Javascript_example');_x000D_
        var startPos = ctl.selectionStart;_x000D_
        var endPos = ctl.selectionEnd;_x000D_
        alert(startPos + ", " + endPos);_x000D_
<input id="Javascript_example" name="one" type="text" value="Javascript example" onclick="textbox()">

Also, if you're supporting IE <= 8 you need to be aware that those browsers do not support selectionStart and selectionEnd.

How can I load Partial view inside the view?

if you want to populate contents of your partial view inside your view you can use




if you want to make server request and process the data and then return partial view to you main view filled with that data you can use

    @Html.Action("Load", "Home")

public PartialViewResult Load()
    return PartialView("_LoadView");

if you want user to click on the link and then populate the data of partial view you can use:

    "Click Here to Load the Partial View", 
    new AjaxOptions { UpdateTargetId = "toUpdate" }

Spring MVC How take the parameter value of a GET HTTP Request in my controller method?

You could also use a URI template. If you structured your request into a restful URL Spring could parse the provided value from the url.


    <a id="byParameter" 
       class="textLink" href="<c:url value="/mapping/parameter/bar />">By path, method,and
           presence of parameter</a>


@RequestMapping(value="/mapping/parameter/{foo}", method=RequestMethod.GET)
public @ResponseBody String byParameter(@PathVariable String foo) {
    //Perform logic with foo
    return "Mapped by path + method + presence of query parameter! (MappingController)";

Spring URI Template Documentation

Android Studio: Unable to start the daemon process

I have solve this problem by just deleting .gradle folder within my application project..

Delete folder .gradle from your project no need to delete main .gradle folder which is located at C:\Users\<username>

Using the value in a cell as a cell reference in a formula?


=SUM(INDIRECT(<start cell here> & ":" & <end cell here>))

How to write string literals in python without having to escape them?

If you're dealing with very large strings, specifically multiline strings, be aware of the triple-quote syntax:

a = r"""This is a multiline string
with more than one line
in the source code."""

Get the current language in device

I've checked the Locale methods on my Android 4.1.2 device, and the results:

Locale.getDefault().getLanguage()       ---> en      
Locale.getDefault().getISO3Language()   ---> eng 
Locale.getDefault().getCountry()        ---> US 
Locale.getDefault().getISO3Country()    ---> USA 
Locale.getDefault().getDisplayCountry() ---> United States 
Locale.getDefault().getDisplayName()    ---> English (United States) 
Locale.getDefault().toString()          ---> en_US
Locale.getDefault().getDisplayLanguage()---> English
Locale.getDefault().toLanguageTag()     ---> en-US

Return values from the row above to the current row

To solve this problem in Excel, usually I would just type in the literal row number of the cell above, e.g., if I'm typing in Cell A7, I would use the formula =A6. Then if I copied that formula to other cells, they would also use the row of the previous cell.

Another option is to use Indirect(), which resolves the literal statement inside to be a formula. You could use something like:

=INDIRECT("A" & ROW() - 1)

The above formula will resolve to the value of the cell in column A and the row that is one less than that of the cell which contains the formula.

How can I work with command line on synology?

The current windows 10 (Version 1803 (OS Build 17134.1)) has SSH built in. With that, just enable SSH from the Control Panel, Terminal & SNMP, be sure you are using an account in the Administrator's group, and you're all set.

Launch Powershell or CMD, enter ssh yourAccountName@diskstation

The first time it will cache off your certificate.


Further detailed explanations can be found on the synology docs page:

How to login to DSM with root permission via SSH Telnet

500 Internal Server Error for php file not for html

I know this question is old, however I ran into this problem on Windows 8.1 while trying to use .htaccess files for rewriting. My solution was simple, I forgot to modify the following line in httpd.conf

#LoadModule rewrite_module modules/


LoadModule rewrite_module modules/

Restarted the apache monitor, now all works well. Just posting this as an answer because someone in the future may run across the same issue with a simple fix.

Good luck!

Error You must specify a region when running command aws ecs list-container-instances

#1- Run this to configure the region once and for all:

aws configure set region us-east-1 --profile admin
  • Change admin next to the profile if it's different.

  • Change us-east-1 if your region is different.

#2- Run your command again:

aws ecs list-container-instances --cluster default

Time complexity of accessing a Python dict

My program seems to suffer from linear access to dictionaries, its run-time grows exponentially even though the algorithm is quadratic.

I use a dictionary to memoize values. That seems to be a bottleneck.

This is evidence of a bug in your memoization method.

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

No need for basename, and especially no need for a subshell running pwd (which adds an extra, and expensive, fork operation); the shell can do this internally using parameter expansion:

result=${PWD##*/}          # to assign to a variable

printf '%s\n' "${PWD##*/}" # to print to stdout
                           # ...more robust than echo for unusual names
                           #    (consider a directory named -e or -n)

printf '%q\n' "${PWD##*/}" # to print to stdout, quoted for use as shell input
                           # ...useful to make hidden characters readable.

Note that if you're applying this technique in other circumstances (not PWD, but some other variable holding a directory name), you might need to trim any trailing slashes. The below uses bash's extglob support to work even with multiple trailing slashes:

shopt -s extglob           # enable +(...) glob syntax
result=${dirname%%+(/)}    # trim however many trailing slashes exist
result=${result##*/}       # remove everything before the last / that still remains
printf '%s\n' "$result"

Alternatively, without extglob:

result="${dirname%"${dirname##*[!/]}"}" # extglob-free multi-trailing-/ trim
result="${result##*/}"                  # remove everything before the last /

pip cannot install anything

This is the full text of the blog post linked below:

If you've tried installing a package with pip recently, you may have encountered this error:

Could not fetch URL There was a problem confirming the ssl certificate: <urlopen error [Errno 1] _ssl.c:504: error:0D0890A1:asn1 encoding routines:ASN1_verify:unknown message digest algorithm>
  Will skip URL when looking for download links for Django==1.5.1 (from -r requirements.txt (line 1))
  Could not fetch URL There was a problem confirming the ssl certificate: <urlopen error [Errno 1] _ssl.c:504: error:0D0890A1:asn1 encoding routines:ASN1_verify:unknown message digest algorithm>
  Will skip URL when looking for download links for Django==1.5.1 (from -r requirements.txt (line 1))
  Cannot fetch index base URL
  Could not fetch URL There was a problem confirming the ssl certificate: <urlopen error [Errno 1] _ssl.c:504: error:0D0890A1:asn1 encoding routines:ASN1_verify:unknown message digest algorithm>
  Will skip URL when looking for download links for Django==1.5.1 (from -r requirements.txt (line 1))
  Could not fetch URL There was a problem confirming the ssl certificate: <urlopen error [Errno 1] _ssl.c:504: error:0D0890A1:asn1 encoding routines:ASN1_verify:unknown message digest algorithm>
  Will skip URL when looking for download links for Django==1.5.1 (from -r requirements.txt (line 1))
  Could not find any downloads that satisfy the requirement Django==1.5.1 (from -r requirements.txt (line 1))
No distributions at all found for Django==1.5.1 (from -r requirements.txt (line 1))
Storing complete log in /Users/paul/.pip/pip.log

This seems to be an issue with an old version of OpenSSL being incompatible with pip 1.3.1. If you're using a non-stock Python distribution (notably EPD 7.3), you're very likely to have a setup that isn't going to work with pip 1.3.1 without a shitload of work.

The easy workaround for now, is to install pip 1.2.1, which does not require SSL:

curl -O
tar xvfz pip-1.2.1.tar.gz
cd pip-1.2.1
python install

If you are using EPD, and you're not using it for a class where things might break, you may want to consider installing the new incarnation: Enthought Canopy. I know they were aware of the issues caused by the previous version of OpenSSL, and would imagine they are using a new version now that should play nicely with pip 1.3.1.

Convert a string to a datetime

Try converting date like this:

    Dim expenddt as Date = Date.ParseExact(edate, "dd/mm/yyyy", 

Hope this helps.

Is the buildSessionFactory() Configuration method deprecated in Hibernate

It is not unusual to find discrepancies between different versions of documentation. Most developers view documentation as a chore, and they tend to put it off.

As a rule of thumb, if the javadoc says one thing and some non-javadoc documentation contradicts it, the chances are that the javadoc is more accurate. Programmers are more likely to keep the javadoc up to date with changes to the code ... because the "source" for the javadoc is in the same file as the code.

In the case of @deprecated tags, it is a virtual certainty that the javadoc is more accurate. Developers deprecate things after careful consideration ... and (generally speaking) they don't undeprecate them.

CRC32 C or C++ implementation

using zlib.h (

#include <zlib.h>
unsigned long  crc = crc32(0L, Z_NULL, 0);
crc = crc32(crc, (const unsigned char*)data_address, data_len);

How do I encode URI parameter values?

It seems that CharEscapers from Google GData-java-client has what you want. It has uriPathEscaper method, uriQueryStringEscaper, and generic uriEscaper. (All return Escaper object which does actual escaping). Apache License.

Console.log not working at all

Consider a more pragmatic approach to the question of "doing it correctly".

console.log("about to bind scroll fx");

$(window).scroll(function() {

       console.log("scroll bound, loop through div's");


If both of those logs output correctly, then its likely the problem exists in your var declaration. To debug that, consider breaking it out into several lines:

var id='#'+$(this).attr('id');


var off=$(id).offset().top;
var hei=$(id).height();
var winscroll=$(window).scrollTop();
var dif=hei+off-($(window).height());

By doing this, at least during debugging, you may find that the var id is undefined, causing errors throughout the rest of the code. Is it possible some of your div tags do not have id's?

How do I get the current year using SQL on Oracle?

Another option is:


Java URLConnection Timeout

You can set timeouts for all connections made from the jvm by changing the following System-properties:

System.setProperty("", "10000");
System.setProperty("", "10000");

Every connection will time out after 10 seconds.

Setting 'defaultReadTimeout' is not needed, but shown as an example if you need to control reading.

Escaping Double Quotes in Batch Script

Google eventually came up with the answer. The syntax for string replacement in batch is this:

set v_myvar=replace me
set v_myvar=%v_myvar:ace=icate%

Which produces "replicate me". My script now looks like this:

@echo off
set v_params=%*
set v_params=%v_params:"=\"%
call bash -c "g++-linux-4.1 %v_params%"

Which replaces all instances of " with \", properly escaped for bash.

How can I check if a Perl array contains a particular value?

Method 1: grep (may careful while value is expected to be a regex).

Try to avoid using grep, if looking at resources.

if ( grep( /^$value$/, @badparams ) ) {
  print "found";

Method 2: Linear Search

for (@badparams) {
    if ($_ eq $value) {
       print "found";

Method 3: Use a hash

my %hash = map {$_ => 1} @badparams;
print "found" if (exists $hash{$value});

Method 4: smartmatch

(added in Perl 5.10, marked is experimental in Perl 5.18).

use experimental 'smartmatch';  # for perl 5.18
print "found" if ($value ~~ @badparams);

Method 5: Use the module List::MoreUtils

use List::MoreUtils qw(any);
@badparams = (1,2,3);
$value = 1;
print "found" if any {$_ == $value} @badparams;

Why Is Subtracting These Two Times (in 1927) Giving A Strange Result?

The moral of this strangeness is:

  • Use dates and times in UTC wherever possible.
  • If you can not display a date or time in UTC, always indicate the time-zone.
  • If you can not require an input date/time in UTC, require an explicitly indicated time-zone.

How do I add slashes to a string in Javascript?

replace works for the first quote, so you need a tiny regular expression:

str = str.replace(/'/g, "\\'");

SUM of grouped COUNT in SQL Query

I required having count(*) > 1 also. So, I wrote my own query after referring some the above queries


select sum(count) from (select count(`table_name`.`id`) as `count` from `table_name` where {some condition} group by {some_column} having count(`table_name`.`id`) > 1) as `tmp`;


select sum(count) from (select count(`table_name`.`id`) as `count` from `table_name` where `table_name`.`name` IS NOT NULL and `table_name`.`name` != '' group by `table_name`.`name` having count(`table_name`.`id`) > 1) as `tmp`;

Propagation Delay vs Transmission delay

The transmission delay is the amount of time required for the router to push out the packet, it has nothing to do with the distance between the two routers. The propagation delay is the time taken by a bit to to propagate form one router to the next

How can I replace a regex substring match in Javascript?

using str.replace(regex, $1);:

var str   = 'asd-0.testing';
var regex = /(asd-)\d(\.\w+)/;

if (str.match(regex)) {
    str = str.replace(regex, "$1" + "1" + "$2");

Edit: adaptation regarding the comment

How do I get started with Node.js

Use the source, Luke.

No, but seriously I found that building Node.js from source, running the tests, and looking at the benchmarks did get me on the right track. From there, the .js files in the lib directory are a good place to look, especially the file http.js.

Update: I wrote this answer over a year ago, and since that time there has an explosion in the number of great resources available for people learning Node.js. Though I still believe diving into the source is worthwhile, I think that there are now better ways to get started. I would suggest some of the books on Node.js that are starting to come out.

How to pass parameters in $ajax POST?

function funcion(y) {
   type: 'POST',
   url: '/ruta',
   data: {"x": y},
   contentType: "application/x-www-form-urlencoded;charset=utf8",

Difference between .keystore file and .jks file

Ultimately, .keystore and .jks are just file extensions: it's up to you to name your files sensibly. Some application use a keystore file stored in $HOME/.keystore: it's usually implied that it's a JKS file, since JKS is the default keystore type in the Sun/Oracle Java security provider. Not everyone uses the .jks extension for JKS files, because it's implied as the default. I'd recommend using the extension, just to remember which type to specify (if you need).

In Java, the word keystore can have either of the following meanings, depending on the context:

When talking about the file and storage, this is not really a storage facility for key/value pairs (there are plenty or other formats for this). Rather, it's a container to store cryptographic keys and certificates (I believe some of them can also store passwords). Generally, these files are encrypted and password-protected so as not to let this data available to unauthorized parties.

Java uses its KeyStore class and related API to make use of a keystore (whether it's file based or not). JKS is a Java-specific file format, but the API can also be used with other file types, typically PKCS#12. When you want to load a keystore, you must specify its keystore type. The conventional extensions would be:

  • .jks for type "JKS",
  • .p12 or .pfx for type "PKCS12" (the specification name is PKCS#12, but the # is not used in the Java keystore type name).

In addition, BouncyCastle also provides its implementations, in particular BKS (typically using the .bks extension), which is frequently used for Android applications.

Jenkins - Configure Jenkins to poll changes in SCM

I believe best practice these days is H/5 * * * *, which means every 5 minutes with a hashing factor to avoid all jobs starting at EXACTLY the same time.

-bash: export: `=': not a valid identifier

First of all go to the /home directorty then open invisible shell script with some text editor, ~/.bash_profile (macOS) or ~/.bashrc (linux) go to the bottom, you would see something like this,

export LD_LIBRARY_PATH = /usr/local/lib

change this like that( remove blank point around the = ),

export LD_LIBRARY_PATH=/usr/local/lib

it should be useful.

HTML code for INR

Use similar symbol: <del>&#2352;</del> =>

Try &#8377; => ₹

Use an image(bad solution but works): <img src="" width="8" height="10"> =>

Source: Empty rectanglar box is displayed instead of the rupee symbol in HTML

How to get json key and value in javascript?

//By using jquery json parser    
var obj = $.parseJSON('{"name": "", "skills": "", "jobtitel": "Entwickler", "res_linkedin": "GwebSearch"}');

//By using javasript json parser
var t = JSON.parse('{"name": "", "skills": "", "jobtitel": "Entwickler", "res_linkedin": "GwebSearch"}');

Check this jsfiddle

As of jQuery 3.0, $.parseJSON is deprecated. To parse JSON strings use the native JSON.parse method instead.


How to run SQL script in MySQL?

I had this error, and tried all the advice i could get to no avail.

Finally, the problem was that my folder had a space in the folder name which appearing as a forward-slash in the folder path, once i found and removed it, it worked fine.

What is the difference among col-lg-*, col-md-* and col-sm-* in Bootstrap?

Let's un-complicate Bootstrap!

responsive bootstrap columns

Notice how the col-sm occupies the 100% width (in other terms breaks into new line) below 576px but col doesn't. You can notice the current width at the top center in gif.

Here comes the code:

<div class="container">
    <div class="row">
        <div class="col">col</div>
        <div class="col">col</div>
        <div class="col">col</div>
    <div class="row">
        <div class="col-sm">col-sm</div>
        <div class="col-sm">col-sm</div>
        <div class="col-sm">col-sm</div>

Bootstrap by default aligns all the columns(col) in a single row with equal width. In this case three col will occupy 100%/3 width each, whatever the screen size. You can notice that in gif.

Now what if we want to render only one column per line i.e give 100% width to each column but for smaller screens only? Now comes the col-xx classes!

I used col-sm because I wanted to break the columns into separate lines below 576px. These 4 col-xx classes are provided by Bootstrap for different display devices like mobiles, tablets, laptops, large monitors etc.

So,col-sm would break below 576px, col-md would break below 768px, col-lg would break below 992px and col-xl would break below 1200px

Note that there's no col-xs class in bootstrap 4.

Bootstrap Grid System

This pretty much sums-up. You can go back to work.

But there's bit more to it. Now comes the col-* and col-xx-* for customizing width.

Remember in the above example I mentioned that col or col-xx takes the equal width in a row. So if we want to give more width to a specific col we can do this.

Bootstrap row is divided into 12 parts, so in above example there were 3 col so each one takes 12/3 = 4 part. You can consider these parts as a way to measure width.

We could also write that in format col-* i.e. col-4 like this :

<div class="row">
  <div class="col-4">col</div>
  <div class="col-4">col</div>
  <div class="col-4">col</div>

And it would've made no difference because by default bootstrap gives equal width to col (4 + 4 + 4 = 12).

But, what if we want to give 7 parts to 1st col, 3 parts to 2nd col and rest 2 parts (12-7-3 = 2) to 3rd col (7+3+2 so total is 12), we can simply do this:

<div class="row">
  <div class="col-7">col-7</div>
  <div class="col-3">col-3</div>
  <div class="col-2">col-2</div>

enter image description here

and you can customize the width of col-xx-* classes also.

<div class="row">
    <div class="col-sm-7">col-sm-7</div>
    <div class="col-sm-3">col-sm-3</div>
    <div class="col-sm-2">col-sm-2</div>

enter image description here

How does it look in the action?

responsive grid

What if sum of col is more than 12? Then the col will shift/adjust to below line. Yes, there can be any number of columns for a row!

<div class="row">
        <div class="col-12">col-12</div>
        <div class="col-9">col-9</div>
        <div class="col-6">col-6</div>
        <div class="col-6">col-6</div>

enter image description here

What if we want 3 columns in a row for large screens but split these columns into 2 rows for small screens?

<div class="row">
    <div class="col-12 col-sm">col-12 col-sm TOP</div>
    <div class="col col-sm">col col-sm</div>
    <div class="col col-sm">col col-sm</div>

enter image description here

You can play around here:

VBA - Range.Row.Count

This works for me especially in pivots table filtering when I want the count of cells with data on a filtered column. Reduce k accordingly (k - 1) if you have a header row for filtering:

k = Sheets("Sheet1").Range("$A:$A").SpecialCells(xlCellTypeVisible).SpecialCells(xlCellTypeConstants).Count

Call a function with argument list in python

You need to use arguments unpacking..

def wrapper(func, *args):

def func1(x):

def func2(x, y, z):
    print x+y+z

wrapper(func1, 1)
wrapper(func2, 1, 2, 3)

google console error `OR-IEH-01`

Recently I was also having this issue, then I contacted Google Support and they gave me this link to provide required info, I posted and within 24 hours my problem was fixed.


What are advantages of Artificial Neural Networks over Support Vector Machines?

One thing to note is that the two are actually very related. Linear SVMs are equivalent to single-layer NN's (i.e., perceptrons), and multi-layer NNs can be expressed in terms of SVMs. See here for some details.

The following classes could not be instantiated: -

The solutions above didn't help me. I've tried 2 first steps from this link. Worked fine for me. But don't forget to

import com.melnykov.fab.FloatingActionButton; 

instead of


in your

DB2 Query to retrieve all table names for a given schema

There is no big difference in data.The Major difference is column order In list tables schema column will be after table/view column In list tables show details schema column will be after column type

Why use pointers?

One use of pointers (I won't mention things already covered in other people's posts) is to access memory that you haven't allocated. This isn't useful much for PC programming, but it's used in embedded programming to access memory mapped hardware devices.

Back in the old days of DOS, you used to be able to access the video card's video memory directly by declaring a pointer to:

unsigned char *pVideoMemory = (unsigned char *)0xA0000000;

Many embedded devices still use this technique.

Is there a regular expression to detect a valid regular expression?

^                                             # start of string
(                                             # first group start
    (?:[^?+*{}()[\]\\|]+                      # literals and ^, $
     | \\.                                    # escaped characters
     | \[ (?: \^?\\. | \^[^\\] | [^\\^] )     # character classes
          (?: [^\]\\]+ | \\. )* \]
     | \( (?:\?[:=!]|\?<[=!]|\?>)? (?1)?? \)  # parenthesis, with recursive content
     | \(\? (?:R|[+-]?\d+) \)                 # recursive matching
    (?: (?:[?+*]|\{\d+(?:,\d*)?\}) [?+]? )?   # quantifiers
  | \|                                        # alternative
  )*                                          # repeat content
)                                             # end first group
$                                             # end of string

This is a recursive regex, and is not supported by many regex engines. PCRE based ones should support it.

Without whitespace and comments:


.NET does not support recursion directly. (The (?1) and (?R) constructs.) The recursion would have to be converted to counting balanced groups:

^                                         # start of string
  (?: [^?+*{}()[\]\\|]+                   # literals and ^, $
   | \\.                                  # escaped characters
   | \[ (?: \^?\\. | \^[^\\] | [^\\^] )   # character classes
        (?: [^\]\\]+ | \\. )* \]
   | \( (?:\?[:=!]
         | \?<[=!]
         | \?>
         | \?<[^\W\d]\w*>
         | \?'[^\W\d]\w*'
         )?                               # opening of group
     (?<N>)                               #   increment counter
   | \)                                   # closing of group
     (?<-N>)                              #   decrement counter
  (?: (?:[?+*]|\{\d+(?:,\d*)?\}) [?+]? )? # quantifiers
| \|                                      # alternative
)*                                        # repeat content
$                                         # end of string
(?(N)(?!))                                # fail if counter is non-zero.



From the comments:

Will this validate substitutions and translations?

It will validate just the regex part of substitutions and translations. s/<this part>/.../

It is not theoretically possible to match all valid regex grammars with a regex.

It is possible if the regex engine supports recursion, such as PCRE, but that can't really be called regular expressions any more.

Indeed, a "recursive regular expression" is not a regular expression. But this an often-accepted extension to regex engines... Ironically, this extended regex doesn't match extended regexes.

"In theory, theory and practice are the same. In practice, they're not." Almost everyone who knows regular expressions knows that regular expressions does not support recursion. But PCRE and most other implementations support much more than basic regular expressions.

using this with shell script in the grep command , it shows me some error.. grep: Invalid content of {} . I am making a script that could grep a code base to find all the files that contain regular expressions

This pattern exploits an extension called recursive regular expressions. This is not supported by the POSIX flavor of regex. You could try with the -P switch, to enable the PCRE regex flavor.

Regex itself "is not a regular language and hence cannot be parsed by regular expression..."

This is true for classical regular expressions. Some modern implementations allow recursion, which makes it into a Context Free language, although it is somewhat verbose for this task.

I see where you're matching []()/\. and other special regex characters. Where are you allowing non-special characters? It seems like this will match ^(?:[\.]+)$, but not ^abcdefg$. That's a valid regex.

[^?+*{}()[\]\\|] will match any single character, not part of any of the other constructs. This includes both literal (a - z), and certain special characters (^, $, .).

How to retrieve a recursive directory and file list from PowerShell excluding some files and folders?

I like Keith Hill's answer except it has a bug that prevents it from recursing past two levels. These commands manifest the bug:

New-Item level1/level2/level3/level4/foobar.txt -Force -ItemType file
cd level1
GetFiles . xyz | % { $_.fullname }

With Hill's original code you get this:


Here is a corrected, and slightly refactored, version:

function GetFiles($path = $pwd, [string[]]$exclude)
    foreach ($item in Get-ChildItem $path)
        if ($exclude | Where {$item -like $_}) { continue }

        if (Test-Path $item.FullName -PathType Container)
            GetFiles $item.FullName $exclude

With that bug fix in place you get this corrected output:


I also like ajk's answer for conciseness though, as he points out, it is less efficient. The reason it is less efficient, by the way, is because Hill's algorithm stops traversing a subtree when it finds a prune target while ajk's continues. But ajk's answer also suffers from a flaw, one I call the ancestor trap. Consider a path such as this that includes the same path component (i.e. subdir2) twice:


Set your location somewhere in between, e.g. cd \usr\testdir\subdir2\child, then run ajk's algorithm to filter out the lower subdir2 and you will get no output at all, i.e. it filters out everything because of the presence of subdir2 higher in the path. This is a corner case, though, and not likely to be hit often, so I would not rule out ajk's solution due to this one issue.

Nonetheless, I offer here a third alternative, one that does not have either of the above two bugs. Here is the basic algorithm, complete with a convenience definition for the path or paths to prune--you need only modify $excludeList to your own set of targets to use it:

$excludeList = @("stuff","bin","obj*")
Get-ChildItem -Recurse | % {
    $pathParts = $_.FullName.substring($pwd.path.Length + 1).split("\");
    if ( ! ($excludeList | where { $pathParts -like $_ } ) ) { $_ }

My algorithm is reasonably concise but, like ajk's, it is less efficient than Hill's (for the same reason: it does not stop traversing subtrees at prune targets). However, my code has an important advantage over Hill's--it can pipeline! It is therefore amenable to fit into a filter chain to make a custom version of Get-ChildItem while Hill's recursive algorithm, through no fault of its own, cannot. ajk's algorithm can be adapted to pipeline use as well, but specifying the item or items to exclude is not as clean, being embedded in a regular expression rather than a simple list of items that I have used.

I have packaged my tree pruning code into an enhanced version of Get-ChildItem. Aside from my rather unimaginative name--Get-EnhancedChildItem--I am excited about it and have included it in my open source Powershell library. It includes several other new capabilities besides tree pruning. Furthermore, the code is designed to be extensible: if you want to add a new filtering capability, it is straightforward to do. Essentially, Get-ChildItem is called first, and pipelined into each successive filter that you activate via command parameters. Thus something like this...

Get-EnhancedChildItem –Recurse –Force –Svn
    –Exclude *.txt –ExcludeTree doc*,man -FullName -Verbose 

... is converted internally into this:

Get-ChildItem | FilterExcludeTree | FilterSvn | FilterFullName

Each filter must conform to certain rules: accepting FileInfo and DirectoryInfo objects as inputs, generating the same as outputs, and using stdin and stdout so it may be inserted in a pipeline. Here is the same code refactored to fit these rules:

filter FilterExcludeTree()
  $target = $_
  Coalesce-Args $Path "." | % {
    $canonicalPath = (Get-Item $_).FullName
    if ($target.FullName.StartsWith($canonicalPath)) {
      $pathParts = $target.FullName.substring($canonicalPath.Length + 1).split("\");
      if ( ! ($excludeList | where { $pathParts -like $_ } ) ) { $target }

The only additional piece here is the Coalesce-Args function (found in this post by Keith Dahlby), which merely sends the current directory down the pipe in the event that the invocation did not specify any paths.

Because this answer is getting somewhat lengthy, rather than go into further detail about this filter, I refer the interested reader to my recently published article on entitled Practical PowerShell: Pruning File Trees and Extending Cmdlets where I discuss Get-EnhancedChildItem at even greater length. One last thing I will mention, though, is another function in my open source library, New-FileTree, that lets you generate a dummy file tree for testing purposes so you can exercise any of the above algorithms. And when you are experimenting with any of these, I recommend piping to % { $_.fullname } as I did in the very first code fragment for more useful output to examine.

Basic CSS - how to overlay a DIV with semi-transparent DIV on top

Using CSS3 you don't need to make your own image with the transparency.

Just have a div with the following

background: rgba(255,255,255,.5);

The last parameter in background (.5) is the level of transparency (a higher number is more opaque).

Example Fiddle

Hide console window from Process.Start C#

I've had bad luck with this answer, with the process (Wix light.exe) essentially going out to lunch and not coming home in time for dinner. However, the following worked well for me:

Process p = new Process();
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
// etc, then start process

SQL Server Escape an Underscore

Obviously @Lasse solution is right, but there's another way to solve your problem: T-SQL operator LIKE defines the optional ESCAPE clause, that lets you declare a character which will escape the next character into the pattern.

For your case, the following WHERE clauses are equivalent:

WHERE username LIKE '%[_]d';            -- @Lasse solution
WHERE username LIKE '%$_d' ESCAPE '$';
WHERE username LIKE '%^_d' ESCAPE '^';

Comparing mongoose _id and strings

ObjectIDs are objects so if you just compare them with == you're comparing their references. If you want to compare their values you need to use the ObjectID.equals method:

if (results.userId.equals(AnotherMongoDocument._id)) {

how to open *.sdf files?

Try LINQPad, it works for SQL Server, MySQL, SQLite and also SDF (SQL CE 4.0). Best of all it's free!


Steps with version 4.35.1:

  1. click 'Add Connection'

  2. Click Next with 'Build data context automatically' and 'Default(LINQ to SQL)' selected.

  3. Under 'Provider' choose 'SQL CE 4.0'.

  4. Under 'Database' with 'Attach database file' selected, choose 'Browse' to select your .sdf file.

  5. Click 'OK'.

  6. Voila! It should show the tables in .sdf and be able to query it via right clicking the table or writing LINQ code in your favorite .NET language or even SQL. How cool is that?

Improve INSERT-per-second performance of SQLite

Several tips:

  1. Put inserts/updates in a transaction.
  2. For older versions of SQLite - Consider a less paranoid journal mode (pragma journal_mode). There is NORMAL, and then there is OFF, which can significantly increase insert speed if you're not too worried about the database possibly getting corrupted if the OS crashes. If your application crashes the data should be fine. Note that in newer versions, the OFF/MEMORY settings are not safe for application level crashes.
  3. Playing with page sizes makes a difference as well (PRAGMA page_size). Having larger page sizes can make reads and writes go a bit faster as larger pages are held in memory. Note that more memory will be used for your database.
  4. If you have indices, consider calling CREATE INDEX after doing all your inserts. This is significantly faster than creating the index and then doing your inserts.
  5. You have to be quite careful if you have concurrent access to SQLite, as the whole database is locked when writes are done, and although multiple readers are possible, writes will be locked out. This has been improved somewhat with the addition of a WAL in newer SQLite versions.
  6. Take advantage of saving space...smaller databases go faster. For instance, if you have key value pairs, try making the key an INTEGER PRIMARY KEY if possible, which will replace the implied unique row number column in the table.
  7. If you are using multiple threads, you can try using the shared page cache, which will allow loaded pages to be shared between threads, which can avoid expensive I/O calls.
  8. Don't use !feof(file)!

I've also asked similar questions here and here.

Creating a "Hello World" WebSocket example


Since you are using WebSocket, spender is correct. After recieving the initial data from the WebSocket, you need to send the handshake message from the C# server before any further information can flow.

HTTP/1.1 101 Web Socket Protocol Handshake
Upgrade: websocket
Connection: Upgrade
WebSocket-Origin: example
WebSocket-Protocol: 13

Something along those lines.

You can do some more research into how WebSocket works on w3 or google.

Links and Resources

Here is a protocol specifcation:

List of working examples:

jQuery - replace all instances of a character in a string

RegEx is the way to go in most cases.

In some cases, it may be faster to specify more elements or the specific element to perform the replace on:

$(document).ready(function () {
    $('.myclass').each(function () {
        $('img').each(function () {
            $(this).attr('src', $(this).attr('src').replace('_s.jpg', '_n.jpg'));

This does the replace once on each string, but it does it using a more specific selector.

Get a json via Http Request in NodeJS

Just tell request that you are using json:true and forget about header and parse

var options = {
    hostname: '',
    port: app.get('port'),
    path: '/users',
    method: 'GET',
request(options, function(error, response, body){
    if(error) console.log(error);
    else console.log(body);

and the same for post

var options = {
    hostname: '',
    port: app.get('port'),
    path: '/users',
    method: 'POST',
    json: {"name":"John", "lastname":"Doe"}
request(options, function(error, response, body){
    if(error) console.log(error);
    else console.log(body);

C# Interfaces. Implicit implementation versus Explicit implementation

One important use of explicit interface implementation is when in need to implement interfaces with mixed visibility.

The problem and solution are well explained in the article C# Internal Interface.

For example, if you want to protect leakage of objects between application layers, this technique allows you to specify different visibility of members that could cause the leakage.

Have nginx access_log and error_log log to STDOUT and STDERR of master process

In docker image of PHP-FPM, i've see such approach:

# cat /usr/local/etc/php-fpm.d/docker.conf
error_log = /proc/self/fd/2

; if we send this to /proc/self/fd/1, it never appears
access.log = /proc/self/fd/2

How to get all Errors from ASP.Net MVC modelState?

During debugging I find it useful to put a table at the bottom of each of my pages to show all ModelState errors.

<table class="model-state">
    @foreach (var item in ViewContext.ViewData.ModelState) 
        if (item.Value.Errors.Any())
            <td>@((item.Value == null || item.Value.Value == null) ? "<null>" : item.Value.Value.RawValue)</td>
            <td>@(string.Join("; ", item.Value.Errors.Select(x => x.ErrorMessage)))</td>

        border-color: #600;
        border-width: 0 0 1px 1px;
        border-style: solid;
        border-collapse: collapse;
        font-size: .8em;
        font-family: arial;

    table.model-state td
        border-color: #600;
        border-width: 1px 1px 0 0;
        border-style: solid;
        margin: 0;
        padding: .25em .75em;
        background-color: #FFC;

How do you find the first key in a dictionary?

Update: as of Python 3.7, insertion order is maintained, so you don't need an OrderedDict here. You can use the below approaches with a normal dict

Changed in version 3.7: Dictionary order is guaranteed to be insertion order. This behavior was an implementation detail of CPython from 3.6.


Python 3.6 and earlier*

If you are talking about a regular dict, then the "first key" doesn't mean anything. The keys are not ordered in any way you can depend on. If you iterate over your dict you will likely not get "banana" as the first thing you see.

If you need to keep things in order, then you have to use an OrderedDict and not just a plain dictionary.

import collections
prices  = collections.OrderedDict([
        ("banana", 4),
        ("apple", 2),
        ("orange", 1.5),
        ("pear", 3),

If you then wanted to see all the keys in order you could do so by iterating through it

for k in prices:

You could, alternatively put all of the keys into a list and then work with that

ks = list(prices)
print(ks[0]) # will print "banana"

A faster way to get the first element without creating a list would be to call next on the iterator. This doesn't generalize nicely when trying to get the nth element though

>>> next(iter(prices))

* CPython had guaranteed insertion order as an implementation detail in 3.6.

SystemError: Parent module '' not loaded, cannot perform relative import

if you just run the under the app, just import like

from mymodule import myclass

if you want to call on other folder, use:

from .mymodule import myclass

for example:

+-- app
¦   +--
¦   +--
¦   +--

from .mymodule import myclass

from app import main

So I think the main question of you is how to call app.main.

Validate that text field is numeric usiung jQuery

You don't need a regex for this one. Use the isNAN() JavaScript function.

The isNaN() function determines whether a value is an illegal number (Not-a-Number). This function returns true if the value is NaN, and false if not.

if (isNaN($('#Field').val()) == false) {

    // It's a number

How do I skip an iteration of a `foreach` loop?

Another approach is to filter using LINQ before the loop executes:

foreach ( int number in numbers.Where(n => n >= 0) )
    // process number