Programs & Examples On #Mysql error 1064

1064 means "syntax error" in MySQL. It shows part of the failing query to help you troubleshoot.

MySQL error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near

Delimiters, delimiters...

You really need them when there are multiple statements in your procedure. (in other words, do you have a ; in your code and then more statements/commands? Then, you need to use delimiters).

For such a simpler rpocedure as yours though, you could just do:

  SELECT * FROM `hs_hr_employee_leave_quota`;

Check for database connection, otherwise display message

very basic:

$username = 'user';
$password = 'password';
$server = 'localhost'; 
// Opens a connection to a MySQL server
$connection = mysql_connect ($server, $username, $password) or die('try again in some minutes, please');
//if you want to suppress the error message, substitute the connection line for:
//$connection = @mysql_connect($server, $username, $password) or die('try again in some minutes, please');


Warning: mysql_connect() [function.mysql-connect]: Access denied for user 'user'@'localhost' (using password: YES) in /home/user/public_html/zdel1.php on line 6 try again in some minutes, please

as per Wrikken's recommendation below, check out a complete error handler for more complex, efficient and elegant solutions:

How to delete from multiple tables in MySQL?

Use this

DELETE FROM `articles`, `comments` 
USING `articles`,`comments` 
WHERE `comments`.`article_id` = `articles`.`id` AND `articles`.`id` = 4


DELETE `articles`, `comments` 
FROM `articles`, `comments` 
WHERE `comments`.`article_id` = `articles`.`id` AND `articles`.`id` = 4

How to grant all privileges to root user in MySQL 8.0

My Specs:

mysql --version
mysql  Ver 8.0.16 for Linux on x86_64 (MySQL Community Server - GPL)

What worked for me:

mysql> CREATE USER 'username'@'localhost' IDENTIFIED BY 'desired_password';
mysql> GRANT ALL PRIVILEGES ON db_name.* TO 'username'@'localhost' WITH GRANT OPTION;

Response in both queries:

Query OK, O rows affected (0.10 sec*)

N.B: I created a database (db_name) earlier and was creating a user credential with all privileges granted to all tables in the DB in place of using the default root user which I read somewhere is a best practice.

Declaring and using MySQL varchar variables

Looks like you forgot the @ in variable declaration. Also I remember having problems with SET in MySql a long time ago.


DECLARE @FOO varchar(7);
DECLARE @oldFOO varchar(7);
SELECT @FOO = '138';

update mypermits 
   set person = @FOO 
 where person = @oldFOO;

mysql is not recognised as an internal or external command,operable program or batch

MYSQL_HOME variable value:C:\Program Files\MySQL\MySQL Server 5.0\bin %MYSQL_HOME%\bin

See the problem? This resolves to a path of C:\Program Files\MySQL\MySQL Server 5.0\bin\bin

How can I fix MySQL error #1064?

For my case, I was trying to execute procedure code in MySQL, and due to some issue with server in which Server can't figure out where to end the statement I was getting Error Code 1064. So I wrapped the procedure with custom DELIMITER and it worked fine.

For example, Before it was:

CREATE PROCEDURE `getStats` (param_id INT, param_offset INT, param_startDate datetime, param_endDate datetime)
    /*Procedure Code Here*/

After putting DELIMITER it was like this:

CREATE PROCEDURE `getStats` (param_id INT, param_offset INT, param_startDate datetime, param_endDate datetime)
    /*Procedure Code Here*/

MySql Inner Join with WHERE clause

You are using two WHERE clauses but only one is allowed. Use it like this:

SELECT table1.f_id FROM table1
INNER JOIN table2 ON table2.f_id = table1.f_id
  table1.f_com_id = '430'
  AND table1.f_status = 'Submitted'
  AND table2.f_type = 'InProcess'

MySQL Error #1133 - Can't find any matching row in the user table

I encountered this issue, but in my case the password for the 'phpmyadmin' user did not match the contents of /etc/phpmyadmin/config-db.php

Once I updated the password for the 'phpmyadmin' user the error went away.

These are the steps I took:

  1. Log in to mysql as root: mysql -uroot -pYOUR_ROOT_PASS
  2. Change to the 'mysql' db: use mysql;
  3. Update the password for the 'phpmyadmin' user: UPDATE mysql.user SET Password=PASSWORD('YOUR_PASS_HERE') WHERE User='phpmyadmin' AND Host='localhost';
  4. Flush privileges: FLUSH PRIVILEGES;

DONE!! It worked for me.

MySQl Error #1064

Sometimes when your table has a similar name to the database name you should use back tick. so instead of:

INSERT INTO, field2) VALUES ('value1', 'value2');

You should have this:

INSERT INTO `books`.`book`(`field1`, `field2`) VALUES ('value1', 'value2');

ERROR 1064 (42000) in MySQL

This was my case: I forgot to add ' before );

End of file.sql with error:


End of file.sql without error:


SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax — PHP — PDO

from is a keyword in SQL. You may not used it as a column name without quoting it. In MySQL, things like column names are quoted using backticks, i.e. `from`.

Personally, I wouldn't bother; I'd just rename the column.

PS. as pointed out in the comments, to is another SQL keyword so it needs to be quoted, too. Conveniently, the folks at maintain a list of reserved words in SQL.

Warning about SSL connection when connecting to MySQL database

the new versions of mysql-connector establish SSL connection by default solve it:

Download the older version of mysql-connector such as

. . or . . Download OpenSSL for Windows and follow the instructions how to set it

Empty brackets '[]' appearing when using .where

A good bet is to utilize Rails' Arel SQL manager, which explicitly supports case-insensitive ActiveRecord queries:

t = Guide.arel_table Guide.where(t[:title].matches('%attack')) 

Here's an interesting blog post regarding the portability of case-insensitive queries using Arel. It's worth a read to understand the implications of utilizing Arel across databases.

How to get all the values of input array element jquery


function getvalues(){
var inps = document.getElementsByName('pname[]');
for (var i = 0; i <inps.length; i++) {
var inp=inps[i];

Here is Demo.

How to empty the content of a div

An alternative way to do it is:

var div = document.getElementById('myDiv');

However, using document.getElementById('myDiv').innerHTML = ""; is faster.

See: Benchmark test


Both methods preserve the div.

Issue with Task Scheduler launching a task

As far as I know you will need to give the domain account the proper "User Rights" such as "Log on as a Batch Job". You can check that in your Local Policies. Also, you might have a Domain GPO which is overwriting your local policies. I bet if you add this Domain Account into the local admin group of that machine, your problem will go away. A few articles for you to check:

Angular HttpClient "Http failure during parsing"

if you have options

return`${this.endpoint}/account/login`,payload, { ...options, responseType: 'text' })

Creating a REST API using PHP

Trying to write a REST API from scratch is not a simple task. There are many issues to factor and you will need to write a lot of code to process requests and data coming from the caller, authentication, retrieval of data and sending back responses.

Your best bet is to use a framework that already has this functionality ready and tested for you.

Some suggestions are:

Phalcon - REST API building - Easy to use all in one framework with huge performance

Apigility - A one size fits all API handling framework by Zend Technologies

Laravel API Building Tutorial

and many more. Simple searches on Bitbucket/Github will give you a lot of resources to start with.

How can I get enum possible values in a MySQL database?

You can use this syntax for get enum possible values in MySQL QUERY :

$syntax = "SELECT COLUMN_TYPY FROM information_schema.`COLUMNS` 

and you get value, example : enum('Male','Female')

this is example sytax php:

function ($table,$colm){

// mysql query.
$syntax = mysql_query("SELECT COLUMN_TYPY FROM information_schema.`COLUMNS` 
WHERE TABLE_NAME = '$table' AND COLUMN_NAME ='$colm'");

if (!mysql_error()){
 //Get a array possible values from table and colm.
 $array_string = mysql_fetch_array($syntax);

    //Remove part string
    $string = str_replace("'", "", $array_string['COLUMN_TYPE']);
    $string = str_replace(')', "", $string);
    $string = explode(",",substr(5,$string));
    $string = "error mysql :".mysql_error();
// Values is (Examples) Male,Female,Other
return $string;

How to get DataGridView cell value in messagebox?

MessageBox.Show(" Value at 0,0" + DataGridView1.Rows[0].Cells[0].Value );

Conditional HTML Attributes using Razor MVC3

I guess a little more convenient and structured way is to use Html helper. In your view it can be look like:

 var htmlAttr = new Dictionary<string, object>();
 htmlAttr.Add("id", strElementId);
 if (!CSSClass.IsEmpty())
   htmlAttr.Add("class", strCSSClass);

@* ... *@

@Html.TextBox("somename", "", htmlAttr)

If this way will be useful for you i recommend to define dictionary htmlAttr in your model so your view doesn't need any @{ } logic blocks (be more clear).

how can I connect to a remote mongo server from Mac OS terminal

With Mongo 3.2 and higher just use your connection string as is:

mongo mongodb://username:[email protected]:10011/my_database

How to wrap text in textview in Android

Strange enough - I created my TextView in Code and it wrapped - despite me not setting anything except standard stuff - but see for yourself:

LinearLayout.LayoutParams childParams = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
childParams.setMargins(5, 5, 5, 5);

Label label = new Label(this);
label.setText("This is a testing label This is a testing label This is a testing label This is a testing labelThis is a testing label This is a testing label");

As you can see from the params definition I am using a LinearLayout. The class Label simply extends TextView - not doing anything there except setting the font size and the font color.

When running it in the emulator (API Level 9) it automatically wraps the text across 3 lines.

How do I print part of a rendered HTML page in JavaScript?

You could use a print stylesheet, but this will affect all print functions.

You could try having a print stylesheet externalally, and it is included via JavaScript when a button is pressed, and then call window.print(), then after that remove it.

How to Disable landscape mode in Android?

You must set the orientation of each activity.

                android:theme="@android:style/Theme.Black.NoTitleBar" >
                android:theme="@android:style/Theme.Black.NoTitleBar" >
                android:theme="@android:style/Theme.Black.NoTitleBar" >
                android:theme="@android:style/Theme.Black.NoTitleBar" >
                android:theme="@android:style/Theme.Black.NoTitleBar" >

Unsigned keyword in C++

You can read about the keyword unsigned in the C++ Reference.

There are two different types in this matter, signed and un-signed. The default for integers is signed which means that they can have negative values.

On a 32-bit system an integer is 32 Bit which means it can contain a value of ~4 billion.

And when it is signed, this means you need to split it, leaving -2 billion to +2 billion.

When it is unsigned however the value cannot contain any negative numbers, so for integers this would mean 0 to +4 billion.

There is a bit more informationa bout this on Wikipedia.

Append data frames together in a for loop

For me, it worked very simply. At first, I made an empty data.frame, then in each iteration I added one column to it. Here is my code:

df <- data.frame(modelForOneIteration)
for(i in 1:10){
  model <- # some processing
  df[,i] = model

Icons missing in jQuery UI

You need downbload the jQueryUI, this contains de images that you need

enter link description here

Reading/writing an INI file

I'm late to join the party, but I had the same issue today and I've written the following implementation:

using System.Text.RegularExpressions;

static bool match(this string str, string pat, out Match m) =>
    (m = Regex.Match(str, pat, RegexOptions.IgnoreCase)).Success;

static void Main()
    Dictionary<string, Dictionary<string, string>> ini = new Dictionary<string, Dictionary<string, string>>();
    string section = "";

    foreach (string line in File.ReadAllLines(.........)) // read from file
        string ln = (line.Contains('#') ? line.Remove(line.IndexOf('#')) : line).Trim();

        if (ln.match(@"^[ \t]*\[(?<sec>[\w\-]+)\]", out Match m))
            section = m.Groups["sec"].ToString();
        else if (ln.match(@"^[ \t]*(?<prop>[\w\-]+)\=(?<val>.*)", out m))
            if (!ini.ContainsKey(section))
                ini[section] = new Dictionary<string, string>();

            ini[section][m.Groups["prop"].ToString()] = m.Groups["val"].ToString();

    // access the ini file as follows:
    string content = ini["section"]["property"];

It must be noted, that this implementation does not handle sections or properties which are not found. To achieve this, you should extend the Dictionary<,>-class to handle unfound keys.

To serialize an instance of Dictionary<string, Dictionary<string, string>> to an .ini-file, I use the following code:

string targetpath = .........;
Dictionary<string, Dictionary<string, string>> ini = ........;
StringBuilder sb = new StringBuilder();

foreach (string section in ini.Keys)

    foreach (string property in ini[section].Keys)

File.WriteAllText(targetpath, sb.ToString());

what exactly is device pixel ratio?

Device Pixel Ratio == CSS Pixel Ratio

In the world of web development, the device pixel ratio (also called CSS Pixel Ratio) is what determines how a device's screen resolution is interpreted by the CSS.

A browser's CSS calculates a device's logical (or interpreted) resolution by the formula:


For example:

Apple iPhone 6s

  • Actual Resolution: 750 x 1334
  • CSS Pixel Ratio: 2
  • Logical Resolution:


When viewing a web page, the CSS will think the device has a 375x667 resolution screen and Media Queries will respond as if the screen is 375x667. But the rendered elements on the screen will be twice as sharp as an actual 375x667 screen because there are twice as many physical pixels in the physical screen.

Some other examples:

Samsung Galaxy S4

  • Actual Resolution: 1080 x 1920
  • CSS Pixel Ratio: 3
  • Logical Resolution:


iPhone 5s

  • Actual Resolution: 640 x 1136
  • CSS Pixel Ratio: 2
  • Logical Resolution:


Why does the Device Pixel Ratio exist?

The reason that CSS pixel ratio was created is because as phones screens get higher resolutions, if every device still had a CSS pixel ratio of 1 then webpages would render too small to see.

A typical full screen desktop monitor is a roughly 24" at 1920x1080 resolution. Imagine if that monitor was shrunk down to about 5" but had the same resolution. Viewing things on the screen would be impossible because they would be so small. But manufactures are coming out with 1920x1080 resolution phone screens consistently now.

So the device pixel ratio was invented by phone makers so that they could continue to push the resolution, sharpness and quality of phone screens, without making elements on the screen too small to see or read.

Here is a tool that also tells you your current device's pixel density:

Mysql password expired. Can't connect

The password expiration is a new feature in MySQL 5.6 or 5.7.

The answer is clear: Use a client which is capable of expired password changing (I think Sequel Pro can do it).

MySQLi library obviously isnt able to change the expired password.

If you have limited access to localhost and you only have a console client, the standard mysql client can do it.

multi line comment in Visual studio 2010

Highlight block of text, then:

Comment Block: Ctrl + K + C

Uncomment Block: Ctrl + K + U

Tested in Visual Studio 2012

Running Node.Js on Android

the tutorial of how to build NodeJS for Android
there are several versions v0.12, v4, v6, v7

It is easy to run compiled binary on Android; for example run compiled Nginx:

You just need to modify code to replace Nginx to NodeJS; it is better if using Android Service to run node js server on the backend.

JQuery DatePicker ReadOnly

If you're trying to disable the field (without actually disabling it), try setting the onfocus event to this.blur();. This way, whenever the field gets focus, it automatically loses it.

How to enter command with password for git pull?

Note that the way the git credential helper "store" will store the unencrypted passwords changes with Git 2.5+ (Q2 2014).
See commit 17c7f4d by Junio C Hamano (gitster)


Tweak the sample "store" backend of the credential helper to honor XDG configuration file locations when specified.

The doc now say:

If not specified:

  • credentials will be searched for from ~/.git-credentials and $XDG_CONFIG_HOME/git/credentials, and
  • credentials will be written to ~/.git-credentials if it exists, or $XDG_CONFIG_HOME/git/credentials if it exists and the former does not.

input checkbox true or checked or yes

Only checked and checked="checked" are valid. Your other options depend on error recovery in browsers.

checked="yes" and checked="true" are particularly bad as they imply that checked="no" and checked="false" will set the default state to be unchecked … which they will not.

Python append() vs. + operator on lists, why do these give different results?

you should use extend()

>>> c=[1,2,3]
>>> c.extend(c)
>>> c
[1, 2, 3, 1, 2, 3]

other info: append vs. extend

Protractor : How to wait for page complete after click a button?

Depending on what you want to do, you can try:


or {
  // do some stuff 

to solve the promise. It would be better if you can do that in the beforeEach.

NB: I noticed that the expect() waits for the promise inside (i.e. getCurrentUrl) to be solved before comparing.

HTML 5 Video "autoplay" not automatically starting in CHROME

Here is it: You have to add the tags: autoplay="autoplay" loop="loop" or just "autoplay" and "loop".

ASP.NET MVC Ajax Error handling

Unfortunately, neither of answers are good for me. Surprisingly the solution is much simpler. Return from controller:

return new HttpStatusCodeResult(HttpStatusCode.BadRequest, e.Response.ReasonPhrase);

And handle it as standard HTTP error on client as you like.

Find file in directory from command line

Yes, bash has filename completion mechanisms. I don't use them myself (too lazy to learn, and I don't find it necessary often enough to make it urgent), but the basic mechanism is to type the first few characters, and then a tab; this will extend the name as far as it can (perhaps not at all) as long as the name is unambiguous. There are a boatload of Emacs-style commands related to completion in the good ol' man page.

MySQL: selecting rows where a column is null

As all are given answers I want to add little more. I had also faced the same issue.

Why did your query fail? You have,

SELECT pid FROM planets WHERE userid = NULL;

This will not give you the expected result, because from mysql doc

In SQL, the NULL value is never true in comparison to any other value, even NULL. An expression that contains NULL always produces a NULL value unless otherwise indicated in the documentation for the operators and functions involved in the expression.

Emphasis mine.

To search for column values that are NULL, you cannot use an expr = NULL test. The following statement returns no rows, because expr = NULL is never true for any expression


SELECT pid FROM planets WHERE userid IS NULL; 

To test for NULL, use the IS NULL and IS NOT NULL operators.

How do I get client IP address in ASP.NET CORE?

var remoteIpAddress = HttpContext.Features.Get<IHttpConnectionFeature>()?.RemoteIpAddress;

How do I check whether a file exists without exceptions?

How do I check whether a file exists, using Python, without using a try statement?

Now available since Python 3.4, import and instantiate a Path object with the file name, and check the is_file method (note that this returns True for symlinks pointing to regular files as well):

>>> from pathlib import Path
>>> Path('/').is_file()
>>> Path('/initrd.img').is_file()
>>> Path('/doesnotexist').is_file()

If you're on Python 2, you can backport the pathlib module from pypi, pathlib2, or otherwise check isfile from the os.path module:

>>> import os
>>> os.path.isfile('/')
>>> os.path.isfile('/initrd.img')
>>> os.path.isfile('/doesnotexist')

Now the above is probably the best pragmatic direct answer here, but there's the possibility of a race condition (depending on what you're trying to accomplish), and the fact that the underlying implementation uses a try, but Python uses try everywhere in its implementation.

Because Python uses try everywhere, there's really no reason to avoid an implementation that uses it.

But the rest of this answer attempts to consider these caveats.

Longer, much more pedantic answer

Available since Python 3.4, use the new Path object in pathlib. Note that .exists is not quite right, because directories are not files (except in the unix sense that everything is a file).

>>> from pathlib import Path
>>> root = Path('/')
>>> root.exists()

So we need to use is_file:

>>> root.is_file()

Here's the help on is_file:

    Whether this path is a regular file (also True for symlinks pointing
    to regular files).

So let's get a file that we know is a file:

>>> import tempfile
>>> file = tempfile.NamedTemporaryFile()
>>> filepathobj = Path(
>>> filepathobj.is_file()
>>> filepathobj.exists()

By default, NamedTemporaryFile deletes the file when closed (and will automatically close when no more references exist to it).

>>> del file
>>> filepathobj.exists()
>>> filepathobj.is_file()

If you dig into the implementation, though, you'll see that is_file uses try:

def is_file(self):
    Whether this path is a regular file (also True for symlinks pointing
    to regular files).
        return S_ISREG(self.stat().st_mode)
    except OSError as e:
        if e.errno not in (ENOENT, ENOTDIR):
        # Path doesn't exist or is a broken symlink
        # (see
        return False

Race Conditions: Why we like try

We like try because it avoids race conditions. With try, you simply attempt to read your file, expecting it to be there, and if not, you catch the exception and perform whatever fallback behavior makes sense.

If you want to check that a file exists before you attempt to read it, and you might be deleting it and then you might be using multiple threads or processes, or another program knows about that file and could delete it - you risk the chance of a race condition if you check it exists, because you are then racing to open it before its condition (its existence) changes.

Race conditions are very hard to debug because there's a very small window in which they can cause your program to fail.

But if this is your motivation, you can get the value of a try statement by using the suppress context manager.

Avoiding race conditions without a try statement: suppress

Python 3.4 gives us the suppress context manager (previously the ignore context manager), which does semantically exactly the same thing in fewer lines, while also (at least superficially) meeting the original ask to avoid a try statement:

from contextlib import suppress
from pathlib import Path


>>> with suppress(OSError), Path('doesnotexist').open() as f:
...     for line in f:
...         print(line)
>>> with suppress(OSError):
...     Path('doesnotexist').unlink()

For earlier Pythons, you could roll your own suppress, but without a try will be more verbose than with. I do believe this actually is the only answer that doesn't use try at any level in the Python that can be applied to prior to Python 3.4 because it uses a context manager instead:

class suppress(object):
    def __init__(self, *exceptions):
        self.exceptions = exceptions
    def __enter__(self):
        return self
    def __exit__(self, exc_type, exc_value, traceback):
        if exc_type is not None:
            return issubclass(exc_type, self.exceptions)

Perhaps easier with a try:

from contextlib import contextmanager

def suppress(*exceptions):
    except exceptions:

Other options that don't meet the ask for "without try":


import os

from the docs:


Return True if path is an existing regular file. This follows symbolic links, so both islink() and isfile() can be true for the same path.

But if you examine the source of this function, you'll see it actually does use a try statement:

# This follows symbolic links, so both islink() and isdir() can be true
# for the same path on systems that support symlinks
def isfile(path):
    """Test whether a path is a regular file"""
        st = os.stat(path)
    except os.error:
        return False
    return stat.S_ISREG(st.st_mode)
>>> OSError is os.error

All it's doing is using the given path to see if it can get stats on it, catching OSError and then checking if it's a file if it didn't raise the exception.

If you intend to do something with the file, I would suggest directly attempting it with a try-except to avoid a race condition:

    with open(path) as f:
except OSError:


Available for Unix and Windows is os.access, but to use you must pass flags, and it does not differentiate between files and directories. This is more used to test if the real invoking user has access in an elevated privilege environment:

import os
os.access(path, os.F_OK)

It also suffers from the same race condition problems as isfile. From the docs:

Note: Using access() to check if a user is authorized to e.g. open a file before actually doing so using open() creates a security hole, because the user might exploit the short time interval between checking and opening the file to manipulate it. It’s preferable to use EAFP techniques. For example:

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
return "some default data"

is better written as:

    fp = open("myfile")
except IOError as e:
    if e.errno == errno.EACCES:
        return "some default data"
    # Not a permission error.
    with fp:

Avoid using os.access. It is a low level function that has more opportunities for user error than the higher level objects and functions discussed above.

Criticism of another answer:

Another answer says this about os.access:

Personally, I prefer this one because under the hood, it calls native APIs (via "${PYTHON_SRC_DIR}/Modules/posixmodule.c"), but it also opens a gate for possible user errors, and it's not as Pythonic as other variants:

This answer says it prefers a non-Pythonic, error-prone method, with no justification. It seems to encourage users to use low-level APIs without understanding them.

It also creates a context manager which, by unconditionally returning True, allows all Exceptions (including KeyboardInterrupt and SystemExit!) to pass silently, which is a good way to hide bugs.

This seems to encourage users to adopt poor practices.

Remove local git tags that are no longer on the remote repository

Just added a git sync-local-tags command to pivotal_git_scripts Gem fork on GitHub:

Install the gem, then run "git sync-local-tags" in your repository to delete the local tags that do not exist on the remote.

Alternatively you can just install this script below and call it "git-sync-local-tags":

#!/usr/bin/env ruby

# Delete tags from the local Git repository, which are not found on 
# a remote origin
# Usage: git sync-local-tags [-n]
#        if -n is passed, just print the tag to be deleted, but do not 
#        actually delete it.
# Author: Konstantin Gredeskoul (

class TagSynchronizer
  def self.local_tags
    `git show-ref --tags | awk '{print $2}'`.split(/\n/)

  def self.remote_tags
    `git ls-remote --tags origin | awk '{print $2}'`.split(/\n/)

  def self.orphaned_tags
    self.local_tags - self.remote_tags

  def self.remove_unused_tags(print_only = false)
    self.orphaned_tags.each do |ref|
      tag = ref.gsub /refs\/tags\//, ''
      puts "deleting local tag #{tag}"
      `git tag -d #{tag}` unless print_only

unless File.exists?(".git")
  puts "This doesn't look like a git repository."
  exit 1

print_only = ARGV.include?("-n")

Two way sync with rsync

I'm now using SparkleShare

works on mac, linux and windows.

Error:Execution failed for task ':ProjectName:mergeDebugResources'. > Crunching Cruncher *some file* failed, see logs

I was also stuck by this problem.But in my case I delete all .png images from drawable folder ,clean and rebuild application and then paste all .png images to my drawable, rebuild again. It worked fine for me.

How to do a newline in output

I would like to share my experience with \n
I came to notice that "\n" works as-

puts "\n\n" // to provide 2 new lines

but not

p "\n\n"

also puts '\n\n'
Doesn't works.

Hope will work for you!!

What are SP (stack) and LR in ARM?

SP is the stack register a shortcut for typing r13. LR is the link register a shortcut for r14. And PC is the program counter a shortcut for typing r15.

When you perform a call, called a branch link instruction, bl, the return address is placed in r14, the link register. the program counter pc is changed to the address you are branching to.

There are a few stack pointers in the traditional ARM cores (the cortex-m series being an exception) when you hit an interrupt for example you are using a different stack than when running in the foreground, you dont have to change your code just use sp or r13 as normal the hardware has done the switch for you and uses the correct one when it decodes the instructions.

The traditional ARM instruction set (not thumb) gives you the freedom to use the stack in a grows up from lower addresses to higher addresses or grows down from high address to low addresses. the compilers and most folks set the stack pointer high and have it grow down from high addresses to lower addresses. For example maybe you have ram from 0x20000000 to 0x20008000 you set your linker script to build your program to run/use 0x20000000 and set your stack pointer to 0x20008000 in your startup code, at least the system/user stack pointer, you have to divide up the memory for other stacks if you need/use them.

Stack is just memory. Processors normally have special memory read/write instructions that are PC based and some that are stack based. The stack ones at a minimum are usually named push and pop but dont have to be (as with the traditional arm instructions).

If you go to I created a teaching processor and have an assembly language tutorial. Somewhere in there I go through a discussion about stacks. It is NOT an arm processor but the story is the same it should translate directly to what you are trying to understand on the arm or most other processors.

Say for example you have 20 variables you need in your program but only 16 registers minus at least three of them (sp, lr, pc) that are special purpose. You are going to have to keep some of your variables in ram. Lets say that r5 holds a variable that you use often enough that you dont want to keep it in ram, but there is one section of code where you really need another register to do something and r5 is not being used, you can save r5 on the stack with minimal effort while you reuse r5 for something else, then later, easily, restore it.

Traditional (well not all the way back to the beginning) arm syntax:

stmdb r13!,{r5}
...temporarily use r5 for something else...
ldmia r13!,{r5}

stm is store multiple you can save more than one register at a time, up to all of them in one instruction.

db means decrement before, this is a downward moving stack from high addresses to lower addresses.

You can use r13 or sp here to indicate the stack pointer. This particular instruction is not limited to stack operations, can be used for other things.

The ! means update the r13 register with the new address after it completes, here again stm can be used for non-stack operations so you might not want to change the base address register, leave the ! off in that case.

Then in the brackets { } list the registers you want to save, comma separated.

ldmia is the reverse, ldm means load multiple. ia means increment after and the rest is the same as stm

So if your stack pointer were at 0x20008000 when you hit the stmdb instruction seeing as there is one 32 bit register in the list it will decrement before it uses it the value in r13 so 0x20007FFC then it writes r5 to 0x20007FFC in memory and saves the value 0x20007FFC in r13. Later, assuming you have no bugs when you get to the ldmia instruction r13 has 0x20007FFC in it there is a single register in the list r5. So it reads memory at 0x20007FFC puts that value in r5, ia means increment after so 0x20007FFC increments one register size to 0x20008000 and the ! means write that number to r13 to complete the instruction.

Why would you use the stack instead of just a fixed memory location? Well the beauty of the above is that r13 can be anywhere it could be 0x20007654 when you run that code or 0x20002000 or whatever and the code still functions, even better if you use that code in a loop or with recursion it works and for each level of recursion you go you save a new copy of r5, you might have 30 saved copies depending on where you are in that loop. and as it unrolls it puts all the copies back as desired. with a single fixed memory location that doesnt work. This translates directly to C code as an example:

void myfun ( void )
   int somedata;

In a C program like that the variable somedata lives on the stack, if you called myfun recursively you would have multiple copies of the value for somedata depending on how deep in the recursion. Also since that variable is only used within the function and is not needed elsewhere then you perhaps dont want to burn an amount of system memory for that variable for the life of the program you only want those bytes when in that function and free that memory when not in that function. that is what a stack is used for.

A global variable would not be found on the stack.

Going back...

Say you wanted to implement and call that function you would have some code/function you are in when you call the myfun function. The myfun function wants to use r5 and r6 when it is operating on something but it doesnt want to trash whatever someone called it was using r5 and r6 for so for the duration of myfun() you would want to save those registers on the stack. Likewise if you look into the branch link instruction (bl) and the link register lr (r14) there is only one link register, if you call a function from a function you will need to save the link register on each call otherwise you cant return.

bl myfun
    <--- the return from my fun returns here

stmdb sp!,{r5,r6,lr}
sub sp,#4 <--- make room for the somedata variable
some code here that uses r5 and r6
bl more_fun <-- this modifies lr, if we didnt save lr we wouldnt be able to return from myfun
   <---- more_fun() returns here
add sp,#4 <-- take back the stack memory we allocated for the somedata variable
ldmia sp!,{r5,r6,lr}
mov pc,lr <---- return to whomever called myfun.

So hopefully you can see both the stack usage and link register. Other processors do the same kinds of things in a different way. for example some will put the return value on the stack and when you execute the return function it knows where to return to by pulling a value off of the stack. Compilers C/C++, etc will normally have a "calling convention" or application interface (ABI and EABI are names for the ones ARM has defined). if every function follows the calling convention, puts parameters it is passing to functions being called in the right registers or on the stack per the convention. And each function follows the rules as to what registers it does not have to preserve the contents of and what registers it has to preserve the contents of then you can have functions call functions call functions and do recursion and all kinds of things, so long as the stack does not go so deep that it runs into the memory used for globals and the heap and such, you can call functions and return from them all day long. The above implementation of myfun is very similar to what you would see a compiler produce.

ARM has many cores now and a few instruction sets the cortex-m series works a little differently as far as not having a bunch of modes and different stack pointers. And when executing thumb instructions in thumb mode you use the push and pop instructions which do not give you the freedom to use any register like stm it only uses r13 (sp) and you cannot save all the registers only a specific subset of them. the popular arm assemblers allow you to use

push {r5,r6}
pop {r5,r6}

in arm code as well as thumb code. For the arm code it encodes the proper stmdb and ldmia. (in thumb mode you also dont have the choice as to when and where you use db, decrement before, and ia, increment after).

No you absolutly do not have to use the same registers and you dont have to pair up the same number of registers.

push {r5,r6,r7}
pop {r2,r3}
pop {r1}

assuming there is no other stack pointer modifications in between those instructions if you remember the sp is going to be decremented 12 bytes for the push lets say from 0x1000 to 0x0FF4, r5 will be written to 0xFF4, r6 to 0xFF8 and r7 to 0xFFC the stack pointer will change to 0x0FF4. the first pop will take the value at 0x0FF4 and put that in r2 then the value at 0x0FF8 and put that in r3 the stack pointer gets the value 0x0FFC. later the last pop, the sp is 0x0FFC that is read and the value placed in r1, the stack pointer then gets the value 0x1000, where it started.

The ARM ARM, ARM Architectural Reference Manual (, reference manuals, find the one for ARMv5 and download it, this is the traditional ARM ARM with ARM and thumb instructions) contains pseudo code for the ldm and stm ARM istructions for the complete picture as to how these are used. Likewise well the whole book is about the arm and how to program it. Up front the programmers model chapter walks you through all of the registers in all of the modes, etc.

If you are programming an ARM processor you should start by determining (the chip vendor should tell you, ARM does not make chips it makes cores that chip vendors put in their chips) exactly which core you have. Then go to the arm website and find the ARM ARM for that family and find the TRM (technical reference manual) for the specific core including revision if the vendor has supplied that (r2p0 means revision 2.0 (two point zero, 2p0)), even if there is a newer rev, use the manual that goes with the one the vendor used in their design. Not every core supports every instruction or mode the TRM tells you the modes and instructions supported the ARM ARM throws a blanket over the features for the whole family of processors that that core lives in. Note that the ARM7TDMI is an ARMv4 NOT an ARMv7 likewise the ARM9 is not an ARMv9. ARMvNUMBER is the family name ARM7, ARM11 without a v is the core name. The newer cores have names like Cortex and mpcore instead of the ARMNUMBER thing, which reduces confusion. Of course they had to add the confusion back by making an ARMv7-m (cortex-MNUMBER) and the ARMv7-a (Cortex-ANUMBER) which are very different families, one is for heavy loads, desktops, laptops, etc the other is for microcontrollers, clocks and blinking lights on a coffee maker and things like that. google beagleboard (Cortex-A) and the stm32 value line discovery board (Cortex-M) to get a feel for the differences. Or even the board which uses multiple cores at more than a gigahertz or the newer tegra 2 from nvidia, same deal super scaler, muti core, multi gigahertz. A cortex-m barely brakes the 100MHz barrier and has memory measured in kbytes although it probably runs of a battery for months if you wanted it to where a cortex-a not so much.

sorry for the very long post, hope it is useful.

SQL Bulk Insert with FIRSTROW parameter skips the following line

Given how mangled some data can look after BCP importing into SQL Server from non-SQL data sources, I'd suggest doing all the BCP import into some scratch tables first.

For example

truncate table Address_Import_tbl

BULK INSERT dbo.Address_Import_tbl FROM 'E:\external\SomeDataSource\Address.csv' WITH ( FIELDTERMINATOR = '|', ROWTERMINATOR = '\n', MAXERRORS = 10 )

Make sure all the columns in Address_Import_tbl are nvarchar(), to make it as agnostic as possible, and avoid type conversion errors.

Then apply whatever fixes you need to Address_Import_tbl. Like deleting the unwanted header.

Then run a INSERT SELECT query, to copy from Address_Import_tbl to Address_tbl, along with any datatype conversions you need. For example, to cast imported dates to SQL DATETIME.

Writing file to web server - ASP.NET

Keep in mind you'll also have to give the IUSR account write access for the folder once you upload to your web server.

Personally I recommend not allowing write access to the root folder unless you have a good reason for doing so. And then you need to be careful what sort of files you allow to be saved so you don't inadvertently allow someone to write their own ASPX pages.

Pandas: create two new columns in a dataframe with values calculated from a pre-existing column

The top answer is flawed in my opinion. Hopefully, no one is mass importing all of pandas into their namespace with from pandas import *. Also, the map method should be reserved for those times when passing it a dictionary or Series. It can take a function but this is what apply is used for.

So, if you must use the above approach, I would write it like this

df["A1"], df["A2"] = zip(*df["a"].apply(calculate))

There's actually no reason to use zip here. You can simply do this:

df["A1"], df["A2"] = calculate(df['a'])

This second method is also much faster on larger DataFrames

df = pd.DataFrame({'a': [1,2,3] * 100000, 'b': [2,3,4] * 100000})

DataFrame created with 300,000 rows

%timeit df["A1"], df["A2"] = calculate(df['a'])
2.65 ms ± 92.4 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

%timeit df["A1"], df["A2"] = zip(*df["a"].apply(calculate))
159 ms ± 5.24 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

60x faster than zip

In general, avoid using apply

Apply is generally not much faster than iterating over a Python list. Let's test the performance of a for-loop to do the same thing as above

A1, A2 = [], []
for val in df['a']:

df['A1'] = A1
df['A2'] = A2

298 ms ± 7.14 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

So this is twice as slow which isn't a terrible performance regression, but if we cythonize the above, we get much better performance. Assuming, you are using ipython:

%load_ext cython

cpdef power(vals):
    A1, A2 = [], []
    cdef double val
    for val in vals:

    return A1, A2

%timeit df['A1'], df['A2'] = power(df['a'])
72.7 ms ± 2.16 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

Directly assigning without apply

You can get even greater speed improvements if you use the direct vectorized operations.

%timeit df['A1'], df['A2'] = df['a'] ** 2, df['a'] ** 3
5.13 ms ± 320 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

This takes advantage of NumPy's extremely fast vectorized operations instead of our loops. We now have a 30x speedup over the original.

The simplest speed test with apply

The above example should clearly show how slow apply can be, but just so its extra clear let's look at the most basic example. Let's square a Series of 10 million numbers with and without apply

s = pd.Series(np.random.rand(10000000))

%timeit s.apply(calc)
3.3 s ± 57.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

Without apply is 50x faster

%timeit s ** 2
66 ms ± 2 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

Angular2 use [(ngModel)] with [ngModelOptions]="{standalone: true}" to link to a reference to model's property

<form (submit)="addTodo()">_x000D_
  <input type="text" [(ngModel)]="text">_x000D_

How to avoid 'cannot read property of undefined' errors?


  • If you use JavaScript according to ECMAScript 2020 or later, see optional chaining.
  • TypeScript has added support for optional chaining in version 3.7.
// use it like this

Solution for JavaScript before ECMASCript 2020 or TypeScript older than version 3.7:

A quick workaround is using a try/catch helper function with ES6 arrow function:

function getSafe(fn, defaultVal) {
  try {
    return fn();
  } catch (e) {
    return defaultVal;

// use it like this
console.log(getSafe(() =>;

// or add an optional default value
console.log(getSafe(() =>, 'nothing'));

How can I iterate over an enum?

C++ doesn't have introspection, so you can't determine this kind of thing at run-time.

Find text in string with C#

I have different approach on ReplaceTextBetween() function.

public static string ReplaceTextBetween(this string strSource, string strStart, string strEnd, string strReplace)
            if (strSource.Contains(strStart) && strSource.Contains(strEnd))
                var startIndex = strSource.IndexOf(strStart, 0) + strStart.Length;

                var endIndex = strSource.IndexOf(strEnd, startIndex);

                var strSourceLength = strSource.Length;

                var strToReplace = strSource.Substring(startIndex, endIndex - startIndex);

                var concatStart = startIndex + strToReplace.Length;

                var beforeReplaceStr = strSource.Substring(0, startIndex);

                var afterReplaceStr = strSource.Substring(concatStart, strSourceLength - endIndex);

                return string.Concat(beforeReplaceStr, strReplace, afterReplaceStr);

            return strSource;

How to get Client location using Google Maps API v3?

Try this :)

    <script type="text/javascript" src=""></script>
    <script type="text/javascript">
    function initialize() {
        var loc = {};
        var geocoder = new google.maps.Geocoder();
        if(google.loader.ClientLocation) {
   = google.loader.ClientLocation.latitude;
            loc.lng = google.loader.ClientLocation.longitude;

            var latlng = new google.maps.LatLng(, loc.lng);
            geocoder.geocode({'latLng': latlng}, function(results, status) {
                if(status == google.maps.GeocoderStatus.OK) {

    google.load("maps", "3.x", {other_params: "sensor=false", callback:initialize});


Python: PIP install path, what is the correct location for this and other addons?

Since pip is an executable and which returns path of executables or filenames in environment. It is correct. Pip module is installed in site-packages but the executable is installed in bin.

How can I change the color of my prompt in zsh (different from normal text)?

Zsh comes with colored prompts builtin. Try

autoload -U promptinit && promptinit

and then prompt -l lists available prompts, -p fire previews the "fire" prompt, -s fire sets it.

When you are ready to add a prompt add something like this below the autoload line above:

prompt fade red

With MySQL, how can I generate a column containing the record index in a table?

SELECT @i:=@i+1 AS iterator, t.*
FROM tablename t,(SELECT @i:=0) foo

What is the best way to insert source code examples into a Microsoft Word document?

These answers look outdated and quite tedious compared to the web add-in solution; which is available for products since Office 2013.

I'm using Easy Code Formatter, which allows you to codify the text in-place. It also gives you line-numbering options, highlighting, different styles and the styles are open sourced here: so you could extend the styling yourself. To install - open Microsoft Word, go to Insert Tab / click "Get Add-ins" and search for "Easy Code Formatter"

enter image description here enter image description here enter image description here

Why use @Scripts.Render("~/bundles/jquery")

Bundling is all about compressing several JavaScript or stylesheets files without any formatting (also referred as minified) into a single file for saving bandwith and number of requests to load a page.

As example you could create your own bundle:

bundles.Add(New ScriptBundle("~/bundles/mybundle").Include(

And render it like this:


One more advantage of @Scripts.Render("~/bundles/mybundle") over the native <script src="~/bundles/mybundle" /> is that @Scripts.Render() will respect the web.config debug setting:

    <compilation debug="true|false" />

If debug="true" then it will instead render individual script tags for each source script, without any minification.

For stylesheets you will have to use a StyleBundle and @Styles.Render().

Instead of loading each script or style with a single request (with script or link tags), all files are compressed into a single JavaScript or stylesheet file and loaded together.

What do I do when my program crashes with exception 0xc0000005 at address 0?

Exception code 0xc0000005 is an Access Violation. An AV at fault offset 0x00000000 means that something in your service's code is accessing a nil pointer. You will just have to debug the service while it is running to find out what it is accessing. If you cannot run it inside a debugger, then at least install a third-party exception logger framework, such as EurekaLog or MadExcept, to find out what your service was doing at the time of the AV.

'"SDL.h" no such file or directory found' when compiling

the simplest idea is to add pkg-config --cflags --libs sdl2 while compiling the code.

g++ file.cpp `pkg-config --cflags --libs sdl2`

How to reset db in Django? I get a command 'reset' not found error

It looks like the 'flush' answer will work for some, but not all cases. I needed not just to flush the values in the database, but to recreate the tables properly. I'm not using migrations yet (early days) so I really needed to drop all the tables.

Two ways I've found to drop all tables, both require something other than core django.

If you're on Heroku, drop all the tables with pg:reset:

heroku pg:reset DATABASE_URL
heroku run python syncdb

If you can install Django Extensions, it has a way to do a complete reset:

python ./ reset_db --router=default

Forwarding port 80 to 8080 using NGINX

This is how you can achieve this.

upstream {

server {
    listen 80;

    # The host name to respond to

    location /(.*) {
        proxy_pass http://nodeapp/$1$is_args$args;
        proxy_set_header X-Real-IP  $remote_addr;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_set_header Host $host;
        proxy_set_header X-Real-Port $server_port;
        proxy_set_header X-Real-Scheme $scheme;

You can also use this configuration to load balance amongst multiple Node processes like so:

upstream {

Where you are running your node server on ports 8081, 8082 and 8083 in separate processes. Nginx will easily load balance your traffic amongst these server processes.

Bi-directional Map in Java?

There is no bidirectional map in the Java Standard API. Either you can maintain two maps yourself or use the BidiMap from Apache Collections.

How to parse XML using shellscript?

A rather new project is the xml-coreutils package featuring xml-cat, xml-cp, xml-cut, xml-grep, ...

How to add a new project to Github using VS Code

You can create a GitHub repo via the command line using the GitHub API. Outside of the API, there's no way to create a repo on GitHub via the command line.


curl -u 'username' -d '{"name":"projectname","description":"project desc"}'

git remote add origin [email protected]:nyeates/projectname.git

and now you can continue regular way

Adding a directory to PATH in Ubuntu

you can set it in .bashrc

PATH=$PATH:/opt/ActiveTcl-8.5/bin;export PATH;

Is there a way to make a PowerShell script work by double clicking a .ps1 file?

If you are familiar with advanced Windows administration, then you can use this ADM package (instructions are included on that page) and allow running PowerShell scripts after double click via this template and Local GPO. After this you can simply change default program associated to .ps1 filetype to powershell.exe (use search, it's quite stashed) and you're ready to run PowerShell scripts with double click.

Otherwise, I would recommend to stick with other suggestions as you can mess up the whole system with these administrations tools.

I think that the default settings are too strict. If someone manages to put some malicious code on your computer then he/she is also able to bypass this restriction (wrap it into .cmd file or .exe, or trick with shortcut) and all that it in the end accomplishes is just to prevent you from easy way of running the script you've written.

In Laravel, the best way to pass different types of flash messages in the session

My way is to always Redirect::back() or Redirect::to():

Redirect::back()->with('message', 'error|There was an error...');

Redirect::back()->with('message', 'message|Record updated.');

Redirect::to('/')->with('message', 'success|Record updated.');

I have a helper function to make it work for me, usually this is in a separate service:

function displayAlert()
      if (Session::has('message'))
         list($type, $message) = explode('|', Session::get('message'));

         $type = $type == 'error' : 'danger';
         $type = $type == 'message' : 'info';

         return sprintf('<div class="alert alert-%s">%s</div>', $type, message);

      return '';

And in my view or layout I just do

{{ displayAlert() }}

Select objects based on value of variable in object using jq

Adapted from this post on Processing JSON with jq, you can use the select(bool) like this:

$ jq '.[] | select(.location=="Stockholm")' json
  "location": "Stockholm",
  "name": "Walt"
  "location": "Stockholm",
  "name": "Donald"

Running a simple shell script as a cronjob


 # cat
 /bin/touch file.txt

cron as:

 * * * * * /bin/sh /home/myUser/scripts/

And you can confirm this by:

 # tailf /var/log/cron

The equivalent of a GOTO in python

Forgive me - I couldn't resist ;-)

def goto(linenum):
    global line
    line = linenum

line = 1
while True:
    if line == 1:
        response = raw_input("yes or no? ")
        if response == "yes":
        elif response == "no":
    elif line == 2:
        print "Thank you for the yes!"
    elif line == 3:
        print "Thank you for the no!"
    elif line == 20:
    elif line == 100:
        print "You're annoying me - answer the question!"

Call a VBA Function into a Sub Procedure

Calling a Sub Procedure – 3 Way technique

Once you have a procedure, whether you created it or it is part of the Visual Basic language, you can use it. Using a procedure is also referred to as calling it.

Before calling a procedure, you should first locate the section of code in which you want to use it. To call a simple procedure, type its name. Here is an example:

Sub CreateCustomer()
    Dim strFullName As String

    strFullName = "Paul Bertrand Yamaguchi"

msgbox strFullName
End Sub

Sub Exercise()
End Sub

Besides using the name of a procedure to call it, you can also precede it with the Call keyword. Here is an example:

Sub CreateCustomer()
    Dim strFullName As String

    strFullName = "Paul Bertrand Yamaguchi"
End Sub

Sub Exercise()
    Call CreateCustomer
End Sub

When calling a procedure, without or without the Call keyword, you can optionally type an opening and a closing parentheses on the right side of its name. Here is an example:

Sub CreateCustomer()
    Dim strFullName As String

    strFullName = "Paul Bertrand Yamaguchi"
End Sub

Sub Exercise()
End Sub

Procedures and Access Levels

Like a variable access, the access to a procedure can be controlled by an access level. A procedure can be made private or public. To specify the access level of a procedure, precede it with the Private or the Public keyword. Here is an example:

Private Sub CreateCustomer()
    Dim strFullName As String

    strFullName = "Paul Bertrand Yamaguchi"
End Sub

The rules that were applied to global variables are the same:

Private: If a procedure is made private, it can be called by other procedures of the same module. Procedures of outside modules cannot access such a procedure.

Also, when a procedure is private, its name does not appear in the Macros dialog box

Public: A procedure created as public can be called by procedures of the same module and by procedures of other modules.

Also, if a procedure was created as public, when you access the Macros dialog box, its name appears and you can run it from there

sql server #region

(I am developer of SSMSBoost add-in for SSMS)

We have recently added support for this syntax into our SSMSBoost add-in.

--#region [Optional Name]

It has also an option to automatically "recognize" regions when opening scripts.

Javascript callback when IFRAME is finished loading?

The innerHTML of your iframe is blank because your iframe tag doesn't surround any content in the parent document. In order to get the content from the page referred to by the iframe's src attribute, you need to access the iframe's contentDocument property. An exception will be thrown if the src is from a different domain though. This is a security feature that prevents you from executing arbitrary JavaScript on someone else's page, which would create a cross-site scripting vulnerability. Here is some example code the illustrates what I'm talking about:

<script src="" type="text/javascript"></script>


<script type="text/javascript">
function on_load(iframe) {
  try {
    // Displays the first 50 chars in the innerHTML of the
    // body of the page that the iframe is showing.
    // EDIT 2012-04-17: for wider support, fallback to contentWindow.document
    var doc = iframe.contentDocument || iframe.contentWindow.document;
    alert(doc.body.innerHTML.substring(0, 50));
  } catch (e) {
    // This can happen if the src of the iframe is
    // on another domain
    alert('exception: ' + e);
<iframe id="child" src="iframe_content.html" onload="on_load(this)"></iframe>

To further the example, try using this as the content of the iframe:


<a href="">Google</a>

<p>Use the preceeding link to change the src of the iframe
to see what happens when the src domain is different from
that of the parent page</p>

Which tool to build a simple web front-end to my database

I think PHP is a good solution. It's simple to set up, free and there is plenty of documentation on how to create a database management app. Ruby on Rails is faster to code but a bit more difficult to set up.

system("pause"); - Why is it wrong?

Because it is not portable.


is a windows / dos only program, so this your code won't run on linux. Moreover, system is not generally regarded as a very good way to call another program - it is usually better to use CreateProcess or fork or something similar.

HTML5 video - show/hide controls programmatically

<video id="myvideo">
  <source src="path/to/movie.mp4" />

<p onclick="toggleControls();">Toggle</p>

var video = document.getElementById("myvideo");

function toggleControls() {
  if (video.hasAttribute("controls")) {
  } else {

See it working on jsFiddle:

Node.js version on the command line? (not the REPL)

If you are windows user and using command line to check following versions then:

  1. Check node version

    node -v

  2. Check npm version

    npm -v

Angular 2 : No NgModule metadata found

I had the same problem and couldn't solve it after reading all the above answers. Then I noticed that an extra comma in declarations was creating a problem. Removed it, problem solved.

    imports: [
    declarations: [

Selector on background color of TextView

An even simpler solution to the above:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="">
    <item android:state_pressed="true">
        <color android:color="@color/semitransparent_white" />
        <color android:color="@color/transparent" />

Save that in the drawable folder and you're good to go.

How do I install a custom font on an HTML site

For the best possible browser support, your CSS code should look like this :

@font-face {
  font-family: 'MyWebFont';
  src: url('webfont.eot'); /* IE9 Compat Modes */
  src: url('webfont.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
       url('webfont.woff2') format('woff2'), /* Super Modern Browsers */
       url('webfont.woff') format('woff'), /* Pretty Modern Browsers */
       url('webfont.ttf')  format('truetype'), /* Safari, Android, iOS */
       url('webfont.svg#svgFontName') format('svg'); /* Legacy iOS */

body {
  font-family: 'MyWebFont', Fallback, sans-serif;

For more info, see the article Using @font-face at

How to expire a cookie in 30 minutes using jQuery?

30 minutes is 30 * 60 * 1000 miliseconds. Add that to the current date to specify an expiration date 30 minutes in the future.

 var date = new Date();
 var minutes = 30;
 date.setTime(date.getTime() + (minutes * 60 * 1000));
 $.cookie("example", "foo", { expires: date });

Put text at bottom of div

If you only have one line of text and your div has a fixed height, you can do this:

div {
    line-height: (2*height - font-size);
    text-align: right;

See fiddle.

Sql Server trigger insert values from new row into another table

trigger `[dbo].[mytrigger]` on `[dbo].[Patients]` after update , insert as
     --Sql logic
     print 'Hello world'     

Implementing two interfaces in a class with same method. Which interface method is overridden?

Try implementing the interface as anonymous.

public class MyClass extends MySuperClass implements MyInterface{

MyInterface myInterface = new MyInterface(){

/* Overrided method from interface */
public void method1(){



/* Overrided method from superclass*/
public void method1(){



Force HTML5 youtube video

I've found the solution :

You have to add the html5=1 in the src attribute of the iframe :

<iframe src=""></iframe>

The video will be displayed as HTML5 if available, or fallback into flash player.

Radio button checked event handling

You can simply use the method change of JQuery to get the value of the current radio checked with the following code:

$(document).on('change', '[type="radio"]', function() {
    var currentlyValue = $(this).val(); // Get the radio checked value
    alert('Currently value: '+currentlyValue); // Show a alert with the current value

You can change the selector '[type="radio"]' for a class or id that you want.

How can I add an item to a IEnumerable<T> collection?

To add second message you need to -

IEnumerable<T> items = new T[]{new T("msg")};
items = items.Concat(new[] {new T("msg2")})

Iterating through a string word by word

s = 'hi how are you'
l = list(map(lambda x: x,s.split()))

Output: ['hi', 'how', 'are', 'you']

How to pass arguments from command line to gradle

If you need to check and set one argument, your build.gradle file would be like this:


def coverageThreshold = 0.15

if (project.hasProperty('threshold')) {
    coverageThreshold ='threshold').toString().toBigDecimal()

//print the value of variable
println("Coverage Threshold: $coverageThreshold")

And the Sample command in windows:

gradlew clean test -Pthreshold=0.25

How to continue the code on the next line in VBA

(i, j, n + 1) = k * b_xyt(xi, yi, tn) / (4 * hx * hy) * U_matrix(i + 1, j + 1, n) + _
(k * (a_xyt(xi, yi, tn) / hx ^ 2 + d_xyt(xi, yi, tn) / (2 * hx)))

From ms support

To continue a statement from one line to the next, type a space followed by the line-continuation character [the underscore character on your keyboard (_)].

You can break a line at an operator, list separator, or period.

Efficiently counting the number of lines of a text file. (200mb+)

You have several options. The first is to increase the availble memory allowed, which is probably not the best way to do things given that you state the file can get very large. The other way is to use fgets to read the file line by line and increment a counter, which should not cause any memory issues at all as only the current line is in memory at any one time.

PostgreSQL: Resetting password of PostgreSQL on Ubuntu

Assuming you're the administrator of the machine, Ubuntu has granted you the right to sudo to run any command as any user.
Also assuming you did not restrict the rights in the pg_hba.conf file (in the /etc/postgresql/9.1/main directory), it should contain this line as the first rule:

# Database administrative login by Unix domain socket  
local   all             postgres                                peer

(About the file location: 9.1 is the major postgres version and main the name of your "cluster". It will differ if using a newer version of postgres or non-default names. Use the pg_lsclusters command to obtain this information for your version/system).

Anyway, if the pg_hba.conf file does not have that line, edit the file, add it, and reload the service with sudo service postgresql reload.

Then you should be able to log in with psql as the postgres superuser with this shell command:

sudo -u postgres psql

Once inside psql, issue the SQL command:

ALTER USER postgres PASSWORD 'newpassword';

In this command, postgres is the name of a superuser. If the user whose password is forgotten was ritesh, the command would be:

ALTER USER ritesh PASSWORD 'newpassword';

References: PostgreSQL 9.1.13 Documentation, Chapter 19. Client Authentication

Keep in mind that you need to type postgres with a single S at the end

If leaving the password in clear text in the history of commands or the server log is a problem, psql provides an interactive meta-command to avoid that, as an alternative to ALTER USER ... PASSWORD:

\password username

It asks for the password with a double blind input, then hashes it according to the password_encryption setting and issue the ALTER USER command to the server with the hashed version of the password, instead of the clear text version.

Could not load file or assembly '***.dll' or one of its dependencies

1) Copy DLLs from "Externals\ffmpeg\bin" to your project's output directory (where executable stays); 2) Make sure your project is built for x86 target (runs in 32-bit mode).

Follow this thread for more

Add item to Listview control

The ListView control uses the Items collection to add items to listview in the control and is able to customize items.

How to configure SSL certificates with Charles Web Proxy and the latest Android Emulator on Windows?

To remotely capture http or https traffic with charles you will need to do the following:

HOST - Machine running Charles and hosting the proxy CLIENT – User’s machine generating the traffic you will capture

Host Machine

  1. Install fully licensed charles version
  2. Proxy -> Proxy Settings -> check “Enable Transparent HTTP Proxying”
  3. Proxy -> SSL Proxying Settings -> check “enable SSL Proxying”
  4. Proxy -> SSL Proxying Settings -> click Add button and input * in both fields
  5. Proxy -> Access Control Settings -> Add your local subnet (ex: to authorize all machines on your local network to use the proxy from another machine
  6. It might be advisable to set up the “auto save tool” in charles, this will auto save and rotate the charles logs.

Client Machine:

  1. Install and permanently accept/trust the charles SSL certificate
  2. Configure IE, Firefox, and Chrome to use the socket charles is hosting the proxy on (ex:

When I tested this out I picked up two lines of a Facebook HTTPS chat (one was a line TO someone, and the other FROM)

you can also capture android emulator traffic this way if you start the emulator with:

emulator -avd <avd name> -http-proxy http://local_ip:8888/

Where LOCAL_IP is the IP address of your computer, not as that is the IP address of the emulated phone.


How do I schedule jobs in Jenkins?

Jenkins lets you set up multiple times, separated by line breaks.

If you need it to build daily at 7 am, along with every Sunday at 4 pm, the below works well.

H 7 * * *

H 16 * * 0

iPhone UIView Animation Best Practice

We can animate images in ios 5 using this simple code.

CGRect imageFrame = imageView.frame;
imageFrame.origin.y = self.view.bounds.size.height;

[UIView animateWithDuration:0.5
    options: UIViewAnimationCurveEaseOut
        imageView.frame = imageFrame;
    completion:^(BOOL finished){

How to rollback a specific migration?

From Rails Guide

Reverting Previous Migrations

You can use Active Record's ability to rollback migrations using the revert method:

require_relative '20100905201547_create_blocks'

class FixupCreateBlock < ActiveRecord::Migration
  def change
    revert CreateBlock

    create_table(:apples) do |t|
      t.string :variety

The revert method also accepts a block of instructions to reverse. This could be useful to revert selected parts of previous migrations. For example, let's imagine that CreateBlock is committed and it is later decided it would be best to use Active Record validations, in place of the CHECK constraint, to verify the zipcode.

    class DontUseConstraintForZipcodeValidationMigration < ActiveRecord::Migration
      def change
        revert do
          # copy-pasted code from CreateBlock
          reversible do |dir|
            dir.up do
              # add a CHECK constraint
              execute <<-SQL
                ALTER TABLE distributors
                  ADD CONSTRAINT zipchk
                    CHECK (char_length(zipcode) = 5);
            dir.down do
              execute <<-SQL
                ALTER TABLE distributors
                  DROP CONSTRAINT zipchk

          # The rest of the migration was ok

The same migration could also have been written without using revert but this would have involved a few more steps: reversing the order of create_table and reversible, replacing create_table by drop_table, and finally replacing up by down and vice-versa. This is all taken care of by revert.

How can I send large messages with Kafka (over 15MB)?

You need to adjust three (or four) properties:

  • Consumer side:fetch.message.max.bytes - this will determine the largest size of a message that can be fetched by the consumer.
  • Broker side: replica.fetch.max.bytes - this will allow for the replicas in the brokers to send messages within the cluster and make sure the messages are replicated correctly. If this is too small, then the message will never be replicated, and therefore, the consumer will never see the message because the message will never be committed (fully replicated).
  • Broker side: message.max.bytes - this is the largest size of the message that can be received by the broker from a producer.
  • Broker side (per topic): max.message.bytes - this is the largest size of the message the broker will allow to be appended to the topic. This size is validated pre-compression. (Defaults to broker's message.max.bytes.)

I found out the hard way about number 2 - you don't get ANY exceptions, messages, or warnings from Kafka, so be sure to consider this when you are sending large messages.

Scraping data from website using vba

There are several ways of doing this. This is an answer that I write hoping that all the basics of Internet Explorer automation will be found when browsing for the keywords "scraping data from website", but remember that nothing's worth as your own research (if you don't want to stick to pre-written codes that you're not able to customize).

Please note that this is one way, that I don't prefer in terms of performance (since it depends on the browser speed) but that is good to understand the rationale behind Internet automation.

1) If I need to browse the web, I need a browser! So I create an Internet Explorer browser:

Dim appIE As Object
Set appIE = CreateObject("internetexplorer.application")

2) I ask the browser to browse the target webpage. Through the use of the property ".Visible", I decide if I want to see the browser doing its job or not. When building the code is nice to have Visible = True, but when the code is working for scraping data is nice not to see it everytime so Visible = False.

With appIE
    .Navigate ""
    .Visible = True
End With

3) The webpage will need some time to load. So, I will wait meanwhile it's busy...

Do While appIE.Busy

4) Well, now the page is loaded. Let's say that I want to scrape the change of the US30Y T-Bond: What I will do is just clicking F12 on Internet Explorer to see the webpage's code, and hence using the pointer (in red circle) I will click on the element that I want to scrape to see how can I reach my purpose.

enter image description here

5) What I should do is straight-forward. First of all, I will get by the ID property the tr element which is containing the value:

Set allRowOfData = appIE.document.getElementById("pair_8907")

Here I will get a collection of td elements (specifically, tr is a row of data, and the td are its cells. We are looking for the 8th, so I will write:

Dim myValue As String: myValue = allRowOfData.Cells(7).innerHTML

Why did I write 7 instead of 8? Because the collections of cells starts from 0, so the index of the 8th element is 7 (8-1). Shortly analysing this line of code:

  • .Cells() makes me access the td elements;
  • innerHTML is the property of the cell containing the value we look for.

Once we have our value, which is now stored into the myValue variable, we can just close the IE browser and releasing the memory by setting it to Nothing:

Set appIE = Nothing

Well, now you have your value and you can do whatever you want with it: put it into a cell (Range("A1").Value = myValue), or into a label of a form (Me.label1.Text = myValue).

I'd just like to point you out that this is not how StackOverflow works: here you post questions about specific coding problems, but you should make your own search first. The reason why I'm answering a question which is not showing too much research effort is just that I see it asked several times and, back to the time when I learned how to do this, I remember that I would have liked having some better support to get started with. So I hope that this answer, which is just a "study input" and not at all the best/most complete solution, can be a support for next user having your same problem. Because I have learned how to program thanks to this community, and I like to think that you and other beginners might use my input to discover the beautiful world of programming.

Enjoy your practice ;)

Select dropdown with fixed width cutting off content in IE

A workaround if you don't care about the strange view after an option is selected (i.e. Select to jump to a new page):

<!-- Limit width of the wrapping div instead of the select and use 'overflow: hidden' to hide the right part of it. -->
<div style='width: 145px; overflow: hidden; border-right: 1px solid #aaa;'>
  <select onchange='jump();'>
    <!-- '&#9660;(?)' produces a fake dropdown indicator -->
    <option value=''>Jump to ... &#9660;</option>
    <option value='1'></option>

Git push error: "origin does not appear to be a git repository"

my case was a little different - unintentionally I have changed owner of git repository (project.git directory in my case), changing owner back to the git user helped

How can I check if an InputStream is empty without reading from it?

How about using inputStreamReader.ready() to find out?


/// ...

InputStreamReader reader = new InputStreamReader(inputStream);
if (reader.ready()) {
    // do something

// ...

concat scope variables into string in angular directive expression

You can just concat the values using +

<a ng-click="$navigate.go('#/path/' + obj.val1 + '/' + obj.val2)">{{obj.val1}}, {{obj.val2}}</a>

Simple example on jsfiddle

I am sure the code you posted is a simplified example, if your path building is more complex I would recommend extracting out a function (or service) that would build your urls so you can effectively write unit test.

Git Bash: Could not open a connection to your authentication agent

I would like to improve on the accepted answer

Downsides of using .bashrc with eval ssh-agent -s:

  1. Every git-bash will have it's own ssh-agent.exe process
  2. SSH key should be manually added every time you open git-bash

Here is my .bashrc that will eradicate above downsides

Put this .bashrc into your home directory (Windows 10: C:\Users\[username]\.bashrc) and it will be executed every time a new git-bash is opened and ssh-add will be working as a first class citizen

Read #comments to understand how it works

# Env vars used
# SSH_AUTH_SOCK - ssh-agent socket, should be set for ssh-add or git to be able to connect
# SSH_AGENT_PID - ssh-agent process id, should be set in order to check that it is running
# SSH_AGENT_ENV - env file path to share variable between instances of git-bash
# import env file and supress error message if it does not exist
. $SSH_AGENT_ENV 2> /dev/null

# if we know that ssh-agent was launched before ($SSH_AGENT_PID is set) and process with that pid is running 
if [ -n "$SSH_AGENT_PID" ] && ps -p $SSH_AGENT_PID > /dev/null 
  # we don't need to do anything, ssh-add and git will properly connect since we've imported env variables required
  echo "Connected to ssh-agent"
  # start ssh-agent and save required vars for sharing in $SSH_AGENT_ENV file
  eval $(ssh-agent) > /dev/null
  echo "Started ssh-agent"

Also this script uses a little trick to ensure that provided environment variables are shared between git-bash instances by saving them into an .env file.

How does one target IE7 and IE8 with valid CSS?

Explicitly Target IE versions without hacks using HTML and CSS

Use this approach if you don't want hacks in your CSS. Add a browser-unique class to the <html> element so you can select based on browser later.


<!doctype html>
<!--[if IE]><![endif]-->
<!--[if lt IE 7 ]> <html lang="en" class="ie6">    <![endif]-->
<!--[if IE 7 ]>    <html lang="en" class="ie7">    <![endif]-->
<!--[if IE 8 ]>    <html lang="en" class="ie8">    <![endif]-->
<!--[if IE 9 ]>    <html lang="en" class="ie9">    <![endif]-->
<!--[if (gt IE 9)|!(IE)]><!--><html lang="en"><!--<![endif]-->

Then in your CSS you can very strictly access your target browser.


.ie6 body { 
    border:1px solid red;
.ie7 body { 
    border:1px solid blue;

For more information check out

Target IE versions with CSS "Hacks"

More to your point, here are the hacks that let you target IE versions.

Use "\9" to target IE8 and below.
Use "*" to target IE7 and below.
Use "_" to target IE6.


body { 
border:1px solid red; /* standard */
border:1px solid blue\9; /* IE8 and below */
*border:1px solid orange; /* IE7 and below */
_border:1px solid blue; /* IE6 */

Update: Target IE10

IE10 does not recognize the conditional statements so you can use this to apply an "ie10" class to the <html> element

<!doctype html>
    <html lang="en">
    <!--[if !IE]><!--><script>if (/*@cc_on!@*/false) {document.documentElement.className+=' ie10';}</script><!--<![endif]-->

Avoid synchronized(this) in Java?

Short answer: You have to understand the difference and make choice depending on the code.

Long answer: In general I would rather try to avoid synchronize(this) to reduce contention but private locks add complexity you have to be aware of. So use the right synchronization for the right job. If you are not so experienced with multi-threaded programming I would rather stick to instance locking and read up on this topic. (That said: just using synchronize(this) does not automatically make your class fully thread-safe.) This is a not an easy topic but once you get used to it, the answer whether to use synchronize(this) or not comes naturally.

Downloading a Google font and setting up an offline site that uses it

If you'd like to explicitly declare your package dependencies or automate the download, you can add a node package to pull in google fonts and serve locally.

npm - Google Font Downloads

The typefaces project creates NPM packages for Open Source typefaces :

Each package ships with all the necessary fons and css to self-host an open source typeface.
All Google Fonts have been added as well as a small but growing list of other open source fonts.

Just search npm for typeface-<typefacename> to browse the available fonts like typeface-roboto or typeface-open-sans and install like this:

$ npm install typeface-roboto    --save 
$ npm install typeface-open-sans --save 
$ npm install material-icons     --save 

npm - Google Fonts Download-ers

For the more generic use case, there are several npm packages that will deliver fonts in two steps, first by obtaining the package, and then by pointing it to the font name and options you'd like to include.

Here are some of the options:

Further Reading:

If/else else if in Jquery for a condition

If statement for images in jquery:

<button id="chain">Chain</button>
<img src="bulb_on.jpg" alt="img" id="img"/>

                $("#img").attr('src', 'bulb_on.jpg');
                $("#img").attr('src', 'bulb_onn.jpg');

Connecting to SQL Server with Visual Studio Express Editions

You should be able to choose the SQL Server Database file option to get the right kind of database (the provider), and then manually correct the connection string to point to your db.

I think the reasoning behind those db choices probably goes something like this:

  • If you're using the Express Edition, and you're not using Visual Web Developer, you're probably building a desktop program.
  • If you're building a desktop program, and you're using the express edition, you're probably a hobbyist or uISV-er working at home rather than doing development for a corporation.
  • If you're not developing for a corporation, your app is probably destined for the end-user and your data store is probably going on their local machine.
  • You really shouldn't be deploying server-class databases to end-user desktops. An in-process db like Sql Server Compact or MS Access is much more appropriate.

However, this logic doesn't quite hold. Even if each of those 4 points is true 90% of the time, by the time you apply all four of them it only applies to ~65% of your audience, which means up to 35% of the express market might legitimately want to talk to a server-class db, and that's a significant group. And so, the simplified (greedy) version:

  • A real db server (and the hardware to run it) costs real money. If you have access to that, you ought to be able to afford at least the standard edition of visual studio.

How to handle button clicks using the XML onClick within Fragments

The problem I think is that the view is still the activity, not the fragment. The fragments doesn't have any independent view of its own and is attached to the parent activities view. Thats why the event ends up in the Activity, not the fragment. Its unfortunate, but I think you will need some code to make this work.

What I've been doing during conversions is simply adding a click listener that calls the old event handler.

for instance:

final Button loginButton = (Button) view.findViewById(;
loginButton.setOnClickListener(new OnClickListener() {
    public void onClick(final View v) {

How can I convert this foreach code to Parallel.ForEach?

Foreach loop:

  • Iterations takes place sequentially, one by one
  • foreach loop is run from a single Thread.
  • foreach loop is defined in every framework of .NET
  • Execution of slow processes can be slower, as they're run serially
    • Process 2 can't start until 1 is done. Process 3 can't start until 2 & 1 are done...
  • Execution of quick processes can be faster, as there is no threading overhead


  • Execution takes place in parallel way.
  • Parallel.ForEach uses multiple Threads.
  • Parallel.ForEach is defined in .Net 4.0 and above frameworks.
  • Execution of slow processes can be faster, as they can be run in parallel
    • Processes 1, 2, & 3 may run concurrently (see reused threads in example, below)
  • Execution of quick processes can be slower, because of additional threading overhead

The following example clearly demonstrates the difference between traditional foreach loop and

Parallel.ForEach() Example

using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
namespace ParallelForEachExample
    class Program
        static void Main()
            string[] colors = {
                                  "1. Red",
                                  "2. Green",
                                  "3. Blue",
                                  "4. Yellow",
                                  "5. White",
                                  "6. Black",
                                  "7. Violet",
                                  "8. Brown",
                                  "9. Orange",
                                  "10. Pink"
            Console.WriteLine("Traditional foreach loop\n");
            //start the stopwatch for "for" loop
            var sw = Stopwatch.StartNew();
            foreach (string color in colors)
                Console.WriteLine("{0}, Thread Id= {1}", color, Thread.CurrentThread.ManagedThreadId);
            Console.WriteLine("foreach loop execution time = {0} seconds\n", sw.Elapsed.TotalSeconds);
            Console.WriteLine("Using Parallel.ForEach");
            //start the stopwatch for "Parallel.ForEach"
             sw = Stopwatch.StartNew();
            Parallel.ForEach(colors, color =>
                Console.WriteLine("{0}, Thread Id= {1}", color, Thread.CurrentThread.ManagedThreadId);
            Console.WriteLine("Parallel.ForEach() execution time = {0} seconds", sw.Elapsed.TotalSeconds);


Traditional foreach loop
1. Red, Thread Id= 10
2. Green, Thread Id= 10
3. Blue, Thread Id= 10
4. Yellow, Thread Id= 10
5. White, Thread Id= 10
6. Black, Thread Id= 10
7. Violet, Thread Id= 10
8. Brown, Thread Id= 10
9. Orange, Thread Id= 10
10. Pink, Thread Id= 10
foreach loop execution time = 0.1054376 seconds

Using Parallel.ForEach example

1. Red, Thread Id= 10
3. Blue, Thread Id= 11
4. Yellow, Thread Id= 11
2. Green, Thread Id= 10
5. White, Thread Id= 12
7. Violet, Thread Id= 14
9. Orange, Thread Id= 13
6. Black, Thread Id= 11
8. Brown, Thread Id= 10
10. Pink, Thread Id= 12
Parallel.ForEach() execution time = 0.055976 seconds

oracle - what statements need to be committed?

In mechanical terms a COMMIT makes a transaction. That is, a transaction is all the activity (one or more DML statements) which occurs between two COMMIT statements (or ROLLBACK).

In Oracle a DDL statement is a transaction in its own right simply because an implicit COMMIT is issued before the statement is executed and again afterwards. TRUNCATE is a DDL command so it doesn't need an explicit commit because calling it executes an implicit commit.

From a system design perspective a transaction is a business unit of work. It might consist of a single DML statement or several of them. It doesn't matter: only full transactions require COMMIT. It literally does not make sense to issue a COMMIT unless or until we have completed a whole business unit of work.

This is a key concept. COMMITs don't just release locks. In Oracle they also release latches, such as the Interested Transaction List. This has an impact because of Oracle's read consistency model. Exceptions such as ORA-01555: SNAPSHOT TOO OLD or ORA-01002: FETCH OUT OF SEQUENCE occur because of inappropriate commits. Consequently, it is crucial for our transactions to hang onto locks for as long as they need them.

Run on server option not appearing in Eclipse

For me worked: Right click on project > Properties > Project Faces > change Configuration from "custom" to "Default configuration for Apache Tomcat v7.0" > OK and then Run on Server option has appeared.

How to make a variable accessible outside a function?

Your variable declarations and their scope are correct. The problem you are facing is that the first AJAX request may take a little bit time to finish. Therefore, the second URL will be filled with the value of sID before the its content has been set. You have to remember that AJAX request are normally asynchronous, i.e. the code execution goes on while the data is being fetched in the background.

You have to nest the requests:

$.getJSON(""+input+"?api_key=API_KEY_HERE"  , function(name){   obj = name;   // sID is only now available!   sID =;   console.log(sID); }); 

Clean up your code!

  • Put the second request into a function
  • and let it accept sID as a parameter, so you don't have to declare it globally anymore! (Global variables are almost always evil!)
  • Remove sID and obj variables - is sufficient unless you really need the other variables outside the function.

$.getJSON(""+input+"?api_key=API_KEY_HERE"  , function(name){   // We don't need sID or obj here - is sufficient   console.log(;    doSecondRequest(; });  /// TODO Choose a better name function doSecondRequest(sID) {   $.getJSON("" + sID + "/summary?api_key=API_KEY_HERE", function(stats){         console.log(stats);   }); } 

Hapy New Year :)

Preventing multiple clicks on button

After hours of searching i fixed it in this way:

    old_timestamp == null;

    $('#productivity_table').on('click', function(event) {

    // code executed at first load
    // not working if you press too many clicks, it waits 1 second
    if(old_timestamp == null || old_timestamp + 1000 < event.timeStamp)
         // write the code / slide / fade / whatever
         old_timestamp = event.timeStamp;

get selected value in datePicker and format it

var dateObject = $("#datePickerInput").datepicker('getDate');
$.datepicker.formatDate('dd MM, yy', dateObject);

PHP Swift mailer: Failed to authenticate on SMTP using 2 possible authenticators

I had the same issue, so I've disabled one setting on my WHM root login, which is as follows :

WHM > Home > Server Configuration > Tweak Settings > Restrict outgoing SMTP to root, exim, and mailman (FKA SMTP Tweak) [?]

How to Select Every Row Where Column Value is NOT Distinct

Just for fun, here's another way:

;with counts as (
    select CustomerName, EmailAddress,
      count(*) over (partition by EmailAddress) as num
    from Customers
select CustomerName, EmailAddress
from counts
where num > 1

Python RuntimeWarning: overflow encountered in long scalars

An easy way to overcome this problem is to use 64 bit type

list = numpy.array(list, dtype=numpy.float64)

Check that a input to UITextField is numeric only

@property (strong) NSNumberFormatter *numberFormatter;
@property (strong) NSString *oldStringValue;

- (void)awakeFromNib 
  [super awakeFromNib];
  self.numberFormatter = [[NSNumberFormatter alloc] init];
  self.oldStringValue = self.stringValue;
  [self setDelegate:self];

- (void)controlTextDidChange:(NSNotification *)obj
  NSNumber *number = [self.numberFormatter numberFromString:self.stringValue];
  if (number) {
    self.oldStringValue = self.stringValue;
  } else {
    self.stringValue = self.oldStringValue;

Get filename from input [type='file'] using jQuery


How to redirect to a route in laravel 5 by using href tag if I'm not using blade or any template?

In you app config file change the url to localhost/example/public

Then when you want to link to something

<a href="{{ url('page') }}">Some Text</a>

without blade

<a href="<?php echo url('page') ?>">Some Text</a>

ImportError: No module named pandas

As of Dec 2020, I had the same issue when installing python v 3.8.6 via pyenv. So, I started by:

  1. Installing pyenv via homebrew brew install pyenv
  2. Install xz compiling package via brew install xz
  3. pyenv install 3.8.6 pick the required version
  4. pyenv global 3.8.6 make this version as global
  5. python -m pip install -U pip to upgrade pip
  6. pip install virtualenv

After that, I initialized my new env, installed pandas via pip command, and everything worked again. The panda's version installed is 1.1.5 within my working project directory. I hope that might help!

Note: If you have installed python before xz, make sure to uninstall it first, otherwise the error might persist.

Where can I download IntelliJ IDEA Color Schemes?

I like ZenBurn theme, I think it is very mild and appealing for the eye. I had here my own theme's settings JAR file, but I stopped updating it. I still think that theme is very good so I updated this post to a suitable theme with similar colors which is already available on @Yarg's web site screenshot

Link towards the theme

Bootstrap 3 - How to load content in modal body via AJAX?

This is actually super simple with just a little bit of added javascript. The link's href is used as the ajax content source. Note that for Bootstrap 3.* we set data-remote="false" to disable the deprecated Bootstrap load function.


// Fill modal with content from link href
$("#myModal").on("", function(e) {
    var link = $(e.relatedTarget);

Html (based on the official example):

<!-- Link trigger modal -->
<a href="remoteContent.html" data-remote="false" data-toggle="modal" data-target="#myModal" class="btn btn-default">
    Launch Modal

<!-- Default bootstrap modal example -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>
      <div class="modal-body">
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>

Try it yourself:

'Invalid update: invalid number of rows in section 0

In my case issue was that numberOfRowsInSection was returning similar number of rows after calling tableView.deleteRows(...).

Since this was the required behaviour in my case, I ended up calling tableView.reloadData() instead of tableView.deleteRows(...) in cases where numberOfRowsInSection will remain same after deleting a row.

How to fix libeay32.dll was not found error

Download libeay32.dll and ssleay32.dll binary package for 32Bit and 64Bit from then put it into executable or System32 directory.

how to set font size based on container size?

I had a similar issue but I had to consider other issues that @apaul34208 example did not tackle. In my case;

  • I have a container that changed size depending on the viewport using media queries
  • Text inside is dynamically generated
  • I want to scale up as well as down

Not the most elegant of examples but it does the trick for me. Consider using throttling the window resize (

var TextFit = function(){_x000D_
 var container = $('.container');_x000D_
    var container_width = $(this).width(),_x000D_
      width_offset = parseInt($(this).data('width-offset')),_x000D_
        font_container = $(this).find('.font-container');_x000D_
     if ( width_offset > 0 ) {_x000D_
         container_width -= width_offset;_x000D_
      var font_container_width = $(this).width(),_x000D_
          font_size = parseFloat( $(this).css('font-size') );_x000D_
      var diff = Math.max(container_width, font_container_width) - Math.min(container_width, font_container_width);_x000D_
      var diff_percentage = Math.round( ( diff / Math.max(container_width, font_container_width) ) * 100 );_x000D_
      if (diff_percentage !== 0){_x000D_
          if ( container_width > font_container_width ) {_x000D_
            new_font_size = font_size + Math.round( ( font_size / 100 ) * diff_percentage );_x000D_
          } else if ( container_width < font_container_width ) {_x000D_
            new_font_size = font_size - Math.round( ( font_size / 100 ) * diff_percentage );_x000D_
      $(this).css('font-size', new_font_size + 'px');_x000D_
.container {_x000D_
 .font-container {_x000D_
<script src=""></script>_x000D_
<div class="container" data-width-offset="10">_x000D_
 <span class="font-container">£5000</span>_x000D_

Reading text files using read.table

From ?read.table: The number of data columns is determined by looking at the first five lines of input (or the whole file if it has less than five lines), or from the length of col.names if it is specified and is longer. This could conceivably be wrong if fill or blank.lines.skip are true, so specify col.names if necessary.

So, perhaps your data file isn't clean. Being more specific will help the data import:

d = read.table("foobar.txt", 
               col.names=c("id", "name"), 

will specify exact columns and fill=FALSE will force a two column data frame.

Google OAuth 2 authorization - Error: redirect_uri_mismatch

I had this problem using Meteor and Ngrok, while trying to login with Google. I put the Ngrok URL in the Google Developer Console as redirect URLs, and went to the Ngrok URL page. The thing was that I didn't use Meteor's ROOT_URL when executing the app, so any redirect would go to localhost:3000 insted of the Ngrok URL. Just fixed it by adding the Ngrok URL as ROOT_URL on Meteor's configuration or by exporting it before executing the app on the terminal like: export ROOT_URL=https://my_ngrok_url

Cannot run emulator in Android Studio

I got it fixed by running "C:\Program Files\Android\android-sdk\AVD Manager.exe" and repairing my broken device.

dll missing in JDBC

keep sqljdbc_auth.dll in your windows/system32 folder and it will work.Download sqljdbc driver from this link Unzip it and you will find sqljdbc_auth.dll.Now keep the sqljdbc_auth.dll inside system32 folder and run your program

No provider for TemplateRef! (NgIf ->TemplateRef)

You missed the * in front of NgIf (like we all have, dozens of times):

<div *ngIf="answer.accepted">&#10004;</div>

Without the *, Angular sees that the ngIf directive is being applied to the div element, but since there is no * or <template> tag, it is unable to locate a template, hence the error.

If you get this error with Angular v5:

Error: StaticInjectorError[TemplateRef]:
    NullInjectorError: No provider for TemplateRef!

You may have <template>...</template> in one or more of your component templates. Change/update the tag to <ng-template>...</ng-template>.

Github: Can I see the number of downloads for a repo?

I have written a small web application in javascript for showing count of the number of downloads of all the assets in the available releases of any project on Github. You can try out the application over here:

Python Threading String Arguments

You're trying to create a tuple, but you're just parenthesizing a string :)

Add an extra ',':

dRecieved = connFile.readline()
processThread = threading.Thread(target=processLine, args=(dRecieved,))  # <- note extra ','

Or use brackets to make a list:

dRecieved = connFile.readline()
processThread = threading.Thread(target=processLine, args=[dRecieved])  # <- 1 element list

If you notice, from the stack trace: self.__target(*self.__args, **self.__kwargs)

The *self.__args turns your string into a list of characters, passing them to the processLine function. If you pass it a one element list, it will pass that element as the first argument - in your case, the string.

What ports does RabbitMQ use?

What ports is RabbitMQ using?

Default: 5672, the manual has the answer. It's defined in the RABBITMQ_NODE_PORT variable.

The number might be differently if changed by someone in the rabbitmq configuration file:

vi /etc/rabbitmq/rabbitmq-env.conf

Ask the computer to tell you:

sudo nmap -p 1-65535 localhost

Starting Nmap 5.51 ( ) at 2014-09-19 13:50 EDT
Nmap scan report for localhost (
Host is up (0.00041s latency).
443/tcp   open          https
5672/tcp  open          amqp
15672/tcp open  unknown
35102/tcp open  unknown
59440/tcp open  unknown

Oh look, 5672, and 15672

Use netstat:

netstat -lntu
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address               Foreign Address             State
tcp        0      0     *                   LISTEN
tcp        0      0     *                   LISTEN
tcp        0      0 :::5672                     :::*                        LISTEN

Oh look 5672.

use lsof:

eric@dev ~$ sudo lsof -i | grep beam
beam.smp  21216    rabbitmq   17u  IPv4 33148214      0t0  TCP *:55672 (LISTEN)
beam.smp  21216    rabbitmq   18u  IPv4 33148219      0t0  TCP *:15672 (LISTEN)

use nmap from a different machine, find out if 5672 is open:

sudo nmap -p 5672
Starting Nmap 5.51 ( ) at 2014-09-19 13:19 EDT
Nmap scan report for
Host is up (0.00011s latency).
5672/tcp open  amqp
MAC Address: 0A:40:0E:8C:75:6C (Unknown)    
Nmap done: 1 IP address (1 host up) scanned in 0.13 seconds

Try to connect to a port manually with telnet, 5671 is CLOSED:

telnet localhost 5671
telnet: connect to address Connection refused

Try to connect to a port manually with telnet, 5672 is OPEN:

telnet localhost 5672
Connected to localhost.
Escape character is '^]'.

Check your firewall:

sudo cat /etc/sysconfig/iptables  

It should tell you what ports are made open:

-A INPUT -p tcp -m tcp --dport 5672 -j ACCEPT

Reapply your firewall:

sudo service iptables restart
iptables: Setting chains to policy ACCEPT: filter          [  OK  ]
iptables: Flushing firewall rules:                         [  OK  ]
iptables: Unloading modules:                               [  OK  ]
iptables: Applying firewall rules:                         [  OK  ]

Usage of MySQL's "IF EXISTS"

The accepted answer works well and one can also just use the

If Exists (...) Then ... End If; 

syntax in Mysql procedures (if acceptable for circumstance) and it will behave as desired/expected. Here's a link to a more thorough source/description:

One problem with the solution by @SnowyR is that it does not really behave like "If Exists" in that the (Select 1 = 1 ...) subquery could return more than one row in some circumstances and so it gives an error. I don't have permissions to respond to that answer directly so I thought I'd mention it here in case it saves someone else the trouble I experienced and so others might know that it is not an equivalent solution to MSSQLServer "if exists"!

Directly assigning values to C Pointers

In the first example, ptr has not been initialized, so it points to an unspecified memory location. When you assign something to this unspecified location, your program blows up.

In the second example, the address is set when you say ptr = &q, so you're OK.

How to change the color of text in javafx TextField?

Setting the -fx-text-fill works for me.

See below:

if (passed) {
    resultInfo.setStyle("-fx-text-fill: green; -fx-font-size: 16px;");
} else {
    resultInfo.setStyle("-fx-text-fill: red; -fx-font-size: 16px;");

Unable to find the requested .Net Framework Data Provider in Visual Studio 2010 Professional

I like the other suggestions but I would rather not update the machine.config for a single application. I suggest that you just add it to the web.config / app.config. Here is what I needed to use the MySql Connector/NET that I "bin" deployed.

    <DbProviderFactories >
        <add name="MySQL Data Provider" invariant="MySql.Data.MySqlClient" description=".Net Framework Data Provider for MySQL" type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data, Version=, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />

Simple pthread! C++

This worked for me:

#include <iostream>
#include <pthread.h>
using namespace std;

void* print_message(void*) {

    cout << "Threading\n";

int main() {

    pthread_t t1;

    pthread_create(&t1, NULL, &print_message, NULL);
    cout << "Hello";

    // Optional.
    void* result;
    // :~

    return 0;

Can an int be null in Java?

Any Primitive data type like int,boolean, or float etc can't store the null(lateral),since java has provided Wrapper class for storing the same like int to Integer,boolean to Boolean.

Eg: Integer i=null;

How can I multiply all items in a list together with Python?

I would use the to perform the task. See below.

import numpy as np
mylist = [1, 2, 3, 4, 5, 6] 
result =  

Compiling LaTex bib source

You need to compile the bibtex file.

Suppose you have article.tex and article.bib. You need to run:

  • latex article.tex (this will generate a document with question marks in place of unknown references)
  • bibtex article (this will parse all the .bib files that were included in the article and generate metainformation regarding references)
  • latex article.tex (this will generate document with all the references in the correct places)
  • latex article.tex (just in case if adding references broke page numbering somewhere)

Could not load file or assembly "Oracle.DataAccess" or one of its dependencies

Also you can download and execute the install.bat file in '' from 64-bit Oracle Data Access Components (ODAC) Downloads. This resolved my problem.

How to create nonexistent subdirectories recursively using Bash?

mkdir -p newDir/subdir{1..8}
ls newDir/
subdir1 subdir2 subdir3 subdir4 subdir5 subdir6 subdir7 subdir8

jQuery $(this) keyword

$(this) returns a cached version of the element, hence improving performance since jQuery doesn't have to do a complete lookup in the DOM of the element again.

Git Pull is Not Possible, Unmerged Files

Assuming you want to throw away any changes you have, first check the output of git status. For any file that says "unmerged" next to it, run git add <unmerged file>. Then follow up with git reset --hard. That will git rid of any local changes except for untracked files.

Save file/open file dialog box, using Swing & Netbeans GUI editor

I have created a sample UI which shows the save and open file dialog. Click on save button to open save dialog and click on open button to open file dialog.

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class FileChooserEx {
    public static void main(String[] args) {
        Runnable r = new Runnable() {

            public void run() {
                new FileChooserEx().createUI();


    private void createUI() {
        JFrame frame = new JFrame();
        frame.setLayout(new BorderLayout());

        JButton saveBtn = new JButton("Save");
        JButton openBtn = new JButton("Open");

        saveBtn.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent arg0) {
                JFileChooser saveFile = new JFileChooser();

        openBtn.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent arg0) {
                JFileChooser openFile = new JFileChooser();

        frame.add(new JLabel("File Chooser"), BorderLayout.NORTH);
        frame.add(saveBtn, BorderLayout.CENTER);
        frame.add(openBtn, BorderLayout.SOUTH);
        frame.setTitle("File Chooser");

Lua string to int

Since lua 5.3 there is a new math.tointeger function for string to integer. Just for integer, no float.

For example:

print(math.tointeger("10.1")) -- nil
print(math.tointeger("10")) -- 10

If you want to convert integer and float, the tonumber function is more appropriate.

require(vendor/autoload.php): failed to open stream

Proper autoload.php configuration:

A) Quick answer:

Your autoload.php path is wrong. ie. C:\Windows\SysWOW64\vendor\autoload.php To date: you need to change it to: C:\Users\<Windows User Name>\vendor\autoload.php

B) Steps with example: We will take facebook/php-graph-sdk as an example; change to Package Name as needed.

  1. Install composer.exe
  2. Open CMD Prompt. + R + type CMD
  3. Run This command: composer require facebook/graph-sdk
  4. Include path in your PHP page: require_once 'C:\Users\<Windows User Name>\vendor\autoload.php';
  5. Define configuration Secrets and Access Token for your package...etc.
  6. Happy codinig.

C) Further details:

Installing composer on windows will set this default path for your pacakges; you can find them there and include the autoloader path:

C:\Users\<Windows User Name>\vendor

For the same question you asked; the answer was this path for WAMP Server 64 BIT for Windows.

Then simply in your PHP Application change this:

require_once __DIR__ . '/vendor/autoload.php'; 


require_once 'C:\Users\<Windows User Name>\vendor\autoload.php'; 

Find your windows username under C:\Users\

Before all this, as pointed before in B) , you need to run this command:

composer require <package name>

for facebook php SDK for example:

composer require facebook/graph-sdk

Thank you for asking this question; appreciated as it helped me fix similar issue and ended writing this simple tutorial.

React / JSX Dynamic Component Name

Suspose we wish to access various views with dynamic component loading.The following code gives a working example of how to accomplish this by using a string parsed from the search string of a url.

Lets assume we want to access a page 'snozberrys' with two unique views using these url paths:




we define our view's controller like this:

import React, { Component } from 'react';
import ReactDOM from 'react-dom'
import {
  BrowserRouter as Router,
} from 'react-router-dom'
import AComponent from './AComponent.js';
import CoBComponent sole from './BComponent.js';

const views = {
  aComponent: <AComponent />,
  console: <BComponent />

const View = (props) => {
  let name =;
  let view = views[name];
  if(view == null) throw "View '" + name + "' is undefined";
  return view;

class ViewManager extends Component {
  render() {
    return (
          <Route path='/' component={View}/>

export default ViewManager

ReactDOM.render(<ViewManager />, document.getElementById('root'));

What is the purpose of backbone.js?

It also adds routing using controllers and views with KVO. You'll be able to develop "AJAXy" applications with it.

See it as a lightweight Sproutcore or Cappuccino framework.

Is there a common Java utility to break a list into batches?

A one-liner in Java 8 would be:

import static java.util.function.Function.identity;
import static*;

private static <T> Collection<List<T>> partition(List<T> xs, int size) {
    return IntStream.range(0, xs.size())
            .collect(collectingAndThen(toMap(identity(), xs::get), Map::entrySet))
            .collect(groupingBy(x -> x.getKey() / size, mapping(Map.Entry::getValue, toList())))


How to convert integer timestamp to Python datetime

datetime.datetime.fromtimestamp() is correct, except you are probably having timestamp in miliseconds (like in JavaScript), but fromtimestamp() expects Unix timestamp, in seconds.

Do it like that:

>>> import datetime
>>> your_timestamp = 1331856000000
>>> date = datetime.datetime.fromtimestamp(your_timestamp / 1e3)

and the result is:

>>> date
datetime.datetime(2012, 3, 16, 1, 0)

Does it answer your question?

EDIT: J.F. Sebastian correctly suggested to use true division by 1e3 (float 1000). The difference is significant, if you would like to get precise results, thus I changed my answer. The difference results from the default behaviour of Python 2.x, which always returns int when dividing (using / operator) int by int (this is called floor division). By replacing the divisor 1000 (being an int) with the 1e3 divisor (being representation of 1000 as float) or with float(1000) (or 1000. etc.), the division becomes true division. Python 2.x returns float when dividing int by float, float by int, float by float etc. And when there is some fractional part in the timestamp passed to fromtimestamp() method, this method's result also contains information about that fractional part (as the number of microseconds).

Cannot install NodeJs: /usr/bin/env: node: No such file or directory

The issue is not with the version of node. Instead, it is the way NodeJS is installed by default in Ubuntu. When running a Node application in Ubuntu you have to run nodejs somethign.js instead of node something.js

So the application name called in the terminal is nodejs and not node. This is why there is a need for a symlink to simply forward all the commands received as node to nodejs.

sudo ln -s /usr/bin/nodejs /usr/bin/node

How to redirect output of an entire shell script within the script itself?

Typically we would place one of these at or near the top of the script. Scripts that parse their command lines would do the redirection after parsing.

Send stdout to a file

exec > file

with stderr

exec > file                                                                      
exec 2>&1

append both stdout and stderr to file

exec >> file
exec 2>&1

As Jonathan Leffler mentioned in his comment:

exec has two separate jobs. The first one is to replace the currently executing shell (script) with a new program. The other is changing the I/O redirections in the current shell. This is distinguished by having no argument to exec.

How do I get a substring of a string in Python?

Well, I got a situation where I needed to translate a PHP script to Python, and it had many usages of substr(string, beginning, LENGTH).
If I chose Python's string[beginning:end] I'd have to calculate a lot of end indexes, so the easier way was to use string[beginning:][:length], it saved me a lot of trouble.

Finding the handle to a WPF window

Just use your window with the WindowsInteropHelper class:

// ... Window myWindow = get your Window instance...
IntPtr windowHandle = new WindowInteropHelper(myWindow).Handle;

Right now, you're asking for the Application's main window, of which there will always be one. You can use this same technique on any Window, however, provided it is a System.Windows.Window derived Window class.

Delete all duplicate rows Excel vba

The duplicate values in any column can be deleted with a simple for loop.

Sub remove()
Dim a As Long
For a = Cells(Rows.Count, 1).End(xlUp).Row To 1 Step -1
If WorksheetFunction.CountIf(Range("A1:A" & a), Cells(a, 1)) > 1 Then Rows(a).Delete
End Sub

source of historical stock data

I'd crawl (for the quotes) - or

Both these will return html pages for most exchanges around the world, including historical. Then, it's just a matter of parsing the HTML to extract what you need.

I've done this in the past, with great success. Alternatively, if you don't mind using Perl - there are several modules on CPAN that have done this work for you - i.e. extracting quotes from Google/Yahoo.

For more, see Quote History

Accessing @attribute from SimpleXML

You can get the attributes of an XML element by calling the attributes() function on an XML node. You can then var_dump the return value of the function.

More info at

Example code from that page:

$xml = simplexml_load_string($string);
foreach($xml->foo[0]->attributes() as $a => $b) {
    echo $a,'="',$b,"\"\n";

Where in an Eclipse workspace is the list of projects stored?

You can also have several workspaces - so you can connect to one and have set "A" of projects - and then connect to a different set when ever you like.

HTML5 form required attribute. Set custom validation message?

The solution for preventing Google Chrome error messages on input each symbol:

<p>Click the 'Submit' button with empty input field and you will see the custom error message. Then put "-" sign in the same input field.</p>_x000D_
<form method="post" action="#">_x000D_
  <label for="text_number_1">Here you will see browser's error validation message on input:</label><br>_x000D_
  <input id="test_number_1" type="number" min="0" required="true"_x000D_
         oninvalid="this.setCustomValidity('This is my custom message.')"/>_x000D_
  <input type="submit"/>_x000D_
<form method="post" action="#">_x000D_
  <label for="text_number_1">Here you will see no error messages on input:</label><br>_x000D_
  <input id="test_number_2" type="number" min="0" required="true"_x000D_
         oninput="(function(e){e.setCustomValidity(''); return !e.validity.valid && e.setCustomValidity(' ')})(this)"_x000D_
         oninvalid="this.setCustomValidity('This is my custom message.')"/>_x000D_
  <input type="submit"/>_x000D_

How to remove all the occurrences of a char in c++ string

string RemoveChar(string str, char c) 
   string result;
   for (size_t i = 0; i < str.size(); i++) 
          char currentChar = str[i];
          if (currentChar != c)
              result += currentChar;
       return result;

This is how I did it.

Or you could do as Antoine mentioned:

See this question which answers the same problem. In your case:

#include <algorithm>
str.erase(std::remove(str.begin(), str.end(), 'a'), str.end());

java build path problems

From the Package Explorer in Eclipse, you can right click the project, choose Build Path, Configure Build Path to get the build path dialog. From there you can remove the JRE reference for the 1.5 JRE and 'Add Library' to add a reference to your installed JRE.

What does "restore purchases" in In-App purchases mean?

You will get rejection message from apple just because the product you have registered for inApp purchase might come under category Non-renewing subscriptions and consumable products. These type of products will not automatically renewable. you need to have explicit restore button in your application.

for other type of products it will automatically restore it.

Please read following text which will clear your concept about this :

Once a transaction has been processed and removed from the queue, your application normally never sees it again. However, if your application supports product types that must be restorable, you must include an interface that allows users to restore these purchases. This interface allows a user to add the product to other devices or, if the original device was wiped, to restore the transaction on the original device.

Store Kit provides built-in functionality to restore transactions for non-consumable products, auto-renewable subscriptions and free subscriptions. To restore transactions, your application calls the payment queue’s restoreCompletedTransactions method. The payment queue sends a request to the App Store to restore the transactions. In return, the App Store generates a new restore transaction for each transaction that was previously completed. The restore transaction object’s originalTransaction property holds a copy of the original transaction. Your application processes a restore transaction by retrieving the original transaction and using it to unlock the purchased content. After Store Kit restores all the previous transactions, it notifies the payment queue observers by calling their paymentQueueRestoreCompletedTransactionsFinished: method.

If the user attempts to purchase a restorable product (instead of using the restore interface you implemented), the application receives a regular transaction for that item, not a restore transaction. However, the user is not charged again for that product. Your application should treat these transactions identically to those of the original transaction. Non-renewing subscriptions and consumable products are not automatically restored by Store Kit. Non-renewing subscriptions must be restorable, however. To restore these products, you must record transactions on your own server when they are purchased and provide your own mechanism to restore those transactions to the user’s devices

How to cancel/abort jQuery AJAX request?

Create a function to call your API. Within this function we define request callApiRequest = $.get(... - even though this is a definition of a variable, the request is called immediately, but now we have the request defined as a variable. Before the request is called, we check if our variable is defined typeof(callApiRequest) != 'undefined' and also if it is pending suggestCategoryRequest.state() == 'pending' - if both are true, we .abort() the request which will prevent the success callback from running.

// We need to wrap the call in a function
callApi = function () {

    //check if request is defined, and status pending
    if (typeof(callApiRequest) != 'undefined'
        && suggestCategoryRequest.state() == 'pending') {

        //abort request


    //define and make request
    callApiRequest = $.get("", function (data) {

        data = JSON.parse(data); //optional (for JSON data format)
        //success callback


Your server/API might not support aborting the request (what if API executed some code already?), but the javascript callback will not fire. This is useful, when for example you are providing input suggestions to a user, such as hashtags input.

You can further extend this function by adding definition of error callback - what should happen if request was aborted.

Common use-case for this snippet would be a text input that fires on keypress event. You can use a timeout, to prevent sending (some of) requests that you will have to cancel .abort().

How to set JAVA_HOME in Mac permanently?

First, figure out where your java home is by running the command /usr/libexec/java_home -v <version> replacing with whatever version of OpenJDK your running.

Next use vim ~/.bash_profile to edit your bash profile. Add export JAVA_HOME="<java path>" replacing with the path to your java home found in the last step.

Finally, run the command source ~/.bash_profile

This should permanently set your JAVA_HOME environment variable.

To make sure it worked run echo $JAVA_HOME and make sure it returns the path you set

HTML input field hint

With a bit of JavaScript:

  value="Enter username..." 
  onfocus="if (this.value === 'Enter username...') this.value=''" ... />

HTML5 has a nice attribute for this, called placeholder:

<input placeholder="Enter username.." ... />

but this attribute is not supported in old browsers.

Write bytes to file

This example reads 6 bytes into a byte array and writes it to another byte array. It does an XOR operation with the bytes so that the result written to the file is the same as the original starting values. The file is always 6 bytes in size, since it writes at position 0.

using System;
using System.IO;

namespace ConsoleApplication1
    class Program
        static void Main()
        byte[] b1 = { 1, 2, 4, 8, 16, 32 };
        byte[] b2 = new byte[6];
        byte[] b3 = new byte[6];
        byte[] b4 = new byte[6];

        FileStream f1;
        f1 = new FileStream("test.txt", FileMode.Create, FileAccess.Write);

        // write the byte array into a new file
        f1.Write(b1, 0, 6);

        // read the byte array
        f1 = new FileStream("test.txt", FileMode.Open, FileAccess.Read);

        f1.Read(b2, 0, 6);

        // make changes to the byte array
        for (int i = 1; i < b2.Length; i++)
            b2[i] = (byte)(b2[i] ^ (byte)10); //xor 10

        f1 = new FileStream("test.txt", FileMode.Open, FileAccess.Write);
        // write the new byte array into the file
        f1.Write(b2, 0, 6);

        f1 = new FileStream("test.txt", FileMode.Open, FileAccess.Read);

        // read the byte array
        f1.Read(b3, 0, 6);

        // make changes to the byte array
        for (int i = 1; i < b3.Length; i++)
            b4[i] = (byte)(b3[i] ^ (byte)10); //xor 10

        f1 = new FileStream("test.txt", FileMode.Open, FileAccess.Write);

        // b4 will have the same values as b1
        f1.Write(b4, 0, 6);

gcc: undefined reference to

Are you mixing C and C++? One issue that can occur is that the declarations in the .h file for a .c file need to be surrounded by:

#if defined(__cplusplus)
  extern "C" {                 // Make sure we have C-declarations in C++ programs


#if defined(__cplusplus)

Note: if unable / unwilling to modify the .h file(s) in question, you can surround their inclusion with extern "C":

extern "C" {
#include <abc.h>
} //extern

What exactly does Perl's "bless" do?

bless associates a reference with a package.

It doesn't matter what the reference is to, it can be to a hash (most common case), to an array (not so common), to a scalar (usually this indicates an inside-out object), to a regular expression, subroutine or TYPEGLOB (see the book Object Oriented Perl: A Comprehensive Guide to Concepts and Programming Techniques by Damian Conway for useful examples) or even a reference to a file or directory handle (least common case).

The effect bless-ing has is that it allows you to apply special syntax to the blessed reference.

For example, if a blessed reference is stored in $obj (associated by bless with package "Class"), then $obj->foo(@args) will call a subroutine foo and pass as first argument the reference $obj followed by the rest of the arguments (@args). The subroutine should be defined in package "Class". If there is no subroutine foo in package "Class", a list of other packages (taken form the array @ISA in the package "Class") will be searched and the first subroutine foo found will be called.

How to open a new form from another form

You need to control the opening of sub forms from a main form.

In my case I'm opening a Login window first before I launch my form1. I control everything from Program.cs. Set up a validation flag in Program.cs. Open Login window from Program.cs. Control then goes to login window. Then if the validation is good, set the validation flag to true from the login window. Now you can safely close the login window. Control returns to Program.cs. If the validation flag is true, open form1. If the validation flag is false, your application will close.

In Program.cs:

   static class Program
        /// <summary>
        /// The main entry point for the application.
        /// </summary>

        //Validation flag
        public static bool ValidLogin = false;

        static void Main()

            Application.Run(new Login());

            if (ValidLogin)
                Application.Run(new Form1());


In Login.cs:

       private void btnOK_Click(object sender, EventArgs e)
            if (txtUsername.Text == "x" && txtPassword.Text == "x")
                Program.ValidLogin = true;
                MessageBox.Show("Username or Password are incorrect.");

        private void btnExit_Click(object sender, EventArgs e)

Java: Date from unix timestamp


Java 8 introduced a new API for working with dates and times: the java.time package.

With java.time you can parse your count of whole seconds since the epoch reference of first moment of 1970 in UTC, 1970-01-01T00:00Z. The result is an Instant.

Instant instant = Instant.ofEpochSecond( timeStamp );

If you need a java.util.Date to interoperate with old code not yet updated for java.time, convert. Call new conversion methods added to the old classes.

Date date = Date.from( instant );

How to Get XML Node from XDocument


<?xml version="1.0" encoding="utf-8"?>

Select a single node:

XDocument XMLDoc = XDocument.Load("test.xml");
string id = "123"; // id to be selected

XElement Contact = (from xml2 in XMLDoc.Descendants("Node")
                    where xml2.Element("ID").Value == id
                    select xml2).FirstOrDefault();


Delete a single node:

XDocument XMLDoc = XDocument.Load("test.xml");
string id = "123";

var Contact = (from xml2 in XMLDoc.Descendants("Node")
               where xml2.Element("ID").Value == id
               select xml2).FirstOrDefault();


Add new node:

XDocument XMLDoc = XDocument.Load("test.xml");

XElement newNode = new XElement("Node",
    new XElement("ID", "500"),
    new XElement("Name", "Whatever")


Difference between map, applymap and apply methods in Pandas

@jeremiahbuddha mentioned that apply works on row/columns, while applymap works element-wise. But it seems you can still use apply for element-wise computation....

               b         d         e
Utah         NaN  1.435159       NaN
Ohio    1.098164  0.510594  0.729748
Texas        NaN  0.456436  0.697337
Oregon  0.359079       NaN       NaN

               b         d         e
Utah         NaN  1.435159       NaN
Ohio    1.098164  0.510594  0.729748
Texas        NaN  0.456436  0.697337
Oregon  0.359079       NaN       NaN

How to use Tomcat 8.5.x and TomEE 7.x with Eclipse?

I had similar issues with Eclipse Kepler v3.8 I had tomcat v8.5.37 installed. I couldn't see Apache v8.5 as an option. By skimming through StackOverflow I found Apache v9.0 is available on Eclipse Neon. Cool thing is you don't have to change your eclipse version. In your current Eclipse. Download WTP(Web Tools Package) by following the steps:

Step 1: Help >>> Install New Software. Copy this link in the Work with:

Step 2: Select JST Server Adapters and JST Server Adapters Extensions from the first package you see. Install those.

Step 3: Windows >>> Preferences >>> Server >>> Runtime Environments >>> Add..

You'll see Apache v9.0 there! It works!

Can I pass variable to select statement as column name in SQL Server

You can't use variable names to bind columns or other system objects, you need dynamic sql

DECLARE @value varchar(10)  
SET @value = 'intStep'  
DECLARE @sqlText nvarchar(1000); 

SET @sqlText = N'SELECT ' + @value + ' FROM dbo.tblBatchDetail'
Exec (@sqlText)

Convert Mongoose docs to json

It worked for me:

Products.find({}).then(a => console.log( => p.toJSON())))

also if you want use getters, you should add its option also (on defining schema):

new mongoose.Schema({...}, {toJSON: {getters: true}})

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder"

You need to add following jar file in your classpath: slf4j-simple-1.6.2.jar. If you don't have it, please download it. Please refer to

How to differentiate single click event and double click event?

I'm afraid that the behaviour is browser dependent:

It is inadvisable to bind handlers to both the click and dblclick events for the same element. The sequence of events triggered varies from browser to browser, with some receiving two click events before the dblclick and others only one. Double-click sensitivity (maximum time between clicks that is detected as a double click) can vary by operating system and browser, and is often user-configurable.

Running your code in Firefox, the alert() in the click() handler prevents you from clicking a second time. If you remove such alert, you get both events.

How can I show line numbers in Eclipse?

this will be the appropriate solution for asked question:

String lineNumbers = AbstractDecoratedTextEditorPreferenceConstants.EDITOR_LINE_NUMBER_RULER; EditorsUI.getPreferenceStore().setValue(lineNumbers, true);

Remove white space above and below large text in an inline-block element

I've been annoyed by this problem often. Vertical-align would only work on bottom and center, but never top! :-(

It seems I may have stumbled on a solution that works for both table elements and free paragraph elements. I hope we are at least talking similar problem here.


p {
    font-family: "Times New Roman", Times, serif;
    font-size: 15px;
    background: #FFFFFF;
    margin: 0
    margin-top: 3px;
    margin-bottom: 10px;

For me, the margin settings sorted it out no matter where I put my "p>.../p>" code.

Hope this helps...

Modify SVG fill color when being served as Background-Image

for monochrome background you could use a svg with a mask, where the background color should be displayed

<svg xmlns="" viewBox="0 0 20 20" preserveAspectRatio="xMidYMid meet" focusable="false" style="pointer-events: none; display: block; width: 100%; height: 100%;" >
        <mask id="Mask">
            <rect width="100%" height="100%" fill="#fff" />
            <polyline stroke-width="2.5" stroke="black" stroke-linecap="square" fill="none" transform="translate(10.373882, 8.762969) rotate(-315.000000) translate(-10.373882, -8.762969) " points="7.99893906 13.9878427 12.7488243 13.9878427 12.7488243 3.53809523"></polyline>
    <rect x="0" y="0" width="20" height="20" fill="white" mask="url(#Mask)" />

and than use this css

background-repeat: no-repeat;
background-position: center center;
background-size: contain;
background-image: url(your/path/to.svg);
background-color: var(--color);

How to fix IndexError: invalid index to scalar variable

In the for, you have an iteration, then for each element of that loop which probably is a scalar, has no index. When each element is an empty array, single variable, or scalar and not a list or array you cannot use indices.

How can I manually generate a .pyc file from a .py file

In Python2 you could use:

python -m compileall <pythonic-project-name>

which compiles all .py files to .pyc files in a project which contains packages as well as modules.

In Python3 you could use:

python3 -m compileall <pythonic-project-name>

which compiles all .py files to __pycache__ folders in a project which contains packages as well as modules.

Or with browning from this post:

You can enforce the same layout of .pyc files in the folders as in Python2 by using:

python3 -m compileall -b <pythonic-project-name>

The option -b triggers the output of .pyc files to their legacy-locations (i.e. the same as in Python2).

error: invalid type argument of ‘unary *’ (have ‘int’)

Since c is holding the address of an integer pointer, its type should be int**:

int **c;
c = &a;

The entire program becomes:

#include <stdio.h>                                                              
int main(){
    int b=10;
    int *a;
    int **c;
    printf("%d",(**c));   //successfully prints 10
    return 0;

"No such file or directory" but it exists

Below command worked on 16.4 Ubuntu

This issue comes when your .sh file is corrupt or not formatted as per unix protocols.

dos2unix converts the .sh file to Unix format!

sudo apt-get install dos2unix -y
sudo chmod u+x 
sudo ./

What does it mean when the size of a VARCHAR2 in Oracle is declared as 1 byte?

To answer you first question:
Yes, it means that 1 byte allocates for 1 character. Look at this example

SQL> conn / as sysdba
SQL> create table test (id number(10), v_char varchar2(10));

Table created.

SQL> insert into test values(11111111111,'darshan');
insert into test values(11111111111,'darshan')
ERROR at line 1:
ORA-01438: value larger than specified precision allows for this column

SQL> insert into test values(11111,'darshandarsh');
insert into test values(11111,'darshandarsh')
ERROR at line 1:
ORA-12899: value too large for column "SYS"."TEST"."V_CHAR" (actual: 12,
maximum: 10)

SQL> insert into test values(111,'Darshan');

1 row created.


And to answer your next one: The difference between varchar2 and varchar :

  1. VARCHAR can store up to 2000 bytes of characters while VARCHAR2 can store up to 4000 bytes of characters.
  2. If we declare datatype as VARCHAR then it will occupy space for NULL values, In case of VARCHAR2 datatype it will not occupy any space.

How to create temp table using Create statement in SQL Server?

A temporary table can have 3 kinds, the # is the most used. This is a temp table that only exists in the current session. An equivalent of this is @, a declared table variable. This has a little less "functions" (like indexes etc) and is also only used for the current session. The ## is one that is the same as the #, however, the scope is wider, so you can use it within the same session, within other stored procedures.

You can create a temp table in various ways:

declare @table table (id int)
create table #table (id int)
create table ##table (id int)
select * into #table from xyz

IOPub data rate exceeded in Jupyter notebook (when viewing image)

I ran into this using networkx and bokeh

This works for me in Windows 7 (taken from here):

  1. To create a file, with all the defaults commented out, you can use the following command line:

    $ jupyter notebook --generate-config

  2. Open the file and search for c.NotebookApp.iopub_data_rate_limit

  3. Comment out the line c.NotebookApp.iopub_data_rate_limit = 1000000 and change it to a higher default rate. l used c.NotebookApp.iopub_data_rate_limit = 10000000

This unforgiving default config is popping up in a lot of places. See git issues:

It looks like it might get resolved with the 5.1 release


Jupyter notebook is now on release 5.2.2. This problem should have been resolved. Upgrade using conda or pip.

unbound method f() must be called with fibo_ instance as first argument (got classobj instance instead)

Try this. For python 2.7.12 we need to define constructor or need to add self to each methods followed by defining an instance of an class called object.

import cv2

class calculator:

#   def __init__(self):

def multiply(self, a, b):
    x= a*b

def subtract(self, a,b):
    x = a-b

def add(self, a,b):
    x = a+b

def div(self, a,b):
    x = a/b

 calc = calculator()

Difference between \w and \b regular expression meta characters

The metacharacter \b is an anchor like the caret and the dollar sign. It matches at a position that is called a "word boundary". This match is zero-length.

There are three different positions that qualify as word boundaries:

  • Before the first character in the string, if the first character is a word character.
  • After the last character in the string, if the last character is a word character.
  • Between two characters in the string, where one is a word character and the other is not a word character.

Simply put: \b allows you to perform a "whole words only" search using a regular expression in the form of \bword\b. A "word character" is a character that can be used to form words. All characters that are not "word characters" are "non-word characters".

In all flavors, the characters [a-zA-Z0-9_] are word characters. These are also matched by the short-hand character class \w. Flavors showing "ascii" for word boundaries in the flavor comparison recognize only these as word characters.

\w stands for "word character", usually [A-Za-z0-9_]. Notice the inclusion of the underscore and digits.

\B is the negated version of \b. \B matches at every position where \b does not. Effectively, \B matches at any position between two word characters as well as at any position between two non-word characters.

\W is short for [^\w], the negated version of \w.

Django DateField default options

This should do the trick:

models.DateTimeField(_("Date"), auto_now_add = True)

Angular HTML binding

[innerHtml] is great option in most cases, but it fails with really large strings or when you need hard-coded styling in html.

I would like to share other approach:

All you need to do, is to create a div in your html file and give it some id:

<div #dataContainer></div>

Then, in your Angular 2 component, create reference to this object (TypeScript here):

import { Component, ViewChild, ElementRef } from '@angular/core';

    templateUrl: "some html file"
export class MainPageComponent {

    @ViewChild('dataContainer') dataContainer: ElementRef;

    loadData(data) {
        this.dataContainer.nativeElement.innerHTML = data;

Then simply use loadData function to append some text to html element.

It's just a way that you would do it using native javascript, but in Angular environment. I don't recommend it, because makes code more messy, but sometimes there is no other option.

See also Angular 2 - innerHTML styling

What is the difference between and re.match?

The difference is, re.match() misleads anyone accustomed to Perl, grep, or sed regular expression matching, and does not. :-)

More soberly, As John D. Cook remarks, re.match() "behaves as if every pattern has ^ prepended." In other words, re.match('pattern') equals'^pattern'). So it anchors a pattern's left side. But it also doesn't anchor a pattern's right side: that still requires a terminating $.

Frankly given the above, I think re.match() should be deprecated. I would be interested to know reasons it should be retained.

What is the difference between MOV and LEA?

  • LEA means Load Effective Address
  • MOV means Load Value

In short, LEA loads a pointer to the item you're addressing whereas MOV loads the actual value at that address.

The purpose of LEA is to allow one to perform a non-trivial address calculation and store the result [for later usage]

LEA ax, [BP+SI+5] ; Compute address of value

MOV ax, [BP+SI+5] ; Load value at that address

Where there are just constants involved, MOV (through the assembler's constant calculations) can sometimes appear to overlap with the simplest cases of usage of LEA. Its useful if you have a multi-part calculation with multiple base addresses etc.

open_basedir restriction in effect. File(/) is not within the allowed path(s):

In addition to @yogihosting's answer, if you are using DirectAdmin, then follow these steps:

  1. Go to the DirectAdmin's login page. Usually, its port is 2222.
  2. Login as administrator. Its username is admin by default.
  3. From the "Access Level" on the right panel, make sure you are on "Admin Level". If not, change to it.
  4. From the "Extra Features" section, click on "Custom HTTPD Configurations".
  5. Choose the domain you want to change.
  6. Enter the configurations you want to change in the textarea at the top of the page. You should consider the existing configuration file and modify values based on it. For example, if you see that open_basedir is set inside a <Directory>, maybe you should surround your change in the related <Directory> tag:

    <Directory "/path/to/directory">
        php_admin_value open_basedir none
  7. After making necessary changes, click on the "Save" button.

  8. You should now see your changes saved to the configuration file if they were valid.

There is another way of editing the configuration file, however:

Caution: Be careful, and use the following steps at your own risk, as you may run into errors, or it may lead to downtime. The recommended way is the previous one, as it prevents you from modifying configuration file improperly and show you the error.

  1. Login to your server as root.
  2. Go to /usr/local/directadmin/data/users. From the listed users, go to one related to the domain you want to change.
  3. Here, there is an httpd.conf file. Make a backup from it:

    cp httpd.conf httpd.conf.back
  4. Now edit the configuration file with your editor of choice. For example, edit existing open_basedir to none. Do not try to remove things, or you may experience downtime. Save the file after editing.

  5. Restart the Apache web server using one of the following ways (use sudo if needed):

    httpd -k graceful
    apachectl -k graceful
    apache2 -k graceful
  6. If your encounter any errors, then replace the main configuration file with the backed-up file, and restart the web server.

Again, the first solution is the preferred one, and you should not try the second method at the first time. As it is noted in the caution, the advantage of the first way is that it prevents saving your bad-configured stuff.

Hope it helps!

ImportError: No module named 'pygame'

I had the same problem and discovered that Pygame doesn't work for Python3 at least on the Mac OS, but I also have Tython2 installed in my computer as you probably do too, so when I use Pygame, I switch the path so that it uses python2 instead of python3. I use Sublime Text as my text editor so I just go to Tools > Build Systems > New Build System and enter the following:

    "cmd": ["/usr/local/bin/python", "-u", "$file"],    

instead of

    "cmd": ["/usr/local/bin/python3", "-u", "$file"],   

in my case. And when I'm not using pygame, I simply change the path back so that I can use Python3.