Programs & Examples On #Sourcesafe 6.0

AngularJS - $ send data as json

i think the most proper way is to use the same piece of code angular use when doing a "get" request using you $httpParamSerializer will have to inject it to your controller so you can simply do the following without having to use Jquery at all , $,$httpParamSerializer({param:val}))


Best way to find os name and version in Unix/Linux platform

this command gives you a description of your operating system

cat /etc/os-release

How do I make a semi transparent background?

Use rgba():

.transparent {
  background-color: rgba(255,255,255,0.5);

This will give you 50% opacity while the content of the box will continue to have 100% opacity.

If you use opacity:0.5, the content will be faded as well as the background. Hence do not use it.

Is object empty?

here's a good way to do it

function isEmpty(obj) {
  if (Array.isArray(obj)) {
    return obj.length === 0;
  } else if (typeof obj === 'object') {
    for (var i in obj) {
      return false;
    return true;
  } else {
    return !obj;

TypeError: expected a character buffer object - while trying to save integer to textfile

Have you checked the docstring of write()? It says:

write(str) -> None. Write string str to file.

Note that due to buffering, flush() or close() may be needed before the file on disk reflects the data written.

So you need to convert y to str first.

Also note that the string will be written at the current position which will be at the end of the file, because you'll already have read the old value. Use to get to the beginning of the file.`

Edit: As for the IOError, this issue seems related. A cite from there:

For the modes where both read and writing (or appending) are allowed (those which include a "+" sign), the stream should be flushed (fflush) or repositioned (fseek, fsetpos, rewind) between either a reading operation followed by a writing operation or a writing operation followed by a reading operation.

So, I suggest you try and maybe the problem goes away.

How can I generate a unique ID in Python?

This will work very quickly but will not generate random values but monotonously increasing ones (for a given thread).

import threading

_uid = threading.local()
def genuid():
    if getattr(_uid, "uid", None) is None:
        _uid.tid = threading.current_thread().ident
        _uid.uid = 0
    _uid.uid += 1
    return (_uid.tid, _uid.uid)

It is thread safe and working with tuples may have benefit as opposed to strings (shorter if anything). If you do not need thread safety feel free remove the threading bits (in stead of threading.local, use object() and remove tid altogether).

Hope that helps.

remove item from stored array in angular 2

This can be achieved as follows:

this.itemArr = this.itemArr.filter( h => !== ID);

HTML CSS How to stop a table cell from expanding

It appears that your HTML syntax is incorrect for the table cell. Before you try the other idea below, confirm if this works or not... You can also try adding this to your table itself: table-layout:fixed.. .

<td style="overflow: hidden; width: 280px; text-align: left; valign: top; whitespace: nowrap;">


   <div class="MyClass"">

CSS Class:

   height: 280px; 
   width: 456px; 
   overflow: hidden;
   white-space: nowrap;

Difference between "while" loop and "do while" loop

The do while loop executes the content of the loop once before checking the condition of the while.

Whereas a while loop will check the condition first before executing the content.

In this case you are waiting for user input with scanf(), which will never execute in the while loop as wdlen is not initialized and may just contain a garbage value which may be greater than 2.

Javascript require() function giving ReferenceError: require is not defined

Yes, require is a Node.JS function and doesn't work in client side scripting without certain requirements. If you're getting this error while writing electronJS code, try the following:

In your BrowserWindow declaration, add the following webPreferences field: i.e, instead of plain mainWindow = new BrowserWindow(), write

mainWindow = new BrowserWindow({
        webPreferences: {
            nodeIntegration: true

How to call javascript function from button click event

If you don't need to initiate a post back when you press this button, then making the overhead of a server control isn't necesary.

<input id="addButton" type="button" value="Add" />

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

If you still need to be able to do a post back, you can conditionally stop the rest of the button actions with a little different code:

<asp:Button ID="buttonAdd" runat="server" Text="Add" />

<script type="text/javascript" language="javascript">
         $('#<%= buttonAdd.ClientID %>').click(function(e) 

             if(/*Some Condition Is Not Met*/) 
                return false;

Convert NaN to 0 in javascript

Write your own method, and use it everywhere you want a number value:

function getNum(val) {
   if (isNaN(val)) {
     return 0;
   return val;

Angular JS update input field after change

Create a directive and put a watch on it.

app.directive("myApp", function(){

    function:getTotal(){ your maths here

    scope.$watch('one', getTotals());
    scope.$watch('two', getTotals());


When to use a linked list over an array/array list?

Hmm, Arraylist can be used in cases like follows I guess:

  1. you are not sure how many elements will be present
  2. but you need to access all the elements randomly through indexing

For eg, you need to import and access all elements in a contact list (the size of which is unknown to you)

failed to resolve and

in support libraries you always need to add three numbers as version number

Suppose for 22 -> you need to write it as 22.0.0, not just 22

for 22.1 -> 22.1.0

So your dependencies should look like this

compile ''
compile ''
compile ''
compile ''

I Programmers language you need to pad extra zeros.

Hope this solves your problem

How to Find Item in Dictionary Collection?

Sometimes you still need to use FirstOrDefault if you have to do different tests. If the Key component of your dictionnary is nullable, you can do this:

thisTag = _tags.FirstOrDefault(t => t.Key.SubString(1,1) == 'a');
if(thisTag.Key != null) { ... }

Using FirstOrDefault, the returned KeyValuePair's key and value will both be null if no match is found.

How can I convert radians to degrees with Python?

-fix- because you want to change from radians to degrees, it is actually rad=deg * math.pi /180 and not deg*180/math.pi

import math
x=1                # in deg
x = x*math.pi/180  # convert to rad
y = math.cos(x)    # calculate in rad

print y

in 1 line it can be like this


Should I use alias or alias_method?

A year after asking the question comes a new article on the subject:

It seems that "so many men, so many minds." From the former article author encourages to use alias_method, while the latter suggests using alias.

However there's a common overview of these methods in both blogposts and answers above:

  • use alias when you want to limit aliasing to the scope where it's defined
  • use alias_method to allow inherited classes to access it

How can I get name of element with jQuery?

If anyone is also looking for how to get the name of the HTML tag, you can use "tagName": $(this)[0].tagName

json Uncaught SyntaxError: Unexpected token :

I had the same problem and the solution was to encapsulate the json inside this function


.... your json ...


How to use apply a custom drawable to RadioButton?

if you want to change the only icon of radio button then you can only add android:button="@drawable/ic_launcher" to your radio button and for making sensitive on click then you have to use the selector

 <?xml version="1.0" encoding="utf-8"?>
 <selector xmlns:android="">

<item android:drawable="@drawable/image_what_you_want_on_select_state" android:state_checked="true"/>
<item android:drawable="@drawable/image_what_you_want_on_un_select_state"    android:state_checked="false"/>


and set to your radio android:background="@drawable/name_of_selector"

How do I use 3DES encryption/decryption in Java?

Here's a very simply static encrypt/decrypt class biased on the Bouncy Castle no padding example by Jose Luis Montes de Oca. This one is using "DESede/ECB/PKCS7Padding" so I don't have to bother manually padding.

    package com.zenimax.encryption;

    import javax.crypto.BadPaddingException;
    import javax.crypto.Cipher;
    import javax.crypto.IllegalBlockSizeException;
    import javax.crypto.NoSuchPaddingException;
    import javax.crypto.SecretKey;
    import javax.crypto.spec.SecretKeySpec;
    import org.bouncycastle.jce.provider.BouncyCastleProvider;

     * @author Matthew H. Wagner
    public class TripleDesBouncyCastle {
        private static String TRIPLE_DES_TRANSFORMATION = "DESede/ECB/PKCS7Padding";
        private static String ALGORITHM = "DESede";
        private static String BOUNCY_CASTLE_PROVIDER = "BC";

        private static void init()
            Security.addProvider(new BouncyCastleProvider());

        public static byte[] encode(byte[] input, byte[] key)
                throws IllegalBlockSizeException, BadPaddingException,
                NoSuchAlgorithmException, NoSuchProviderException,
                NoSuchPaddingException, InvalidKeyException {
            SecretKey keySpec = new SecretKeySpec(key, ALGORITHM);
            Cipher encrypter = Cipher.getInstance(TRIPLE_DES_TRANSFORMATION,
            encrypter.init(Cipher.ENCRYPT_MODE, keySpec);
            return encrypter.doFinal(input);

        public static byte[] decode(byte[] input, byte[] key)
                throws IllegalBlockSizeException, BadPaddingException,
                NoSuchAlgorithmException, NoSuchProviderException,
                NoSuchPaddingException, InvalidKeyException {
            SecretKey keySpec = new SecretKeySpec(key, ALGORITHM);
            Cipher decrypter = Cipher.getInstance(TRIPLE_DES_TRANSFORMATION,
            decrypter.init(Cipher.DECRYPT_MODE, keySpec);
            return decrypter.doFinal(input);

Eclipse "cannot find the tag library descriptor" for custom tags (not JSTL!)

I had the same problem with MyEclipse and Eclipse 6.6.0. It red lined the uri value in every

<%@ taglib prefix="s" uri="/struts-tags"%>. I fixed it by going to 'Project/MyEclipse/Web/Tag Libraries' and setting the Default TLD Prefix for Struts 1.2 Tiles Tags to 's'. I also had to do the same under 'Project/MyEclipse/Web/Configure workspace settings.../Tag Libraries'.

Location of sqlite database on the device

You can find your database file :


getDatabaseName from class SQLiteOpenHelper

How to get an array of specific "key" in multidimensional array without looping

You can also use array_reduce() if you prefer a more functional approach

For instance:

$userNames = array_reduce($users, function ($carry, $user) {
    array_push($carry, $user['name']);
    return $carry;
}, []);

Or if you like to be fancy,

$userNames = [];
array_map(function ($user) use (&$userNames){
}, $users);

This and all the methods above do loop behind the scenes though ;)

Bootstrap Modal Backdrop Remaining

Add this:
to the ng-click function in controller to prevent the fade-in backdrop from staying.

How to pretty print XML from the command line?


Disclaimer: you should usually prefer installing a mature tool like xmllint to do a job like this. XML/HTML can be a horribly mutilated mess. However, there are valid situations where using existing tooling is preferable over manually installing new ones, and where it is also a safe bet the XML's source is valid (enough). I've written this script for one of those cases, but they are rare, so precede with caution.

I'd like to add a pure Bash solution, as it is not 'that' difficult to just do it by hand, and sometimes you won't want to install an extra tool to do the job.


declare -i currentIndent=0
declare -i nextIncrement=0
while read -r line ; do
  if [[ "$line" == "</"* ]]; then # line contains a closer, just decrease the indent
    dirtyTagName="${dirtyStartTag%% *}"
    # increase indent unless line contains closing tag or closes itself
    if [[ ! "$line" =~ "</$tagName>" && ! "$line" == *"/>"  ]]; then

  # print with indent
  printf "%*s%s" $(( $currentIndent * 2 )) # print spaces for the indent count
  echo $line
done <<< "$(cat - | sed 's/></>\n</g')" # separate >< with a newline

Paste it in a script file, and pipe in the xml. This assumes the xml is all on one line, and there are no extra spaces anywhere. One could easily add some extra \s* to the regexes to fix that.

How do you clear the console screen in C?

The proper way to do it is by using tput or terminfo functions to obtain terminal properties and then insert newlines according to the dimensions..

How to change background color in the Notepad++ text editor?

There seems to have been an update some time in the past 3 years which changes the location of where to place themes in order to get them working.

Previosuly, themes were located in the Notepad++ installation folder. Now they are located in AppData:


My answer is an update to @Amit-IO's answer about manually copying the themes.

  1. In Explorer, browse to: %AppData%\Notepad++.
  2. If a folder called themes does not exist, create it.
  3. Download your favourite theme from wherever (see Amit-IO's answer for a good list) and save it to %AppData%\Notepad++\themes.
  4. Restart Notepad++ and then use Settings -> Style Configurator. The new theme(s) will appear in the list.

Remove all the elements that occur in one list from another

Use the Python set type. That would be the most Pythonic. :)

Also, since it's native, it should be the most optimized method too.

See: (for older python)

# Using Python 2.7 set literal format.
# Otherwise, use: l1 = set([1,2,6,8])
l1 = {1,2,6,8}
l2 = {2,3,5,8}
l3 = l1 - l2

Show history of a file?

git log -p will generate the a patch (the diff) for every commit selected. For a single file, use git log --follow -p $file.

If you're looking for a particular change, use git bisect to find the change in log(n) views by splitting the number of commits in half until you find where what you're looking for changed.

Also consider looking back in history using git blame to follow changes to the line in question if you know what that is. This command shows the most recent revision to affect a certain line. You may have to go back a few versions to find the first change where something was introduced if somebody has tweaked it over time, but that could give you a good start.

Finally, gitk as a GUI does show me the patch immediately for any commit I click on.

Example enter image description here:

Including JavaScript class definition from another file in Node.js

Using ES6, you can have user.js:

export default class User {
  constructor() {

And then use it in server.js

const User = require('./user.js').default;
const user = new User();

Should I URL-encode POST data?

@DougW has clearly answered this question, but I still like to add some codes here to explain Doug's points. (And correct errors in the code above)

Solution 1: URL-encode the POST data with a content-type header :application/x-www-form-urlencoded .

Note: you do not need to urlencode $_POST[] fields one by one, http_build_query() function can do the urlencoding job nicely.

$fields = array(

$fields_string = http_build_query($fields);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);

Solution 2: Pass the array directly as the post data without URL-encoding, while the Content-Type header will be set to multipart/form-data.

$fields = array(

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_POST,1);
    curl_setopt($ch, CURLOPT_POSTFIELDS,$fields);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $response = curl_exec($ch);

Both code snippets work, but using different HTTP headers and bodies.

Reset textbox value in javascript

Try using this:


Custom method names in ASP.NET Web API

By default the route configuration follows RESTFul conventions meaning that it will accept only the Get, Post, Put and Delete action names (look at the route in global.asax => by default it doesn't allow you to specify any action name => it uses the HTTP verb to dispatch). So when you send a GET request to /api/users/authenticate you are basically calling the Get(int id) action and passing id=authenticate which obviously crashes because your Get action expects an integer.

If you want to have different action names than the standard ones you could modify your route definition in global.asax:

    name: "DefaultApi",
    routeTemplate: "api/{controller}/{action}/{id}",
    defaults: new { action = "get", id = RouteParameter.Optional }

Now you can navigate to /api/users/getauthenticate to authenticate the user.

How to increase application heap size in Eclipse?

Find the Run button present on the top of the Eclipse, then select Run Configuration -> Arguments, in VM arguments section just mention the heap size you want to extend as below:


How to install cron

Install cron on Linux/Unix:

apt-get install cron

Use cron on Linux/Unix

crontab -e

See the canonical answer about cron for more details:

iPhone X / 8 / 8 Plus CSS media queries

I noticed that the answers here are using: device-width, device-height, min-device-width, min-device-height, max-device-width, max-device-height.

Please refrain from using them since they are deprecated. see MDN for reference. Instead use the regular min-width, max-width and so on. For extra assurance, you can set the min and max to the same px amount. For example:

iPhone X

@media only screen 
    and (width : 375px) 
    and (height : 635px)
    and (orientation : portrait)  
    and (-webkit-device-pixel-ratio : 3) { }

You may also notice that I am using 635px for height. Try it yourself the window height is actually 635px. run iOS simulator for iPhone X and in Safari Web inspector do window.innerHeight. Here are a few useful links on this subject:

JAVA - using FOR, WHILE and DO WHILE loops to sum 1 through 100

Well, a for or while loop differs from a do while loop. A do while executes the statements atleast once, even if the condition turns out to be false.

The for loop you specified is absolutely correct.

Although i will do all the loops for you once again.

int sum = 0;
// for loop

for (int i = 1; i<= 100; i++){
    sum = sum + i;

// while loop

sum = 0;
int j = 1;

    sum = sum + j;


// do while loop

sum = 0;
j = 1;

    sum = sum + j;


In the last case condition j <= 100 is because, even if the condition of do while turns false, it will still execute once but that doesn't matter in this case as the condition turns true, so it continues to loop just like any other loop statement.

SQL statement to select all rows from previous day

In SQL Server do like this:

where cast(columnName as date) = cast(getdate() -1 as date)

You should cast both sides of the expression to date to avoid issues with time formatting.

If you need to control interval in more detail, then you should try something like:

declare @start datetime = cast(getdate() - 1 as date)
declare @end datetime = cast(getdate() - 1 as date)
set @end = dateadd(second, 86399, @end)

SQL Views - no variables?

Using functions as spencer7593 mentioned is a correct approach for dynamic data. For static data, a more performant approach which is consistent with SQL data design (versus the anti-pattern of writting massive procedural code in sprocs) is to create a separate table with the static values and join to it. This is extremely beneficial from a performace perspective since the SQL Engine can build effective execution plans around a JOIN, and you have the potential to add indexes as well if needed.

The disadvantage of using functions (or any inline calculated values) is the callout happens for every potential row returned, which is costly. Why? Because SQL has to first create a full dataset with the calculated values and then apply the WHERE clause to that dataset.

Nine times out of ten you should not need dynamically calculated cell values in your queries. Its much better to figure out what you will need, then design a data model that supports it, and populate that data model with semi-dynamic data (via batch jobs for instance) and use the SQL Engine to do the heavy lifting via standard SQL.

Can I add and remove elements of enumeration at runtime in Java

Behind the curtain, enums are POJOs with a private constructor and a bunch of public static final values of the enum's type (see here for an example). In fact, up until Java5, it was considered best-practice to build your own enumeration this way, and Java5 introduced the enum keyword as a shorthand. See the source for Enum<T> to learn more.

So it should be no problem to write your own 'TypeSafeEnum' with a public static final array of constants, that are read by the constructor or passed to it.

Also, do yourself a favor and override equals, hashCode and toString, and if possible create a values method

The question is how to use such a dynamic enumeration... you can't read the value "PI=3.14" from a file to create enum MathConstants and then go ahead and use MathConstants.PI wherever you want...

LEFT JOIN only first row

Version without subselect:

   SELECT f.title,
          MIN(a.artist_name) artist_name
     FROM feeds f
LEFT JOIN feeds_artists fa ON fa.feed_id =
LEFT JOIN artists a ON fa.artist_id = a.artist_id

Java String to Date object of the format "yyyy-mm-dd HH:mm:ss"

For future reference:

 yyyy => 4 digit year
 MM   => 2 digit month (you must type MM in ALL CAPS)
 dd   => 2 digit "day of the month"

 HH   => 2-digit "hour in day" (0 to 23)
 mm   => 2-digit minute (you must type mm in lowercase)
 ss   => 2-digit seconds
 SSS  => milliseconds

So "yyyy-MM-dd HH:mm:ss" returns "2018-01-05 09:49:32"

But "MMM dd, yyyy hh:mm a" returns "Jan 05, 2018 09:49 am"

The so-called examples at show only output. They do not tell you what formats to use!

How can I add (simple) tracing in C#?

DotNetCoders has a starter article on it: They talk about how to set up the switches in the configuration file and how to write the code, but it is pretty old (2002).

There's another article on CodeProject: A Treatise on Using Debug and Trace classes, including Exception Handling, but it's the same age.

CodeGuru has another article on custom TraceListeners: Implementing a Custom TraceListener

DateTime.ToString("MM/dd/yyyy HH:mm:ss.fff") resulted in something like "09/14/2013"

You can use String.Format:

DateTime d = DateTime.Now;
string str = String.Format("{0:00}/{1:00}/{2:0000} {3:00}:{4:00}:{5:00}.{6:000}", d.Month, d.Day, d.Year, d.Hour, d.Minute, d.Second, d.Millisecond);
// I got this result: "02/23/2015 16:42:38.234"

Javascript to set hidden form value on drop down change

This is with jQuery.

$('#selectFormElement').change( function() {
} );

In the html

<select id="selectFormElement" name="..."> ... </select>
<input type="hidden" name="..." id="hiddenFormElement" />

Escape dot in a regex range

The dot operator . does not need to be escaped inside of a character class [].

python-dev installation error: ImportError: No module named apt_pkg

If you're using python 3.5, downgrade to 3.4. That's the safest move to do.

Under /usr/lib/python3/dist-packages you'll see *34m* which python 3.5 can't use. zhazha answer symlink to it.

Error: Unable to run mksdcard SDK tool

This is what worked for me

When I tried the Accepted ans my Android Studio hangs on start-up

This is the link

and This is the Command

$ sudo apt-get install libc6:i386 libncurses5:i386 libstdc++6:i386 lib32z1

Setting focus on an HTML input box on page load

You could also use:

<body onload="focusOnInput()">
    <form name="passwordForm" action="verify.php" method="post">
        <input name="passwordInput" type="password" />

And then in your JavaScript:

function focusOnInput() {

How to enter quotes in a Java string?

Here is full java example:-

public class QuoteInJava {     

public static void main (String args[])
            System.out.println ("If you need to 'quote' in Java");
            System.out.println ("you can use single \' or double \" quote");

Here is Out PUT:-

If you need to 'quote' in Java
you can use single ' or double " quote

enter image description here

Access Controller method from another controller in Laravel 5

namespace App\Http\Controllers;

//call the controller you want to use its methods
use App\Http\Controllers\AdminController;

use Illuminate\Http\Request;

use App\Http\Requests;

class MealController extends Controller
      public function try_call( AdminController $admin){
         return $admin->index();   

Simple Digit Recognition OCR in OpenCV-Python

OCR which stands for Optical Character Recognition is a computer vision technique used to identify the different types of handwritten digits that are used in common mathematics. To perform OCR in OpenCV we will use the KNN algorithm which detects the nearest k neighbors of a particular data point and then classifies that data point based on the class type detected for n neighbors.

Data Used

This data contains 5000 handwritten digits where there are 500 digits for every type of digit. Each digit is of 20×20 pixel dimensions. We will split the data such that 250 digits are for training and 250 digits are for testing for every class.

Below is the implementation.

import numpy as np
import cv2
# Read the image
image = cv2.imread('digits.png')
# gray scale conversion
gray_img = cv2.cvtColor(image,
# We will divide the image
# into 5000 small dimensions 
# of size 20x20
divisions = list(np.hsplit(i,100) for i in np.vsplit(gray_img,50))
# Convert into Numpy array
# of size (50,100,20,20)
NP_array = np.array(divisions)
# Preparing train_data
# and test_data.
# Size will be (2500,20x20)
train_data = NP_array[:,:50].reshape(-1,400).astype(np.float32)
# Size will be (2500,20x20)
test_data = NP_array[:,50:100].reshape(-1,400).astype(np.float32)
# Create 10 different labels 
# for each type of digit
k = np.arange(10)
train_labels = np.repeat(k,250)[:,np.newaxis]
test_labels = np.repeat(k,250)[:,np.newaxis]
# Initiate kNN classifier
knn =
# perform training of data
# obtain the output from the
# classifier by specifying the
# number of neighbors.
ret, output ,neighbours,
distance = knn.findNearest(test_data, k = 3)
# Check the performance and
# accuracy of the classifier.
# Compare the output with test_labels
# to find out how many are wrong.
matched = output==test_labels
correct_OP = np.count_nonzero(matched)
#Calculate the accuracy.
accuracy = (correct_OP*100.0)/(output.size)
# Display accuracy.



Well, I decided to workout myself on my question to solve the above problem. What I wanted is to implement a simple OCR using KNearest or SVM features in OpenCV. And below is what I did and how. (it is just for learning how to use KNearest for simple OCR purposes).

1) My first question was about file that comes with OpenCV samples. I wanted to know what is inside that file.

It contains a letter, along with 16 features of that letter.

And this SOF helped me to find it. These 16 features are explained in the paper Letter Recognition Using Holland-Style Adaptive Classifiers. (Although I didn't understand some of the features at the end)

2) Since I knew, without understanding all those features, it is difficult to do that method. I tried some other papers, but all were a little difficult for a beginner.

So I just decided to take all the pixel values as my features. (I was not worried about accuracy or performance, I just wanted it to work, at least with the least accuracy)

I took the below image for my training data:

enter image description here

(I know the amount of training data is less. But, since all letters are of the same font and size, I decided to try on this).

To prepare the data for training, I made a small code in OpenCV. It does the following things:

  1. It loads the image.
  2. Selects the digits (obviously by contour finding and applying constraints on area and height of letters to avoid false detections).
  3. Draws the bounding rectangle around one letter and wait for key press manually. This time we press the digit key ourselves corresponding to the letter in the box.
  4. Once the corresponding digit key is pressed, it resizes this box to 10x10 and saves all 100 pixel values in an array (here, samples) and corresponding manually entered digit in another array(here, responses).
  5. Then save both the arrays in separate .txt files.

At the end of the manual classification of digits, all the digits in the training data (train.png) are labeled manually by ourselves, image will look like below:

enter image description here

Below is the code I used for the above purpose (of course, not so clean):

import sys

import numpy as np
import cv2

im = cv2.imread('pitrain.png')
im3 = im.copy()

gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray,(5,5),0)
thresh = cv2.adaptiveThreshold(blur,255,1,1,11,2)

#################      Now finding Contours         ###################

contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)

samples =  np.empty((0,100))
responses = []
keys = [i for i in range(48,58)]

for cnt in contours:
    if cv2.contourArea(cnt)>50:
        [x,y,w,h] = cv2.boundingRect(cnt)
        if  h>28:
            roi = thresh[y:y+h,x:x+w]
            roismall = cv2.resize(roi,(10,10))
            key = cv2.waitKey(0)

            if key == 27:  # (escape to quit)
            elif key in keys:
                sample = roismall.reshape((1,100))
                samples = np.append(samples,sample,0)

responses = np.array(responses,np.float32)
responses = responses.reshape((responses.size,1))
print "training complete"


Now we enter in to training and testing part.

For the testing part, I used the below image, which has the same type of letters I used for the training phase.

enter image description here

For training we do as follows:

  1. Load the .txt files we already saved earlier
  2. create an instance of the classifier we are using (it is KNearest in this case)
  3. Then we use KNearest.train function to train the data

For testing purposes, we do as follows:

  1. We load the image used for testing
  2. process the image as earlier and extract each digit using contour methods
  3. Draw a bounding box for it, then resize it to 10x10, and store its pixel values in an array as done earlier.
  4. Then we use KNearest.find_nearest() function to find the nearest item to the one we gave. ( If lucky, it recognizes the correct digit.)

I included last two steps (training and testing) in single code below:

import cv2
import numpy as np

#######   training part    ############### 
samples = np.loadtxt('',np.float32)
responses = np.loadtxt('',np.float32)
responses = responses.reshape((responses.size,1))

model = cv2.KNearest()

############################# testing part  #########################

im = cv2.imread('pi.png')
out = np.zeros(im.shape,np.uint8)
gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
thresh = cv2.adaptiveThreshold(gray,255,1,1,11,2)

contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)

for cnt in contours:
    if cv2.contourArea(cnt)>50:
        [x,y,w,h] = cv2.boundingRect(cnt)
        if  h>28:
            roi = thresh[y:y+h,x:x+w]
            roismall = cv2.resize(roi,(10,10))
            roismall = roismall.reshape((1,100))
            roismall = np.float32(roismall)
            retval, results, neigh_resp, dists = model.find_nearest(roismall, k = 1)
            string = str(int((results[0][0])))


And it worked, below is the result I got:

enter image description here

Here it worked with 100% accuracy. I assume this is because all the digits are of the same kind and the same size.

But anyway, this is a good start to go for beginners (I hope so).

Bootstrap 3 Multi-column within a single ul not floating properly

you are thinking too much... Take a look at this [i think this is what you wanted - if not let me know]


.even{background: red; color:white;}
.odd{background: darkred; color:white;}


<div class="container">
  <ul class="list-unstyled">
    <li class="col-md-6 odd">Dumby Content</li>
    <li class="col-md-6 odd">Dumby Content</li>
    <li class="col-md-6 even">Dumby Content</li>
    <li class="col-md-6 even">Dumby Content</li>
    <li class="col-md-6 odd">Dumby Content</li>
    <li class="col-md-6 odd">Dumby Content</li>

How to format strings using printf() to get equal length in the output

There's also the %n modifier which can help in certain circumstances. It returns the column on which the string was so far. Example: you want to write several rows that are within the width of the first row like a table.

int width1, width2;
int values[6][2];
printf("|%s%n|%s%n|\n", header1, &width1, header2, &width2);

for(i=0; i<6; i++)
   printf("|%*d|%*d|\n", width1, values[i][0], width2, values[i][1]);

will print two columns of the same width of whatever length the two strings header1 and header2 may have. I don't know if all implementations have the %n, but Solaris and Linux do.

data.frame rows to a list

Seems a current version of the purrr (0.2.2) package is the fastest solution:

by_row(x, function(v) list(v)[[1L]], .collate = "list")$.out

Let's compare the most interesting solutions:

data("Batting", package = "Lahman")
x <- Batting[1:10000, 1:10]
    split = split(x, seq_len(.row_names_info(x, 2L))),
    mapply = .mapply(function(...) structure(list(...), class = "data.frame", row.names = 1L), x, NULL),
    purrr = by_row(x, function(v) list(v)[[1L]], .collate = "list")$.out


Benchmark summary:
Time units : milliseconds 
  expr n.eval   min  lw.qu median   mean  up.qu  max  total relative
 split    100 983.0 1060.0 1130.0 1130.0 1180.0 1450 113000     34.3
mapply    100 826.0  894.0  963.0  972.0 1030.0 1320  97200     29.3
 purrr    100  24.1   28.6   32.9   44.9   40.5  183   4490      1.0

Also we can get the same result with Rcpp:

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
List df2list(const DataFrame& x) {
    std::size_t nrows = x.rows();
    std::size_t ncols = x.cols();
    CharacterVector nms = x.names();
    List res(no_init(nrows));
    for (std::size_t i = 0; i < nrows; ++i) {
        List tmp(no_init(ncols));
        for (std::size_t j = 0; j < ncols; ++j) {
            switch(TYPEOF(x[j])) {
                case INTSXP: {
                    if (Rf_isFactor(x[j])) {
                        IntegerVector t = as<IntegerVector>(x[j]);
                        RObject t2 = wrap(t[i]);
                        t2.attr("class") = "factor";
                        t2.attr("levels") = t.attr("levels");
                        tmp[j] = t2;
                    } else {
                        tmp[j] = as<IntegerVector>(x[j])[i];
                case LGLSXP: {
                    tmp[j] = as<LogicalVector>(x[j])[i];
                case CPLXSXP: {
                    tmp[j] = as<ComplexVector>(x[j])[i];
                case REALSXP: {
                    tmp[j] = as<NumericVector>(x[j])[i];
                case STRSXP: {
                    tmp[j] = as<std::string>(as<CharacterVector>(x[j])[i]);
                default: stop("Unsupported type '%s'.", type2name(x));
        tmp.attr("class") = "data.frame";
        tmp.attr("row.names") = 1;
        tmp.attr("names") = nms;
        res[i] = tmp;
    res.attr("names") = x.attr("row.names");
    return res;

Now caompare with purrr:

    purrr = by_row(x, function(v) list(v)[[1L]], .collate = "list")$.out,
    rcpp = df2list(x)


Benchmark summary:
Time units : milliseconds 
 expr n.eval  min lw.qu median mean up.qu   max total relative
purrr    100 25.2  29.8   37.5 43.4  44.2 159.0  4340      1.1
 rcpp    100 19.0  27.9   34.3 35.8  37.2  93.8  3580      1.0

Using std::max_element on a vector<double>

min/max_element return the iterator to the min/max element, not the value of the min/max element. You have to dereference the iterator in order to get the value out and assign it to a double. That is:

cLower = *min_element(C.begin(), C.end());

Android AlertDialog Single Button

Its very simple

new AlertDialog.Builder(this).setView(input).setPositiveButton("ENTER",            
                        new DialogInterface.OnClickListener()                      
                        {   public void onClick(DialogInterface di,int id)     

In case you wish to read the full program see here: Program to take input from user using dialog and output to screen

Mapping two integers to one, in a unique and deterministic way

f(a, b) = s(a+b) + a, where s(n) = n*(n+1)/2

  • This is a function -- it is deterministic.
  • It is also injective -- f maps different values for different (a,b) pairs. You can prove this using the fact: s(a+b+1)-s(a+b) = a+b+1 < a.
  • It returns quite small values -- good if your are going to use it for array indexing, as the array does not have to be big.
  • It is cache-friendly -- if two (a, b) pairs are close to each other, then f maps numbers to them which are close to each other (compared to other methods).

I did not understand what You mean by:

should always yield an integer on either the positive or the negative side of integers

How can I write (greater than), (less than) characters in this forum?

How to create a backup of a single table in a postgres database?

If you are on Ubuntu,

  1. Login to your postgres user sudo su postgres
  2. pg_dump -d <database_name> -t <table_name> > file.sql

Make sure that you are executing the command where the postgres user have write permissions (Example: /tmp)


If you want to dump the .sql in another computer, you may need to consider skipping the owner information getting saved into the .sql file.

You can use pg_dump --no-owner -d <database_name> -t <table_name> > file.sql

Missing XML comment for publicly visible type or member

I know this is a really old thread, but it's the first response on google so I thought I'd add this bit of information:

This behavior only occurs when the warning level is set to 4 under "Project Properties" -> "Build". Unless you really need that much information you can set it to 3 and you'll get rid of these warnings. Of course, changing the warning level affects more than just comments, so please refer to the documentation if you're unsure what you'll be missing:

How to safely open/close files in python 2.4

In the above solution, repeated here:

f = open('file.txt', 'r')

    # do stuff with f

if something bad happens (you never know ...) after opening the file successfully and before the try, the file will not be closed, so a safer solution is:

f = None
    f = open('file.txt', 'r')

    # do stuff with f

    if f is not None:

Check cell for a specific letter or set of letters

Some options without REGEXMATCH, since you might want to be case insensitive and not want say blast or ablative to trigger a YES. Using comma as the delimiter, as in the OP, and for the moment ignoring the IF condition:

First very similar to @user1598086's answer:


Is case sensitive but returns #VALUE! rather than NO and a number rather than YES (both of which can however be changed to NO/YES respectively).


Case insensitive, so treats Black and black equally. Returns as above.

The former (for the latter equivalent) to indicate whether bla present after the first three characters in A1:


Returns a number for blazer, black but #VALUE! for blazer, blue.

To find Bla only when a complete word on its own (ie between spaces - not at the start or end of a 'sentence'):

=SEARCH(" Bla ",A1) 

Since the return in all cases above is either a number ("found", so YES preferred) or #VALUE! we can use ISERROR to test for #VALUE! within an IF formula, for instance taking the first example above:


Longer than the regexmatch but the components are easily adjustable.

Observable.of is not a function

Actually I have imports messed up. In latest version of RxJS we can import it like that:

import 'rxjs/add/observable/of';

Sublime Text 2: How do I change the color that the row number is highlighted?

On windows 7, find

C:\Users\Simion\AppData\Roaming\Sublime Text 2\Packages\Color Scheme - Default

Find your color scheme file, open it, and find lineHighlight.


replace #ccc with your preferred background color.

Generating a list of pages (not posts) without the index file

I can offer you a jquery solution

add this in your <head></head> tag

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

add this after </ul>

 <script> $('ul li:first').remove(); </script> 

How to write LaTeX in IPython Notebook?

Since, I was not able to use all the latex commands in Code even after using the %%latex keyword or the $..$ limiter, I installed the nbextensions through which I could use the latex commands in Markdown. After following the instructions here: and then restarting the Jupyter and then localhost:8888/nbextensions and then activating "Latex Environment for Jupyter", I could run many Latex commands. Examples are here:

\section{First section}
c = \sqrt{a^2 + b^2}
\item First item
\item Second item

As you see, I am still unable to use usepackage. But maybe it will be improved in the future.

enter image description here

CertificateException: No name matching found

In Java 8 you can skip server name checking with the following code:

HttpsURLConnection.setDefaultHostnameVerifier ((hostname, session) -> true);

However this should be used only in development!

PHPMyAdmin Default login password

If it was installed with plesk (not sure if it's just that, or on the phpmyadmin side: It changes the root user to admin.

Load image from resources

ResourceManager will work if your image is in a resource file. If it is just a file in your project (let's say the root) you can get it using something like this:

System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
System.IO.Stream file = assembly .GetManifestResourceStream("AssemblyName." + channel);
this.pictureBox1.Image = Image.FromStream(file);

Or if you're in WPF:

    private ImageSource GetImage(string channel)
        StreamResourceInfo sri = Application.GetResourceStream(new Uri("/TestApp;component/" + channel, UriKind.Relative));
        BitmapImage bmp = new BitmapImage();
        bmp.StreamSource = sri.Stream;

        return bmp;

Global variable Python classes

What you have is correct, though you will not call it global, it is a class attribute and can be accessed via class e.g Shape.lolwut or via an instance e.g. shape.lolwut but be careful while setting it as it will set an instance level attribute not class attribute

class Shape(object):
    lolwut = 1

shape = Shape()

print Shape.lolwut,  # 1
print shape.lolwut,  # 1

# setting shape.lolwut would not change class attribute lolwut 
# but will create it in the instance
shape.lolwut = 2

print Shape.lolwut,  # 1
print shape.lolwut,  # 2

# to change class attribute access it via class
Shape.lolwut = 3

print Shape.lolwut,  # 3
print shape.lolwut   # 2 


1 1 1 2 3 2

Somebody may expect output to be 1 1 2 2 3 3 but it would be incorrect

Bash syntax error: unexpected end of file

Apparently, some versions of the shell can also emit this message when the final line of your script lacks a newline.

Adding options to a <select> using jQuery?

This is the way i did it, with a button to add each select tag.

$(document).on("click","#button",function() {

How to disable the resize grabber of <textarea>?

example of textarea for disable the resize option

<textarea CLASS="foo"></textarea>



ValueError: shape mismatch: objects cannot be broadcast to a single shape

This particular error implies that one of the variables being used in the arithmetic on the line has a shape incompatible with another on the same line (i.e., both different and non-scalar). Since n and the output of np.add.reduce() are both scalars, this implies that the problem lies with xm and ym, the two of which are simply your x and y inputs minus their respective means.

Based on this, my guess is that your x and y inputs have different shapes from one another, making them incompatible for element-wise multiplication.

** Technically, it's not that variables on the same line have incompatible shapes. The only problem is when two variables being added, multiplied, etc., have incompatible shapes, whether the variables are temporary (e.g., function output) or not. Two variables with different shapes on the same line are fine as long as something else corrects the issue before the mathematical expression is evaluated.

Python element-wise tuple operations like sum

Sort of combined the first two answers, with a tweak to ironfroggy's code so that it returns a tuple:

import operator

class stuple(tuple):
    def __add__(self, other):
        return self.__class__(map(operator.add, self, other))
        # obviously leaving out checking lengths

>>> a = stuple([1,2,3])
>>> b = stuple([3,2,1])
>>> a + b
(4, 4, 4)

Note: using self.__class__ instead of stuple to ease subclassing.

How to add new column to an dataframe (to the front not end)?

Add column "a"

> df["a"] <- 0
> df
  b c d a
1 1 2 3 0
2 1 2 3 0
3 1 2 3 0

Sort by column using colum name

> df <- df[c('a', 'b', 'c', 'd')]
> df
  a b c d
1 0 1 2 3
2 0 1 2 3
3 0 1 2 3

Or sort by column using index

> df <- df[colnames(df)[c(4,1:3)]]
> df
  a b c d
1 0 1 2 3
2 0 1 2 3
3 0 1 2 3

GitHub - List commits by author

Just add ?author=<emailaddress> or ?author=<githubUserName> to the url when viewing the "commits" section of a repo.

How do I convert a single character into it's hex ascii value in python

This might help

import binascii

x = b'test'
x = binascii.hexlify(x)
y = str(x,'ascii')

print(x) # Outputs b'74657374' (hex encoding of "test")
print(y) # Outputs 74657374

x_unhexed = binascii.unhexlify(x)
print(x_unhexed) # Outputs b'test'

x_ascii = str(x_unhexed,'ascii')
print(x_ascii) # Outputs test

This code contains examples for converting ASCII characters to and from hexadecimal. In your situation, the line you'd want to use is str(binascii.hexlify(c),'ascii').

How can I be notified when an element is added to the page?

A pure javascript solution (without jQuery):

const SEARCH_DELAY = 100; // in ms

// it may run indefinitely. TODO: make it cancellable, using Promise's `reject`
function waitForElementToBeAdded(cssSelector) {
  return new Promise((resolve) => {
    const interval = setInterval(() => {
      if (element = document.querySelector(cssSelector)) {

console.log(await waitForElementToBeAdded('#main'));

Example: Communication between Activity and Service using Messaging

I have seen all answers. I want tell most robust way now a day. That will make you communicate between Activity - Service - Dialog - Fragments (Everything).


This lib which i am using in my projects has great features related to messaging.

EventBus in 3 steps

  1. Define events:

    public static class MessageEvent { /* Additional fields if needed */ }

  2. Prepare subscribers:

Declare and annotate your subscribing method, optionally specify a thread mode:

@Subscribe(threadMode = ThreadMode.MAIN) 
public void onMessageEvent(MessageEvent event) {/* Do something */};

Register and unregister your subscriber. For example on Android, activities and fragments should usually register according to their life cycle:

public void onStart() {

public void onStop() {
  1. Post events:

    EventBus.getDefault().post(new MessageEvent());

Just add this dependency in your app level gradle

compile 'org.greenrobot:eventbus:3.1.1'

How to copy a row and insert in same table with a autoincrement field in MySQL?

I tend to use a variation of what mu is too short posted:

INSERT INTO something_log
FROM something AS s
WHERE = 1;

As long as the tables have identical fields (excepting the auto increment on the log table), then this works nicely.

Since I use stored procedures whenever possible (to make life easier on other programmers who aren't too familiar with databases), this solves the problem of having to go back and update procedures every time you add a new field to a table.

It also ensures that if you add new fields to a table they will start appearing in the log table immediately without having to update your database queries (unless of course you have some that set a field explicitly)

Warning: You will want to make sure to add any new fields to both tables at the same time so that the field order stays the same... otherwise you will start getting odd bugs. If you are the only one that writes database interfaces AND you are very careful then this works nicely. Otherwise, stick to naming all of your fields.

Note: On second thought, unless you are working on a solo project that you are sure won't have others working on it stick to listing all field names explicitly and update your log statements as your schema changes. This shortcut probably is not worth the long term headache it can cause... especially on a production system.

I want to vertical-align text in select box

So far this is working fine for me:

line-height: 100%;

Restarting cron after changing crontab file?

There are instances wherein cron needs to be restarted in order for the start up script to work. There's nothing wrong in restarting the cron.

sudo service cron restart

How to check if a word is an English word with Python?

With pyEnchant.checker SpellChecker:

from enchant.checker import SpellChecker

def is_in_english(quote):
    d = SpellChecker("en_US")
    errors = [err.word for err in d]
    return False if ((len(errors) > 4) or len(quote.split()) < 3) else True

print(is_in_english('“Two things are infinite: the universe and human stupidity; and I\'m not sure about the universe.”'))

> False
> True

Express-js can't GET my static files, why?

I find my css file and add a route to it:

app.get('/css/MyCSS.css', function(req, res){
  res.sendFile(__dirname + '/public/css/MyCSS.css');

Then it seems to work.

Trigger event on body load complete js/jquery


  // your code...this will run when DOM is ready

If you want to run your code after all page resources including images/frames/DOM have loaded, you need to use load event:

  // your code...


window.onload = function(){
  // your code...

How to access custom attributes from event object in React?

<div className='btn' onClick={(e) =>
    <i className='fa fa-bold' />

so e.currentTarget.attributes['tag'].value works for me

Java - Getting Data from MySQL database

Here is what I just did right now:

import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.sun.javafx.runtime.VersionInfo;  

public class ConnectToMySql {
public static ConnectBean dataBean = new ConnectBean();

public static void main(String args[]) {

public static void getData () {

    try {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mynewpage", 
 "root", "root");
 // here mynewpage is database name, root is username and password
Statement stmt = con.createStatement();
        System.out.println("stmt  " + stmt);
        ResultSet rs = stmt.executeQuery("select * from carsData");
        System.out.println("rs  " + rs);
        int count = 1;
        while ( {
            String vehicleType = rs.getString("VHCL_TYPE");
            System.out.println(count  +": " + vehicleType);


    } catch (Exception e) {
        Logger lgr = Logger.getLogger(VersionInfo.class.getName());
        lgr.log(Level.SEVERE, e.getMessage(), e);



The Above code will get you the first column of the table you have.

This is the table which you might need to create in your MySQL database


standard size for html newsletter template

Short answer: 400-800 pixels.

What I have read is that HTML newsletter width should be as narrow as possible without being too narrow. For instance, 400-500 pixels for a one column layout is a lower limit. Any less may look too weird.

Today's widescreen monitors allow for more horizontal pixels and most web email clients will either be of the two-column variety (Gmail) or 3-pane layout where the content window bellow the inbox list (Hotmail and Yahoo). In either case, you can be okay with 800 pixels if you're targeting the 1280 wide audience. An older or less technical audience may have older, square monitors.

There is the problem of Outlook having a three-column layout. That limits the width of your email even more. With them, you may want to go even narrower.

I just recently created a template that required an ad banner that is 730 pixels wide. It was near in the wide range, but not so much that most people could not double-click the email an open a new window in Outlook (the web email users should be okay for the most part).

Hope this advice helps.

Storing database records into array


// run query
$query = mysql_query("SELECT * FROM table");

// set array
$array = array();

// look through query
while($row = mysql_fetch_assoc($query)){

  // add each row returned into an array
  $array[] = $row;

  // OR just echo the data:
  echo $row['username']; // etc


// debug:
print_r($array); // show all array data
echo $array[0]['username']; // print the first rows username

Spring Boot not serving static content

Did you check the Spring Boot reference docs?

By default Spring Boot will serve static content from a folder called /static (or /public or /resources or /META-INF/resources) in the classpath or from the root of the ServletContext.

You can also compare your project with the guide Serving Web Content with Spring MVC, or check out the source code of the spring-boot-sample-web-ui project.

How to use WinForms progress bar?

Since .NET 4.5 you can use combination of async and await with Progress for sending updates to UI thread:

private void Calculate(int i)
    double pow = Math.Pow(i, i);

public void DoWork(IProgress<int> progress)
    // This method is executed in the context of
    // another thread (different than the main UI thread),
    // so use only thread-safe code
    for (int j = 0; j < 100000; j++)

        // Use progress to notify UI thread that progress has
        // changed
        if (progress != null)
            progress.Report((j + 1) * 100 / 100000);

private async void button1_Click(object sender, EventArgs e)
    progressBar1.Maximum = 100;
    progressBar1.Step = 1;

    var progress = new Progress<int>(v =>
        // This lambda is executed in context of UI thread,
        // so it can safely update form controls
        progressBar1.Value = v;

    // Run operation in another thread
    await Task.Run(() => DoWork(progress));

    // TODO: Do something after all calculations

Tasks are currently the preferred way to implement what BackgroundWorker does.

Tasks and Progress are explained in more detail here:

How can I rename a single column in a table at select?

There is no need to use AS, just use:

SELECT table1.price Table1 Price, table2.price Table2 Price, .....

Comparing two NumPy arrays for equality, element-wise


test if all values of array (A==B) are True.

Note: maybe you also want to test A and B shape, such as A.shape == B.shape

Special cases and alternatives (from dbaupp's answer and yoavram's comment)

It should be noted that:

  • this solution can have a strange behavior in a particular case: if either A or B is empty and the other one contains a single element, then it return True. For some reason, the comparison A==B returns an empty array, for which the all operator returns True.
  • Another risk is if A and B don't have the same shape and aren't broadcastable, then this approach will raise an error.

In conclusion, if you have a doubt about A and B shape or simply want to be safe: use one of the specialized functions:

np.array_equal(A,B)  # test if same shape, same elements values
np.array_equiv(A,B)  # test if broadcastable shape, same elements values
np.allclose(A,B,...) # test if same shape, elements have close enough values

Rename MySQL database

It's possible to copy database via mysqldump command without storing dump into file:

  1. mysql -u root -p -e "create database my_new_database"
  2. mysqldump -u root -p original_database | mysql -u root -p my_new_database
  3. mysql -u root -p -e "drop database original_database"

how to set font size based on container size?

Another js alternative:

Working Example

fontsize = function () {
    var fontSize = $("#container").width() * 0.10; // 10% of container width
    $("#container h1").css('font-size', fontSize);

Or as stated in torazaburo's answer you could use svg. I put together a simple example as a proof of concept:

SVG Example

<div id="container">
    <svg width="100%" height="100%" viewBox="0 0 13 15">
        <text x="0" y="13">X</text>

what is the use of $this->uri->segment(3) in codeigniter pagination

Let's say you have a url like this

If you want to know what are the arguments that are being passed in this url

$params = array_slice($this->uri->rsegment_array(), $param_offset);

Output will be:

array (size=2)
  0 => string 'arg1'
  1 => string 'arg2'

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

An XML declaration is not required in all XML documents; however XHTML document authors are strongly encouraged to use XML declarations in all their documents. Such a declaration is required when the character encoding of the document is other than the default UTF-8 or UTF-16 and no encoding was determined by a higher-level protocol. Here is an example of an XHTML document. In this example, the XML declaration is included.

<?xml version="1.0" encoding="UTF-8"?>
 <!DOCTYPE html 
 PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
 <html xmlns="" xml:lang="en" lang="en">
    <title>Virtual Library</title>
    <p>Moved to <a href=""></a>.</p>

Please refer to the W3 standards for XML.

Warning: mysqli_query() expects at least 2 parameters, 1 given. What?

The issue is that you're not saving the mysqli connection. Change your connect to:

$aVar = mysqli_connect('localhost','tdoylex1_dork','dorkk','tdoylex1_dork');

And then include it in your query:

$query1 = mysqli_query($aVar, "SELECT name1 FROM users
    LIMIT 1");
$aName1 = mysqli_fetch_assoc($query1);
$name1 = $aName1['name1'];

Also don't forget to enclose your connections variables as strings as I have above. This is what's causing the error but you're using the function wrong, mysqli_query returns a query object but to get the data out of this you need to use something like mysqli_fetch_assoc to actually get the data out into a variable as I have above.

Compare 2 JSON objects

Simply parsing the JSON and comparing the two objects is not enough because it wouldn't be the exact same object references (but might be the same values).

You need to do a deep equals.

From - which seems the use jQuery.

Object.extend(Object, {
   deepEquals: function(o1, o2) {
     var k1 = Object.keys(o1).sort();
     var k2 = Object.keys(o2).sort();
     if (k1.length != k2.length) return false;
     return, function(keyPair) {
       if(typeof o1[keyPair[0]] == typeof o2[keyPair[1]] == "object"){
         return deepEquals(o1[keyPair[0]], o2[keyPair[1]])
       } else {
         return o1[keyPair[0]] == o2[keyPair[1]];


var anObj = JSON.parse(jsonString1);
var anotherObj= JSON.parse(jsonString2);

if (Object.deepEquals(anObj, anotherObj))

Actionbar notification count icon (badge) like Google has

I found a very good solution here, I'm using it with kotlin.

First, in the drawable folder you have to create item_count.xml:

<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android=""
<corners android:radius="8dp" />
<solid android:color="#f20000" />
    android:color="#FFF" />
    android:top="5dp" />

In your Activity_Main Layout some like:



                            android:background="@mipmap/ic_notification" />




And you can modify like:

btnBadge.setOnClickListener { view ->
        Snackbar.make(view,"badge click", Snackbar.LENGTH_LONG) .setAction("Action", null).show()
        txtBadge.text = "0"

SHA512 vs. Blowfish and Bcrypt

I would recommend Ulrich Drepper's SHA-256/SHA-512 based crypt implementation.

We ported these algorithms to Java, and you can find a freely licensed version of them at

Note that most modern (L)Unices support Drepper's algorithm in their /etc/shadow files.

How do I call a dynamically-named method in Javascript?

Try These

Call Functions With Dynamic Names, like this:

let dynamic_func_name = 'alert';
(new Function(dynamic_func_name+'()'))()

with parameters:

let dynamic_func_name = 'alert';
let para_1 = 'HAHAHA';
let para_2 = 'ABCD';
(new Function(`${dynamic_func_name}('${para_1}','${para_2}')`))()

Run Dynamic Code:

let some_code = "alert('hahaha');";
(new Function(some_code))()

function is not defined error in Python

It works for me:

>>> def pyth_test (x1, x2):
...     print x1 + x2
>>> pyth_test(1,2)

Make sure you define the function before you call it.

Dynamically create an array of strings with malloc

You should assign an array of char pointers, and then, for each pointer assign enough memory for the string:

char **orderedIds;

orderedIds = malloc(variableNumberOfElements * sizeof(char*));
for (int i = 0; i < variableNumberOfElements; i++)
    orderedIds[i] = malloc((ID_LEN+1) * sizeof(char)); // yeah, I know sizeof(char) is 1, but to make it clear...

Seems like a good way to me. Although you perform many mallocs, you clearly assign memory for a specific string, and you can free one block of memory without freeing the whole "string array"

How to create an on/off switch with Javascript/CSS?

Using plain javascript



     <!-- define on/off styles -->
     <style type="text/css">
      .on  { background:blue; }
      .off { background:red; }

     <!-- define the toggle function -->
     <script language="javascript">
        function toggleState(item){
           if(item.className == "on") {
           } else {

     <!-- call 'toggleState' whenever clicked -->
     <input type="button" id="btn" value="button" 
        class="off" onclick="toggleState(this)" />


Using jQuery

If you use jQuery, you can do it using the toggle function, or using the toggleClass function inside click event handler, like this:


Using jQuery UI effects, you can animate transitions:

iReport not starting using JRE 8

iReport does not work with java 8.

  • if not yet installed, download and install java 7
  • find the install dir of your iReport and open the file: ireport.conf

(you will find it here: iReport-x.x.x\etc\ )

change this line:


to this (if not this is your java 7 install dir then replace the parameter value between ""s with your installed java 7's path):

jdkhome="C:\Program Files\Java\jdk1.7.0_67"

Flattening a shallow list in Python

If each item in the list is a string (and any strings inside those strings use " " rather than ' '), you can use regular expressions (re module)

>>> flattener = re.compile("\'.*?\'")
>>> flattener
<_sre.SRE_Pattern object at 0x10d439ca8>
>>> stred = str(in_list)
>>> outed = flattener.findall(stred)

The above code converts in_list into a string, uses the regex to find all the substrings within quotes (i.e. each item of the list) and spits them out as a list.

Store multiple values in single key in json

    "success": true,
    "data": {
        "BLR": {
            "origin": "JAI",
            "destination": "BLR",
            "price": 127,
            "transfers": 0,
            "airline": "LB",
            "flight_number": 655,
            "departure_at": "2017-06-03T18:20:00Z",
            "return_at": "2017-06-07T08:30:00Z",
            "expires_at": "2017-03-05T08:40:31Z"

Oracle query to identify columns having special characters

They key is the backslash escape character will not work with the right square bracket inside of the character class square brackets (it is interpreted as a literal backslash inside the character class square brackets). Add the right square bracket with an OR at the end like this:

select EmpNo, SampleText
from test 
where NOT regexp_like(SampleText, '[ A-Za-z0-9.{}[]|]');

default web page width - 1024px or 980px?

This is a bit of an open ended question since screen sizes are changing all the time and what might have been correct two years ago would likely be out of date now.

I use Twitter Bootstrap 3 at present and it uses a fluid grid system designed to work at sizes ranging from mobile/very small all the way up to the huge wide screen monitors that are now available.

Currently the upper default in BS3 is 1200px which translates to a container width of 1144px after taking account of margins and padding of the grids elements.

In my experience, modern designers are working to a width of around 1366px for desktop. All recent designs I've been given to implement have been 1366px.

Note also that you can customise the BS3 grid quite heavily. For example we will use a 32 column grid with 4px gutter in our sites/designs going forwards.

Ultimately the decision on page width needs to be made based on your website analytics and the screen sizes that your visitors typically use.

Font size of TextView in Android application changes on changing font size from native settings

Also note that if the textSize is set in code, calling textView.setTextSize(X) interprets the number (X) as SP. Use setTextSize(TypedValue.COMPLEX_UNIT_DIP, X) to set values in dp.

With jQuery, how do I capitalize the first letter of a text field while the user is still editing that field?

This will simply transform you first letter of text:


Chrome extension: accessing localStorage in content script

Update 2016:

Google Chrome released the storage API:

It is pretty easy to use like the other Chrome APIs and you can use it from any page context within Chrome.

    // Save it using the Chrome extension storage API.{'foo': 'hello', 'bar': 'hi'}, function() {
      console.log('Settings saved');

    // Read it using the storage API['foo', 'bar'], function(items) {
      message('Settings retrieved', items);

To use it, make sure you define it in the manifest:

    "permissions": [

There are methods to "remove", "clear", "getBytesInUse", and an event listener to listen for changed storage "onChanged"

Using native localStorage (old reply from 2011)

Content scripts run in the context of webpages, not extension pages. Therefore, if you're accessing localStorage from your contentscript, it will be the storage from that webpage, not the extension page storage.

Now, to let your content script to read your extension storage (where you set them from your options page), you need to use extension message passing.

The first thing you do is tell your content script to send a request to your extension to fetch some data, and that data can be your extension localStorage:


chrome.runtime.sendMessage({method: "getStatus"}, function(response) {


chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.method == "getStatus")
      sendResponse({status: localStorage['status']});
      sendResponse({}); // snub them.

You can do an API around that to get generic localStorage data to your content script, or perhaps, get the whole localStorage array.

I hope that helped solve your problem.

To be fancy and generic ...


chrome.runtime.sendMessage({method: "getLocalStorage", key: "status"}, function(response) {


chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.method == "getLocalStorage")
      sendResponse({data: localStorage[request.key]});
      sendResponse({}); // snub them.

How can I display a list view in an Android Alert Dialog?

According to the documentation, there are three kinds of lists that can be used with an AlertDialog:

  1. Traditional single-choice list
  2. Persistent single-choice list (radio buttons)
  3. Persistent multiple-choice list (checkboxes)

I will give an example of each below.

Traditional single-choice list

The way to make a traditional single-choice list is to use setItems.

enter image description here

Java version

// setup the alert builder
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Choose an animal");

// add a list
String[] animals = {"horse", "cow", "camel", "sheep", "goat"};
builder.setItems(animals, new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int which) {
        switch (which) {
            case 0: // horse
            case 1: // cow
            case 2: // camel
            case 3: // sheep
            case 4: // goat

// create and show the alert dialog
AlertDialog dialog = builder.create();;

There is no need for an OK button because as soon as the user clicks on a list item control is returned to the OnClickListener.

Kotlin version

// setup the alert builder
val builder = AlertDialog.Builder(context)
builder.setTitle("Choose an animal")

// add a list
val animals = arrayOf("horse", "cow", "camel", "sheep", "goat")
builder.setItems(animals) { dialog, which ->
    when (which) {
        0 -> { /* horse */ }
        1 -> { /* cow   */ }
        2 -> { /* camel */ }
        3 -> { /* sheep */ }
        4 -> { /* goat  */ }

// create and show the alert dialog
val dialog = builder.create()

Radio button list

enter image description here

The advantage of the radio button list over the traditional list is that the user can see what the current setting is. The way to make a radio button list is to use setSingleChoiceItems.

Java version

// setup the alert builder
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Choose an animal");

// add a radio button list
String[] animals = {"horse", "cow", "camel", "sheep", "goat"};
int checkedItem = 1; // cow
builder.setSingleChoiceItems(animals, checkedItem, new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int which) {
        // user checked an item

// add OK and Cancel buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int which) {
        // user clicked OK
builder.setNegativeButton("Cancel", null);

// create and show the alert dialog
AlertDialog dialog = builder.create();;

I hard coded the chosen item here, but you could keep track of it with a class member variable in a real project.

Kotlin version

// setup the alert builder
val builder = AlertDialog.Builder(context)
builder.setTitle("Choose an animal")

// add a radio button list
val animals = arrayOf("horse", "cow", "camel", "sheep", "goat")
val checkedItem = 1 // cow
builder.setSingleChoiceItems(animals, checkedItem) { dialog, which ->
    // user checked an item

// add OK and Cancel buttons
builder.setPositiveButton("OK") { dialog, which ->
    // user clicked OK
builder.setNegativeButton("Cancel", null)

// create and show the alert dialog
val dialog = builder.create()

Checkbox list

enter image description here

The way to make a checkbox list is to use setMultiChoiceItems.

Java version

// setup the alert builder
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Choose some animals");

// add a checkbox list
String[] animals = {"horse", "cow", "camel", "sheep", "goat"};
boolean[] checkedItems = {true, false, false, true, false};
builder.setMultiChoiceItems(animals, checkedItems, new DialogInterface.OnMultiChoiceClickListener() {
    public void onClick(DialogInterface dialog, int which, boolean isChecked) {
        // user checked or unchecked a box

// add OK and Cancel buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int which) {
        // user clicked OK
builder.setNegativeButton("Cancel", null);

// create and show the alert dialog
AlertDialog dialog = builder.create();;

Here I hard coded the the which items in the list were already checked. It is more likely that you would want to keep track of them in an ArrayList<Integer>. See the documentation example for more details. You can also set the checked items to null if you always want everything to start unchecked.

Kotlin version

// setup the alert builder
val builder = AlertDialog.Builder(context)
builder.setTitle("Choose some animals")

// add a checkbox list
val animals = arrayOf("horse", "cow", "camel", "sheep", "goat")
val checkedItems = booleanArrayOf(true, false, false, true, false)
builder.setMultiChoiceItems(animals, checkedItems) { dialog, which, isChecked ->
    // user checked or unchecked a box

// add OK and Cancel buttons
builder.setPositiveButton("OK") { dialog, which ->
    // user clicked OK
builder.setNegativeButton("Cancel", null)

// create and show the alert dialog
val dialog = builder.create()


  • For the context in the code above, don't use getApplicationContext() or you will get an IllegalStateException (see here for why). Instead, get a reference to the activity context, such as with this.
  • You can also populate the list items from a database or another source using setAdapter or setCursor or passing in a Cursor or ListAdapter into the setSingleChoiceItems or setMultiChoiceItems.
  • If the list is longer than will fit on the screen then the dialog will automatically scroll it. If you have a really long list, though, I'm guessing that you should probably make a custom dialog with a RecyclerView.
  • To test all of the examples above I just had a simple project with a single button than showed the dialog when clicked:

    public class MainActivity extends AppCompatActivity {
        Context context;
        protected void onCreate(Bundle savedInstanceState) {
            context = this;
        public void showAlertDialogButtonClicked(View view) {
            // example code to create alert dialog lists goes here


how to release localhost from Error: listen EADDRINUSE

In window, please execute this command:

taskkill /F /PID 1952

Is there a difference between PhoneGap and Cordova commands?

I have also noticed that cordova has a "serve" command that Phonegap doesn't. This command launches a local server on port 8000. This is handy for running your app in Chrome and using the Ripple emulator.

How to activate virtualenv?

Windows 10

In Windows these directories are created :

Windows 10 Virtual Environment directories

To activate Virtual Environment in Windows 10.


\scripts directory contain activate file.

Linux Ubuntu

In Ubuntu these directories are created :

Linux Ubuntu Virtual Environment directories

To activate Virtual Environment in Linux Ubuntu.

source ./bin/activate

/bin directory contain activate file.

Virtual Environment copied from Windows to Linux Ubuntu vice versa

If Virtual environment folder copied from Windows to Linux Ubuntu then according to directories:

source ./down/Scripts/activate

jsonify a SQLAlchemy result set in Flask

It's been a lot of times and there are lots of valid answers, but the following code block seems to work:

my_object = SqlAlchemyModel()
my_serializable_obj = my_object.__dict__
del my_serializable_obj["_sa_instance_state"]

I'm aware that this is not a perfect solution, nor as elegant as the others, however for those who want o quick fix, they might try this.

How to measure time taken by a function to execute

As previously stated check for and use built in timer. But if you want or need to write your own here is my two cents:

 * JavaScript Timer Object
 *      var now=timer['elapsed'](); 
 *      timer['stop']();
 *      timer['start']();
 *      timer['reset']();
 * @expose
 * @method timer
 * @return {number}
        /** @expose */
        reset:function(){return a=0}

//=-=|Google Advanced Optimized|=-=//
timer=function(){var;b=0;return{a:function(){return},start:function(){return},stop:function(){return},reset:function(){return a=0}}}();

Compilation was a success!

  • Original Size: 219 bytes gzipped (405 bytes uncompressed)
  • Compiled Size: 109 bytes gzipped (187 bytes uncompressed)
  • Saved 50.23% off the gzipped size (53.83% without gzip

Cross Domain Form POSTing

Same origin policy has nothing to do with sending request to another url (different protocol or domain or port).

It is all about restricting access to (reading) response data from another url. So JavaScript code within a page can post to arbitrary domain or submit forms within that page to anywhere (unless the form is in an iframe with different url).

But what makes these POST requests inefficient is that these requests lack antiforgery tokens, so are ignored by the other url. Moreover, if the JavaScript tries to get that security tokens, by sending AJAX request to the victim url, it is prevented to access that data by Same Origin Policy.

A good example: here

And a good documentation from Mozilla: here

HowTo Generate List of SQL Server Jobs and their owners

There is an easy way to get Jobs' Owners info from multiple instances by PowerShell:

Run the script in your PowerShell ISE:

Loads SQL Powerhell SMO and commands:

Import-Module SQLPS -disablenamechecking

BUild list of Servers manually (this builds an array list):

$SysAdmins = $null;
foreach($SQLSvr in $SQLServers)
    ## - Add Code block:
    $MySQL = new-object Microsoft.SqlServer.Management.Smo.Server $SQLSvr;
    ## - End of Code block

Changing CSS Values with Javascript

I don't know why the other solutions go through the whole list of stylesheets for the document. Doing so creates a new entry in each stylesheet, which is inefficient. Instead, we can simply append a new stylesheet and simply add our desired CSS rules there.

function css(selector,property,value)
    try{ stylesheet.insertRule(selector+' {'+property+':'+value+'}',stylesheet.cssRules.length); }

Note that we can override even inline styles set directly on elements by adding " !important" to the value of the property, unless there already exist more specific "!important" style declarations for that property.

Python Brute Force algorithm

If you REALLY want to brute force it, try this, but it will take you a ridiculous amount of time:

your_list = 'abcdefghijklmnopqrstuvwxyz'
complete_list = []
for current in xrange(10):
    a = [i for i in your_list]
    for y in xrange(current):
        a = [x+i for i in your_list for x in a]
    complete_list = complete_list+a

On a smaller example, where list = 'ab' and we only go up to 5, this prints the following:

['a', 'b', 'aa', 'ba', 'ab', 'bb', 'aaa', 'baa', 'aba', 'bba', 'aab', 'bab', 'abb', 'bbb', 'aaaa', 'baaa', 'abaa', 'bbaa', 'aaba', 'baba', 'abba', 'bbba', 'aaab', 'baab', 'abab', 'bbab', 'aabb', 'babb', 'abbb', 'bbbb', 'aaaaa', 'baaaa', 'abaaa', 'bbaaa', 'aabaa', 'babaa', 'abbaa', 'bbbaa', 'aaaba','baaba', 'ababa', 'bbaba', 'aabba', 'babba', 'abbba', 'bbbba', 'aaaab', 'baaab', 'abaab', 'bbaab', 'aabab', 'babab', 'abbab', 'bbbab', 'aaabb', 'baabb', 'ababb', 'bbabb', 'aabbb', 'babbb', 'abbbb', 'bbbbb']

Import CSV to mysql table

As others have mentioned, the load data local infile works just fine. I tried the php script that Hawkee posted, but didnt work for me. Rather than debug it, here's what i did:

1) copy/paste the header row of the CSV file into a txt file and edit with emacs. add a comma and CR between each field to get each on on it's own line.
2) Save that file as FieldList.txt
3) edit the file to include defns for each field (most were varchar, but quite a few were int(x). Add create table tablename ( to the beginning of the file and ) to the end of the file. Save it as CreateTable.sql
4) start mysql client with input from the Createtable.sql file to create the table
5) start mysql client, copy/paste in most of the 'LOAD DATA INFILE' command subsituting my table name and csv file name. Paste in the FieldList.txt file. Be sure to include the 'IGNORE 1 LINES' before pasting in the field list

Sounds like a lot of work, but easy with emacs.....

jQuery add class .active on menu

    let path = window.location.href;
    $('#nav li a').each(function() {
        if (this.href === path) {

Can't open and lock privilege tables: Table 'mysql.user' doesn't exist

As suggested above, i had similar issue with mysql-5.7.18,
i did this in this way

1. Executed this command from "MYSQL_HOME\bin\mysqld.exe --initialize-insecure"
2. then started "MYSQL_HOME\bin\mysqld.exe"
3. Connect workbench to this localhost:3306 with username 'root'
4. then executed this query "SET PASSWORD FOR 'root'@'localhost' = 'root';"

password was also updated successfully.

How can I reference a commit in an issue comment on GitHub?

Answer above is missing an example which might not be obvious (it wasn't to me).

Url could be broken down into parts
                  \_____/\________/       \_______________________________________/
                   |        |                              |
            Account name    |                      Hash of revision
                        Project name              

Hash can be found here (you can click it and will get the url from browser).

enter image description here

Hope this saves you some time.

EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType

For those who use ASP.NET Identity 2.1 and have changed the primary key from the default string to either int or Guid, if you're still getting

EntityType 'xxxxUserLogin' has no key defined. Define the key for this EntityType.

EntityType 'xxxxUserRole' has no key defined. Define the key for this EntityType.

you probably just forgot to specify the new key type on IdentityDbContext:

public class AppIdentityDbContext : IdentityDbContext<
    AppUser, AppRole, int, AppUserLogin, AppUserRole, AppUserClaim>
    public AppIdentityDbContext()
        : base("MY_CONNECTION_STRING")

If you just have

public class AppIdentityDbContext : IdentityDbContext

or even

public class AppIdentityDbContext : IdentityDbContext<AppUser>

you will get that 'no key defined' error when you are trying to add migrations or update the database.

Is there a Python Library that contains a list of all the ascii characters?

ASCII defines 128 characters whose byte values range from 0 to 127 inclusive. So to get a string of all the ASCII characters, you could just do

''.join([chr(i) for i in range(128)])

Only some of those are printable, however- the printable ASCII characters can be accessed in Python via

import string

Getting files by creation date in .NET

this could work for you.

using System.Linq;

DirectoryInfo info = new DirectoryInfo("PATH_TO_DIRECTORY_HERE");
FileInfo[] files = info.GetFiles().OrderBy(p => p.CreationTime).ToArray();
foreach (FileInfo file in files)
    // DO Something...

Text border using css (border around text)

text-shadow: -1px 0 black, 0 1px black, 1px 0 black, 0 -1px black;

Double quotes within php script echo

You need to escape ", so it won't be interpreted as end of string. Use \ to escape it:

echo "<script>$('#edit_errors').html('<h3><em><font color=\"red\">Please Correct Errors Before Proceeding</font></em></h3>')</script>";

Read more: strings and escape sequences

javascript if number greater than number

You should convert them to number before compare.


if (+x > +y) {


if (Number(x) > Number(y)) {
  // ...

Note: parseFloat and pareseInt(for compare integer, and you need to specify the radix) will give you NaN for an empty string, compare with NaN will always be false, If you don't want to treat empty string be 0, then you could use them.

django: TypeError: 'tuple' object is not callable

There is comma missing in your tuple.

insert the comma between the tuples as shown:

pack_size = (('1', '1'),('3', '3'),(b, b),(h, h),(d, d), (e, e),(r, r))

Do the same for all

mysql error 2005 - Unknown MySQL server host 'localhost'(11001)

The case is like :

 mysql connects will localhost when network is not up.
 mysql cannot connect when network is up.

You can try the following steps to diagnose and resolve the issue (my guess is that some other service is blocking port on which mysql is hosted):

  1. Disconnect the network.
  2. Stop mysql service (if windows, try from services.msc window)
  3. Connect to network.
  4. Try to start the mysql and see if it starts correctly.
  5. Check for system logs anyways to be sure that there is no error in starting mysql service.
  6. If all goes well try connecting.
  7. If fails, try to do a telnet localhost 3306 and see what output it shows.
  8. Try changing the port on which mysql is hosted, default 3306, you can change to some other port which is ununsed.

This should ideally resolve the issue you are facing.

Show space, tab, CRLF characters in editor of Visual Studio

The correct shortcut is CTRL-R-W like you don't have to release CTRL button while pressing W. This worked for me in VS 2015

For homebrew mysql installs, where's my.cnf?

One way to find out:

sudo /usr/libexec/locate.updatedb
# wait a few minutes for it to finish
locate my.cnf

How to save all console output to file in R?

  1. If you want to get error messages saved in a file

    zz <- file("Errors.txt", open="wt")
    sink(zz, type="message")

    the output will be:

    Error in print(errr) : object 'errr' not found
    Execution halted

    This output will be saved in a file named Errors.txt

  2. In case, you want printed values of console to a file you can use 'split' argument:

    zz <- file("console.txt", open="wt")
    sink(zz,  split=TRUE)

    output will be:

    [1] "cool"

    in console.txt file. So all your console output will be printed in a file named console.txt

The HTTP request is unauthorized with client authentication scheme 'Negotiate'. The authentication header received from the server was 'NTLM'

THE ANSWER: The problem was all of the posts for such an issue were related to older kerberos and IIS issues where proxy credentials or AllowNTLM properties were helping. My case was different. What I have discovered after hours of picking worms from the ground was that somewhat IIS installation did not include Negotiate provider under IIS Windows authentication providers list. So I had to add it and move up. My WCF service started to authenticate as expected. Here is the screenshot how it should look if you are using Windows authentication with Anonymous auth OFF.

You need to right click on Windows authentication and choose providers menu item.

enter image description here

Hope this helps to save some time.

Color text in terminal applications in UNIX

Different solution that I find more elegant

Here's another way to do it. Some people will prefer this as the code is a bit cleaner. There are no %s and a RESET color to end the coloration.

#include <stdio.h>

#define RED   "\x1B[31m"
#define GRN   "\x1B[32m"
#define YEL   "\x1B[33m"
#define BLU   "\x1B[34m"
#define MAG   "\x1B[35m"
#define CYN   "\x1B[36m"
#define WHT   "\x1B[37m"
#define RESET "\x1B[0m"

int main() {
  printf(RED "red\n"     RESET);
  printf(GRN "green\n"   RESET);
  printf(YEL "yellow\n"  RESET);
  printf(BLU "blue\n"    RESET);
  printf(MAG "magenta\n" RESET);
  printf(CYN "cyan\n"    RESET);
  printf(WHT "white\n"   RESET);

  return 0;

This program gives the following output:

enter image description here

Simple example with multiple colors

This way, it's easy to do something like:

printf("This is " RED "red" RESET " and this is " BLU "blue" RESET "\n");

This line produces the following output:

execution's output

How to find out what is locking my tables?

I have a stored procedure that I have put together, that deals not only with locks and blocking, but also to see what is running in a server. I have put it in master. I will share it with you, the code is below:

USE [master]

CREATE PROCEDURE [dbo].[sp_radhe] 



-- the current_processes
-- marcelo miorelli 
-- CCHQ 
-- 04 MAR 2013 Wednesday

SELECT es.session_id AS session_id
,COALESCE(es.original_login_name, '') AS login_name
,COALESCE(es.host_name,'') AS hostname
,COALESCE(es.last_request_end_time,es.last_request_start_time) AS last_batch
,COALESCE(er.blocking_session_id,0) AS blocked_by
,COALESCE(er.wait_type,'MISCELLANEOUS') AS waittype
,COALESCE(er.wait_time,0) AS waittime
,COALESCE(er.last_wait_type,'MISCELLANEOUS') AS lastwaittype
,COALESCE(er.wait_resource,'') AS waitresource
,coalesce(db_name(er.database_id),'No Info') as dbid
,transaction_isolation =
CASE es.transaction_isolation_level
    WHEN 0 THEN 'Unspecified'
    WHEN 1 THEN 'Read Uncommitted'
    WHEN 2 THEN 'Read Committed'
    WHEN 3 THEN 'Repeatable'
    WHEN 4 THEN 'Serializable'
    WHEN 5 THEN 'Snapshot'
    + COALESCE(er.cpu_time,0) AS cpu
    + COALESCE(es.writes,0) 
    + COALESCE(er.reads,0) 
+ COALESCE(er.writes,0) AS physical_io
,COALESCE(er.open_transaction_count,-1) AS open_tran
,COALESCE(es.program_name,'') AS program_name
FROM sys.dm_exec_sessions es
LEFT OUTER JOIN sys.dm_exec_connections ec ON es.session_id = ec.session_id
LEFT OUTER JOIN sys.dm_exec_requests er ON es.session_id = er.session_id
LEFT OUTER JOIN sys.server_principals sp ON es.security_id = sp.sid
LEFT OUTER JOIN sys.dm_os_tasks ota ON es.session_id = ota.session_id
LEFT OUTER JOIN sys.dm_os_threads oth ON ota.worker_address = oth.worker_address
CROSS APPLY sys.dm_exec_sql_text(er.sql_handle) AS st
where es.is_user_process = 1 
  and es.session_id <> @@spid
  and es.status = 'running'
ORDER BY es.session_id



this procedure has done very good for me in the last couple of years. to run it just type sp_radhe

Regarding putting sp_radhe in the master database

I use the following code and make it a system stored procedure

exec sys.sp_MS_marksystemobject 'sp_radhe'

as you can see on the link below

Creating Your Own SQL Server System Stored Procedures

Regarding the transaction isolation level

Questions About T-SQL Transaction Isolation Levels You Were Too Shy to Ask

Jonathan Kehayias

Once you change the transaction isolation level it only changes when the scope exits at the end of the procedure or a return call, or if you change it explicitly again using SET TRANSACTION ISOLATION LEVEL.

In addition the TRANSACTION ISOLATION LEVEL is only scoped to the stored procedure, so you can have multiple nested stored procedures that execute at their own specific isolation levels.

Failed to install *.apk on device 'emulator-5554': EOF

you could try this:

   1. Open the "Android Virtual device Manager"
   2. Select from one the listed devices there and run it.
   3. Right click your Android App -> Run As -> Android Application

It worked for me. I tried this on an emulator in eclipse. It takes a while before the app is run. For me it took 33 seconds. Wait until the message in the console says "Success!"

Change all files and folders permissions of a directory to 644/755

On they write:

If you need a quick way to reset your public_html data to 755 for directories and 644 for files, then you can use something like this:

cd /home/user/domains/
find . -type d -exec chmod 0755 {} \;
find . -type f -exec chmod 0644 {} \;

I tested and ... it works!

Including non-Python files with

create in the project root with recursive-include to the required directory or include with the file name.

include LICENSE
include README.rst
recursive-include package/static *
recursive-include package/templates *

documentation can be found here

How to pip or easy_install tkinter on Windows

I'm posting as the top answer requotes the documentation which I didn't find useful.

tkinter comes packaged with python install on windows IFF you select it during the install window.

The solution is to repair the installation (via uninstall GUI is fine), and select to install tk this time. You may need to point at or redownload the binary in this process. Downloading directly from activestate did not work for me.

This is a common problem people have on windows as it's easy to not want to install TCL/TK if you don't know what it is, but Matplotlib etc require it.

Calling a Sub in VBA

Try -

Call CatSubProduktAreakum(Stattyp, Daty + UBound(SubCategories) + 2)

As for the reason, this from MSDN via this question - What does the Call keyword do in VB6?

You are not required to use the Call keyword when calling a procedure. However, if you use the Call keyword to call a procedure that requires arguments, argumentlist must be enclosed in parentheses. If you omit the Call keyword, you also must omit the parentheses around argumentlist. If you use either Call syntax to call any intrinsic or user-defined function, the function's return value is discarded.

Reading/parsing Excel (xls) files with Python

You might also consider running the (non-python) program xls2csv. Feed it an xls file, and you should get back a csv.

jQuery get the name of a select option

For anyone who comes across this late, like me.

As others have stated, name isn't a valid attribute of an option element. Combining the accepted answer above with the answer from this other question, you get:


Android SeekBar setOnSeekBarChangeListener

Override all methods

    public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {


    public void onStartTrackingTouch(SeekBar arg0) {


    public void onStopTrackingTouch(SeekBar arg0) {


Updating the list view when the adapter data changes




((BaseAdapter) mMyListView.getAdapter()).notifyDataSetChanged(); 

If that doesnt work, refer to this thread: Android List view refresh

How to set the min and max height or width of a Frame?

There is no single magic function to force a frame to a minimum or fixed size. However, you can certainly force the size of a frame by giving the frame a width and height. You then have to do potentially two more things: when you put this window in a container you need to make sure the geometry manager doesn't shrink or expand the window. Two, if the frame is a container for other widget, turn grid or pack propagation off so that the frame doesn't shrink or expand to fit its own contents.

Note, however, that this won't prevent you from resizing a window to be smaller than an internal frame. In that case the frame will just be clipped.

import Tkinter as tk

root = tk.Tk()
frame1 = tk.Frame(root, width=100, height=100, background="bisque")
frame2 = tk.Frame(root, width=50, height = 50, background="#b22222")

frame1.pack(fill=None, expand=False), rely=.5, anchor="c")


How to access the elements of a 2D array?

If you have this :

a = [[1, 1], [2, 1],[3, 1]]

You can easily access this by using :

a[0][1] = 7

Splitting a dataframe string column into multiple different columns

We could use tidyr::extract()

x <- c("F.US.CLE.V13", "F.US.CA6.U13", "F.US.CA6.U13", "F.US.CA6.U13", 
  "F.US.CA6.U13", "F.US.CA6.U13", "F.US.CA6.U13", "F.US.CA6.U13", 
  "F.US.DL.U13", "F.US.DL.U13", "F.US.DL.U13", "F.US.DL.Z13", "F.US.DL.Z13"

extract(tibble(data=x),"data", regex = "^(.*?)\\.(.*?)\\.(.*?)\\.(.*?)$",into = LETTERS[1:4])
#> # A tibble: 13 x 4
#>    A     B     C     D    
#>    <chr> <chr> <chr> <chr>
#>  1 F     US    CLE   V13  
#>  2 F     US    CA6   U13  
#>  3 F     US    CA6   U13  
#>  4 F     US    CA6   U13  
#>  5 F     US    CA6   U13  
#>  6 F     US    CA6   U13  
#>  7 F     US    CA6   U13  
#>  8 F     US    CA6   U13  
#>  9 F     US    DL    U13  
#> 10 F     US    DL    U13  
#> 11 F     US    DL    U13  
#> 12 F     US    DL    Z13  
#> 13 F     US    DL    Z13

Another option is to use unglue::unglue_data()

# remotes::install_github("moodymudskipper/unglue")
#>    A  B   C   D
#> 1  F US CLE V13
#> 2  F US CA6 U13
#> 3  F US CA6 U13
#> 4  F US CA6 U13
#> 5  F US CA6 U13
#> 6  F US CA6 U13
#> 7  F US CA6 U13
#> 8  F US CA6 U13
#> 9  F US  DL U13
#> 10 F US  DL U13
#> 11 F US  DL U13
#> 12 F US  DL Z13
#> 13 F US  DL Z13

Created on 2019-09-14 by the reprex package (v0.3.0)

Combining (concatenating) date and time into a datetime

dealing with dates, dateadd must be used for precision

declare @a DATE = getdate()
declare @b time(7) = getdate()
select @b, @A, GETDATE(), DATEADD(day, DATEDIFF(day, 0, @a), cast(@b as datetime2(0)))

What is the best way to clone/deep copy a .NET generic Dictionary<string, T>?

This works fine for me

 // assuming this fills the List
 List<Dictionary<string, string>> obj = this.getData(); 

 List<Dictionary<string, string>> objCopy = new List<Dictionary<string, string>>(obj);

As Tomer Wolberg describes in the comments, this does not work if the value type is a mutable class.

How do I convert Int/Decimal to float in C#?

The same as an int:

float f = 6;

Also here's how to programmatically convert from an int to a float, and a single in C# is the same as a float:

int i = 8;
float f = Convert.ToSingle(i);

Or you can just cast an int to a float:

float f = (float)i;

How to create an empty array in Swift?

As per Swift 5

    // An array of 'Int' elements
    let oddNumbers = [1, 3, 5, 7, 9, 11, 13, 15]

    // An array of 'String' elements
    let streets = ["Albemarle", "Brandywine", "Chesapeake"]

    // Shortened forms are preferred
    var emptyDoubles: [Double] = []

    // The full type name is also allowed
    var emptyFloats: Array<Float> = Array()

What is the difference between HTTP and REST?

REST is not necessarily tied to HTTP. RESTful web services are just web services that follow a RESTful architecture.

What is Rest -
1- Client-server
2- Stateless
3- Cacheable
4- Layered system
5- Code on demand
6- Uniform interface

Git Cherry-Pick and Conflicts

Before proceeding:

  • Install a proper mergetool. On Linux, I strongly suggest you to use meld:

    sudo apt-get install meld
  • Configure your mergetool:

    git config --global merge.tool meld

Then, iterate in the following way:

git cherry-pick ....
git mergetool
git cherry-pick --continue

How to combine GROUP BY and ROW_NUMBER?

The deduplication (to select the max T1) and the aggregation need to be done as distinct steps. I've used a CTE since I think this makes it clearer:

    SELECT  Rel.t2ID, SUM(Price) price
    FROM    @t1         AS T1
    JOIN    @relation   AS Rel 
    ON      Rel.t1ID=T1.ID
    BY      Rel.t2ID
    SELECT  Rel.t2ID, Rel.t1ID, 
            ROW_NUMBER()OVER(Partition By Rel.t2ID Order By Price DESC)As PriceList
    FROM    @t1         AS T1
    JOIN    @relation   AS Rel 
    ON      Rel.t1ID=T1.ID
,T2.Name as T2Name
,T1.Name As T1Name
FROM    @t2 AS T2
JOIN    sumCTE AS sumT1
ON      sumT1.t2ID = t2.ID
JOIN    maxCTE AS maxT1
ON      maxT1.t2ID = t2.ID
JOIN    @t1 AS T1
ON      T1.ID = maxT1.t1ID
WHERE   maxT1.PriceList = 1

Convert comma separated string of ints to int array

I have found a simple solution which worked for me.


Passing a method as a parameter in Ruby

you also can use "eval", and pass the method as a string argument, and then simply eval it in the other method.

source of historical stock data

A data set of every symbol on the NASDAQ and NYSE on a second or minute interval is going to be massive.

Let's say there are a total of 4000 companies listed on both exchanges (this is probably on the very low side since there are over 3200 companies listed on the NASDAQ). For data at a second interval, assuming there are 6.5 trading hours in a day, that would give you 23400 data points per day per company, or about 93,600,000 data points in total for that one day. Assuming 200 trading days in a year, thats about 18,720,000,000 data points for just one year.

Maybe you want to start with a smaller set first?

How to add `style=display:"block"` to an element using jQuery?

Depending on the purpose of setting the display property, you might want to take a look at




How to do a FULL OUTER JOIN in MySQL?

The answer that Pablo Santa Cruz gave is correct; however, in case anybody stumbled on this page and wants more clarification, here is a detailed breakdown.

Example Tables

Suppose we have the following tables:

-- t1
id  name
1   Tim
2   Marta

-- t2
id  name
1   Tim
3   Katarina

Inner Joins

An inner join, like this:

FROM `t1`
INNER JOIN `t2` ON `t1`.`id` = `t2`.`id`;

Would get us only records that appear in both tables, like this:

1 Tim  1 Tim

Inner joins don't have a direction (like left or right) because they are explicitly bidirectional - we require a match on both sides.

Outer Joins

Outer joins, on the other hand, are for finding records that may not have a match in the other table. As such, you have to specify which side of the join is allowed to have a missing record.

LEFT JOIN and RIGHT JOIN are shorthand for LEFT OUTER JOIN and RIGHT OUTER JOIN; I will use their full names below to reinforce the concept of outer joins vs inner joins.

Left Outer Join

A left outer join, like this:

FROM `t1`
LEFT OUTER JOIN `t2` ON `t1`.`id` = `t2`.`id`;

...would get us all the records from the left table regardless of whether or not they have a match in the right table, like this:

1 Tim   1    Tim

Right Outer Join

A right outer join, like this:

FROM `t1`
RIGHT OUTER JOIN `t2` ON `t1`.`id` = `t2`.`id`;

...would get us all the records from the right table regardless of whether or not they have a match in the left table, like this:

1    Tim   1  Tim
NULL NULL  3  Katarina

Full Outer Join

A full outer join would give us all records from both tables, whether or not they have a match in the other table, with NULLs on both sides where there is no match. The result would look like this:

1    Tim   1    Tim
2    Marta NULL NULL
NULL NULL  3    Katarina

However, as Pablo Santa Cruz pointed out, MySQL doesn't support this. We can emulate it by doing a UNION of a left join and a right join, like this:

FROM `t1`
LEFT OUTER JOIN `t2` ON `t1`.`id` = `t2`.`id`


FROM `t1`
RIGHT OUTER JOIN `t2` ON `t1`.`id` = `t2`.`id`;

You can think of a UNION as meaning "run both of these queries, then stack the results on top of each other"; some of the rows will come from the first query and some from the second.

It should be noted that a UNION in MySQL will eliminate exact duplicates: Tim would appear in both of the queries here, but the result of the UNION only lists him once. My database guru colleague feels that this behavior should not be relied upon. So to be more explicit about it, we could add a WHERE clause to the second query:

FROM `t1`
LEFT OUTER JOIN `t2` ON `t1`.`id` = `t2`.`id`


FROM `t1`
RIGHT OUTER JOIN `t2` ON `t1`.`id` = `t2`.`id`
WHERE `t1`.`id` IS NULL;

On the other hand, if you wanted to see duplicates for some reason, you could use UNION ALL.

Finding even or odd ID values

dividend % divisor

Dividend is the numeric expression to divide. Dividend must be any expression of integer data type in sql server.

Divisor is the numeric expression to divide the dividend. Divisor must be expression of integer data type except in sql server.

SELECT 15 % 2


Dividend = 15

Divisor = 2

Let's say you wanted to query

Query a list of CITY names from STATION with even ID numbers only.

Schema structure for STATION:

ID Number

CITY varchar

STATE varchar

select CITY from STATION as st where % 2 = 0

Will fetch the even set of records 

In order to fetch the odd records with Id as odd number.

select CITY from STATION as st where % 2 <> 0

% function reduces the value to either 0 or 1

elasticsearch bool query combine must with OR

$filterQuery = $this->queryFactory->create(QueryInterface::TYPE_BOOL, ['must' => $queries,'should'=>$queriesGeo]);

In must you need to add the query condition array which you want to work with AND and in should you need to add the query condition which you want to work with OR.

You can check this:

Where value in column containing comma delimited values

I found this answer on another forum, works perfect. No problems with finding 1 if there is also a 10

WHERE tablename REGEXP "(^|,)@search(,|$)"

I found it here

align divs to the bottom of their container

You can cheat! Say your div is 20px high, place the div at the top of the next container and set

position: absolute;
top: -20px;

It may not be semantically clean but does scale with responsive designs

LaTex left arrow over letter in math mode

Use \overleftarrow to create a long arrow to the left.


LaTeX output

create array from mysql query php

$type_array = array();    
while($row = mysql_fetch_assoc($result)) {
    $type_array[] = $row['type'];

Generate a dummy-variable

This one liner in base R

model.matrix( ~ iris$Species - 1)


    iris$Speciessetosa iris$Speciesversicolor iris$Speciesvirginica
1                    1                      0                     0
2                    1                      0                     0
3                    1                      0                     0
4                    1                      0                     0
5                    1                      0                     0
6                    1                      0                     0
7                    1                      0                     0
8                    1                      0                     0
9                    1                      0                     0
10                   1                      0                     0
11                   1                      0                     0
12                   1                      0                     0
13                   1                      0                     0
14                   1                      0                     0
15                   1                      0                     0
16                   1                      0                     0
17                   1                      0                     0
18                   1                      0                     0
19                   1                      0                     0
20                   1                      0                     0
21                   1                      0                     0
22                   1                      0                     0
23                   1                      0                     0
24                   1                      0                     0
25                   1                      0                     0
26                   1                      0                     0
27                   1                      0                     0
28                   1                      0                     0
29                   1                      0                     0
30                   1                      0                     0
31                   1                      0                     0
32                   1                      0                     0
33                   1                      0                     0
34                   1                      0                     0
35                   1                      0                     0
36                   1                      0                     0
37                   1                      0                     0
38                   1                      0                     0
39                   1                      0                     0
40                   1                      0                     0
41                   1                      0                     0
42                   1                      0                     0
43                   1                      0                     0
44                   1                      0                     0
45                   1                      0                     0
46                   1                      0                     0
47                   1                      0                     0
48                   1                      0                     0
49                   1                      0                     0
50                   1                      0                     0
51                   0                      1                     0
52                   0                      1                     0
53                   0                      1                     0
54                   0                      1                     0
55                   0                      1                     0
56                   0                      1                     0
57                   0                      1                     0
58                   0                      1                     0
59                   0                      1                     0
60                   0                      1                     0
61                   0                      1                     0
62                   0                      1                     0
63                   0                      1                     0
64                   0                      1                     0
65                   0                      1                     0
66                   0                      1                     0
67                   0                      1                     0
68                   0                      1                     0
69                   0                      1                     0
70                   0                      1                     0
71                   0                      1                     0
72                   0                      1                     0
73                   0                      1                     0
74                   0                      1                     0
75                   0                      1                     0
76                   0                      1                     0
77                   0                      1                     0
78                   0                      1                     0
79                   0                      1                     0
80                   0                      1                     0
81                   0                      1                     0
82                   0                      1                     0
83                   0                      1                     0
84                   0                      1                     0
85                   0                      1                     0
86                   0                      1                     0
87                   0                      1                     0
88                   0                      1                     0
89                   0                      1                     0
90                   0                      1                     0
91                   0                      1                     0
92                   0                      1                     0
93                   0                      1                     0
94                   0                      1                     0
95                   0                      1                     0
96                   0                      1                     0
97                   0                      1                     0
98                   0                      1                     0
99                   0                      1                     0
100                  0                      1                     0
101                  0                      0                     1
102                  0                      0                     1
103                  0                      0                     1
104                  0                      0                     1
105                  0                      0                     1
106                  0                      0                     1
107                  0                      0                     1
108                  0                      0                     1
109                  0                      0                     1
110                  0                      0                     1
111                  0                      0                     1
112                  0                      0                     1
113                  0                      0                     1
114                  0                      0                     1
115                  0                      0                     1
116                  0                      0                     1
117                  0                      0                     1
118                  0                      0                     1
119                  0                      0                     1
120                  0                      0                     1
121                  0                      0                     1
122                  0                      0                     1
123                  0                      0                     1
124                  0                      0                     1
125                  0                      0                     1
126                  0                      0                     1
127                  0                      0                     1
128                  0                      0                     1
129                  0                      0                     1
130                  0                      0                     1
131                  0                      0                     1
132                  0                      0                     1
133                  0                      0                     1
134                  0                      0                     1
135                  0                      0                     1
136                  0                      0                     1
137                  0                      0                     1
138                  0                      0                     1
139                  0                      0                     1
140                  0                      0                     1
141                  0                      0                     1
142                  0                      0                     1
143                  0                      0                     1
144                  0                      0                     1
145                  0                      0                     1
146                  0                      0                     1
147                  0                      0                     1
148                  0                      0                     1
149                  0                      0                     1
150                  0                      0                     1

Is it possible to get a history of queries made in postgres

If The question is the see the history of queries executed in the Command line. Answer is

As per Postgresql 9.3, Try \? in your command line, you will find all possible commands, in that search for history,

  \s [FILE]              display history or save it to file

in your command line, try \s. This will list the history of queries, you have executed in the current session. you can also save to the file, as shown below.

hms=# \s /tmp/save_queries.sql
Wrote history to file ".//tmp/save_queries.sql".

How to get current language code with Swift?

Locale.current.languageCode returns me wrong code, so I use these extensions:

extension Locale {
    static var preferredLanguageCode: String {
        let defaultLanguage = "en"
        let preferredLanguage = preferredLanguages.first ?? defaultLanguage
        return Locale(identifier: preferredLanguage).languageCode ?? defaultLanguage

    static var preferredLanguageCodes: [String] {
        return Locale.preferredLanguages.compactMap({Locale(identifier: $0).languageCode})

Java - creating a new thread

There are several ways to create a thread

  1. by extending Thread class >5
  2. by implementing Runnable interface - > 5
  3. by using ExecutorService inteface - >=8

How to move an element into another element?

If the div where you want to put your element has content inside, and you want the element to show after the main content:


If the div where you want to put your element has content inside, and you want to show the element before the main content:


If the div where you want to put your element is empty, or you want to replace it entirely:

$("#element").html('<div id="source">...</div>');

If you want to duplicate an element before any of the above:

// etc.

cd into directory without having permission

chmod +x openfire worked for me. It adds execution permission to the openfire folder.

How to set timeout in Retrofit library?

These answers were outdated for me, so here's how it worked out.

Add OkHttp, in my case the version is 3.3.1:

compile 'com.squareup.okhttp3:okhttp:3.3.1'

Then before building your Retrofit, do this:

OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
    .connectTimeout(60, TimeUnit.SECONDS)
    .readTimeout(60, TimeUnit.SECONDS)
    .writeTimeout(60, TimeUnit.SECONDS)
return new Retrofit.Builder()

What is the default lifetime of a session?

Check out php.ini the value set for session.gc_maxlifetime is the ID lifetime in seconds.

I believe the default is 1440 seconds (24 mins)

Edit: As some comments point out, the above is not entirely accurate. A wonderful explanation of why, and how to implement session lifetimes is available here:

How do I expire a PHP session after 30 minutes?

Convert string into Date type on Python

>>> from datetime import datetime
>>> year, month, day = map(int, my_date.split('-'))
>>> date_object = datetime(year, month, day)

Non-recursive depth first search algorithm

Non-recursive DFS using ES6 generators

class Node {
  constructor(name, childNodes) { = name;
    this.childNodes = childNodes;
    this.visited = false;

function *dfs(s) {
  let stack = [];
  stackLoop: while (stack.length) {
    let u = stack[stack.length - 1]; // peek
    if (!u.visited) {
      u.visited = true; // grey - visited
      yield u;

    for (let v of u.childNodes) {
      if (!v.visited) {
        continue stackLoop;

    stack.pop(); // black - all reachable descendants were processed 

It deviates from typical non-recursive DFS to easily detect when all reachable descendants of given node were processed and to maintain the current path in the list/stack.

Why should we typedef a struct so often in C?

the name you (optionally) give the struct is called the tag name and, as has been noted, is not a type in itself. To get to the type requires the struct prefix.

GTK+ aside, I'm not sure the tagname is used anything like as commonly as a typedef to the struct type, so in C++ that is recognised and you can omit the struct keyword and use the tagname as the type name too:

    struct MyStruct
      int i;

    // The following is legal in C++:
    MyStruct obj;
    obj.i = 7;

Declaring variables inside or outside of a loop

I think the size of the object matters as well. In one of my projects, we had declared and initialized a large two dimensional array that was making the application throw an out-of-memory exception. We moved the declaration out of the loop instead and cleared the array at the start of every iteration.

How do I run Selenium in Xvfb?

open a terminal and run this command xhost +. This commands needs to be run every time you restart your machine. If everything works fine may be you can add this to startup commands

Also make sure in your /etc/environment file there is a line

export DISPLAY=:0.0 

And then, run your tests to see if your issue is resolved.

All please note the comment from sardathrion below before using this.

Why isn't Python very good for functional programming?

One thing that is really important for this question (and the answers) is the following: What the hell is functional programming, and what are the most important properties of it. I'll try to give my view of it:

Functional programming is a lot like writing math on a whiteboard. When you write equations on a whiteboard, you do not think about an execution order. There is (typically) no mutation. You don't come back the day after and look at it, and when you make the calculations again, you get a different result (or you may, if you've had some fresh coffee :)). Basically, what is on the board is there, and the answer was already there when you started writing things down, you just haven't realized what it is yet.

Functional programming is a lot like that; you don't change things, you just evaluate the equation (or in this case, "program") and figure out what the answer is. The program is still there, unmodified. The same with the data.

I would rank the following as the most important features of functional programming: a) referential transparency - if you evaluate the same statement at some other time and place, but with the same variable values, it will still mean the same. b) no side effect - no matter how long you stare at the whiteboard, the equation another guy is looking at at another whiteboard won't accidentally change. c) functions are values too. which can be passed around and applied with, or to, other variables. d) function composition, you can do h=g·f and thus define a new function h(..) which is equivalent to calling g(f(..)).

This list is in my prioritized order, so referential transparency is the most important, followed by no side effects.

Now, if you go through python and check how well the language and libraries supports, and guarantees, these aspects - then you are well on the way to answer your own question.

How do you get the length of a string?

The easiest way:


How can I make a checkbox readonly? not disabled?

Through CSS:

<label for="">
  <input type="checkbox" style="pointer-events: none; tabindex: -1;" checked> Label

pointer-events not supported in IE<10

Downloading video from YouTube

To all interested:

The "Coding for fun" book's chapter 4 "InnerTube: Download, Convert, and Sync YouTube Videos" deals with the topic. The code and discussion are at

[PLEASE BEWARE] While the overall concepts are valid some years after the publication, non-documented details of the youtube internals the project relies on can have changed (see the comment at the bottom of the page behind the second link).

GridView VS GridLayout in Android Apps

A GridView is a ViewGroup that displays items in two-dimensional scrolling grid. The items in the grid come from the ListAdapter associated with this view.

This is what you'd want to use (keep using). Because a GridView gets its data from a ListAdapter, the only data loaded in memory will be the one displayed on screen. GridViews, much like ListViews reuse and recycle their views for better performance.

Whereas a GridLayout is a layout that places its children in a rectangular grid.

It was introduced in API level 14, and was recently backported in the Support Library. Its main purpose is to solve alignment and performance problems in other layouts. Check out this tutorial if you want to learn more about GridLayout.

How to check if a variable is a dictionary in Python?

You could use if type(ele) is dict or use isinstance(ele, dict) which would work if you had subclassed dict:

d = {'abc': 'abc', 'def': {'ghi': 'ghi', 'jkl': 'jkl'}}
for element in d.values():
    if isinstance(element, dict):
       for k, v in element.items():
           print(k,' ',v)

Git reset --hard and push to remote repository

The whole git resetting business looked far to complicating for me.

So I did something along the lines to get my src folder in the state i had a few commits ago

# reset the local state
git reset <somecommit> --hard 
# copy the relevant part e.g. src (exclude is only needed if you specify .)
tar cvfz /tmp/current.tgz --exclude .git  src
# get the current state of git
git pull
# remove what you don't like anymore
rm -rf src
# restore from the tar file
tar xvfz /tmp/current.tgz
# commit everything back to git
git commit -a
# now you can properly push
git push

This way the state of affairs in the src is kept in a tar file and git is forced to accept this state without too much fiddling basically the src directory is replaced with the state it had several commits ago.

How can I find which tables reference a given table in Oracle SQL Developer?

Replace [Your TABLE] with emp in the query below

select owner,constraint_name,constraint_type,table_name,r_owner,r_constraint_name
  from all_constraints 
 where constraint_type='R'
   and r_constraint_name in (select constraint_name 
                               from all_constraints 
                              where constraint_type in ('P','U') 
                                and table_name='[YOUR TABLE]');

How to play video with AVPlayerViewController (AVKit) in Swift

Try This

var player:AVPlayer!
var avPlayerLayer:AVPlayerLayer = AVPlayerLayer(player: player)
avPlayerLayer.frame = CGRectMake(your frame)
self.view.layer .addSublayer(avPlayerLayer)
var steamingURL:NSURL = NSURL(string:playerURL)
player = AVPlayer(URL: steamingURL)

Unstage a deleted file in git

If it has been staged and committed, then the following will reset the file:

git reset COMMIT_HASH file_path
git checkout COMMIT_HASH file_path
git add file_path

This will work for a deletion that occurred several commits previous.