Programs & Examples On #Componentart

ComponentArt delivers User interface components, Developer tools for Visual Studio and .NET and also mobile BI dashboards for Windows, iOS and Android.

How to convert Json array to list of objects in c#

As others have already pointed out, the reason you are not getting the results you expect is because your JSON does not match the class structure that you are trying to deserialize into. You either need to change your JSON or change your classes. Since others have already shown how to change the JSON, I will take the opposite approach here.

To match the JSON you posted in your question, your classes should be defined like those below. Notice I've made the following changes:

  1. I added a Wrapper class corresponding to the outer object in your JSON.
  2. I changed the Values property of the ValueSet class from a List<Value> to a Dictionary<string, Value> since the values property in your JSON contains an object, not an array.
  3. I added some additional [JsonProperty] attributes to match the property names in your JSON objects.

Class definitions:

class Wrapper
    public ValueSet ValueSet { get; set; }

class ValueSet
    public string Id { get; set; }
    public Dictionary<string, Value> Values { get; set; }

class Value
    public string Id { get; set; }
    public string DisplayName { get; set; }

You need to deserialize into the Wrapper class, not the ValueSet class. You can then get the ValueSet from the Wrapper.

var valueSet = JsonConvert.DeserializeObject<Wrapper>(jsonString).ValueSet;

Here is a working program to demonstrate:

class Program
    static void Main(string[] args)
        string jsonString = @"
            ""JsonValues"": {
                ""id"": ""MyID"",
                ""values"": {
                    ""value1"": {
                        ""id"": ""100"",
                        ""diaplayName"": ""MyValue1""
                    ""value2"": {
                        ""id"": ""200"",
                        ""diaplayName"": ""MyValue2""

        var valueSet = JsonConvert.DeserializeObject<Wrapper>(jsonString).ValueSet;

        Console.WriteLine("id: " + valueSet.Id);
        foreach (KeyValuePair<string, Value> kvp in valueSet.Values)
            Console.WriteLine(kvp.Key + " id: " + kvp.Value.Id);
            Console.WriteLine(kvp.Key + " name: " + kvp.Value.DisplayName);

And here is the output:

id: MyID
value1 id: 100
value1 name: MyValue1
value2 id: 200
value2 name: MyValue2

A simple explanation of Naive Bayes Classification

I realize that this is an old question, with an established answer. The reason I'm posting is that is the accepted answer has many elements of k-NN (k-nearest neighbors), a different algorithm.

Both k-NN and NaiveBayes are classification algorithms. Conceptually, k-NN uses the idea of "nearness" to classify new entities. In k-NN 'nearness' is modeled with ideas such as Euclidean Distance or Cosine Distance. By contrast, in NaiveBayes, the concept of 'probability' is used to classify new entities.

Since the question is about Naive Bayes, here's how I'd describe the ideas and steps to someone. I'll try to do it with as few equations and in plain English as much as possible.

First, Conditional Probability & Bayes' Rule

Before someone can understand and appreciate the nuances of Naive Bayes', they need to know a couple of related concepts first, namely, the idea of Conditional Probability, and Bayes' Rule. (If you are familiar with these concepts, skip to the section titled Getting to Naive Bayes')

Conditional Probability in plain English: What is the probability that something will happen, given that something else has already happened.

Let's say that there is some Outcome O. And some Evidence E. From the way these probabilities are defined: The Probability of having both the Outcome O and Evidence E is: (Probability of O occurring) multiplied by the (Prob of E given that O happened)

One Example to understand Conditional Probability:

Let say we have a collection of US Senators. Senators could be Democrats or Republicans. They are also either male or female.

If we select one senator completely randomly, what is the probability that this person is a female Democrat? Conditional Probability can help us answer that.

Probability of (Democrat and Female Senator)= Prob(Senator is Democrat) multiplied by Conditional Probability of Being Female given that they are a Democrat.

  P(Democrat & Female) = P(Democrat) * P(Female | Democrat) 

We could compute the exact same thing, the reverse way:

  P(Democrat & Female) = P(Female) * P(Democrat | Female) 

Understanding Bayes Rule

Conceptually, this is a way to go from P(Evidence| Known Outcome) to P(Outcome|Known Evidence). Often, we know how frequently some particular evidence is observed, given a known outcome. We have to use this known fact to compute the reverse, to compute the chance of that outcome happening, given the evidence.

P(Outcome given that we know some Evidence) = P(Evidence given that we know the Outcome) times Prob(Outcome), scaled by the P(Evidence)

The classic example to understand Bayes' Rule:

Probability of Disease D given Test-positive = 

               P(Test is positive|Disease) * P(Disease)
     (scaled by) P(Testing Positive, with or without the disease)

Now, all this was just preamble, to get to Naive Bayes.

Getting to Naive Bayes'

So far, we have talked only about one piece of evidence. In reality, we have to predict an outcome given multiple evidence. In that case, the math gets very complicated. To get around that complication, one approach is to 'uncouple' multiple pieces of evidence, and to treat each of piece of evidence as independent. This approach is why this is called naive Bayes.

P(Outcome|Multiple Evidence) = 
P(Evidence1|Outcome) * P(Evidence2|outcome) * ... * P(EvidenceN|outcome) * P(Outcome)
scaled by P(Multiple Evidence)

Many people choose to remember this as:

                      P(Likelihood of Evidence) * Prior prob of outcome
P(outcome|evidence) = _________________________________________________

Notice a few things about this equation:

  • If the Prob(evidence|outcome) is 1, then we are just multiplying by 1.
  • If the Prob(some particular evidence|outcome) is 0, then the whole prob. becomes 0. If you see contradicting evidence, we can rule out that outcome.
  • Since we divide everything by P(Evidence), we can even get away without calculating it.
  • The intuition behind multiplying by the prior is so that we give high probability to more common outcomes, and low probabilities to unlikely outcomes. These are also called base rates and they are a way to scale our predicted probabilities.

How to Apply NaiveBayes to Predict an Outcome?

Just run the formula above for each possible outcome. Since we are trying to classify, each outcome is called a class and it has a class label. Our job is to look at the evidence, to consider how likely it is to be this class or that class, and assign a label to each entity. Again, we take a very simple approach: The class that has the highest probability is declared the "winner" and that class label gets assigned to that combination of evidences.

Fruit Example

Let's try it out on an example to increase our understanding: The OP asked for a 'fruit' identification example.

Let's say that we have data on 1000 pieces of fruit. They happen to be Banana, Orange or some Other Fruit. We know 3 characteristics about each fruit:

  1. Whether it is Long
  2. Whether it is Sweet and
  3. If its color is Yellow.

This is our 'training set.' We will use this to predict the type of any new fruit we encounter.

Type           Long | Not Long || Sweet | Not Sweet || Yellow |Not Yellow|Total
Banana      |  400  |    100   || 350   |    150    ||  450   |  50      |  500
Orange      |    0  |    300   || 150   |    150    ||  300   |   0      |  300
Other Fruit |  100  |    100   || 150   |     50    ||   50   | 150      |  200
Total       |  500  |    500   || 650   |    350    ||  800   | 200      | 1000

We can pre-compute a lot of things about our fruit collection.

The so-called "Prior" probabilities. (If we didn't know any of the fruit attributes, this would be our guess.) These are our base rates.

 P(Banana)      = 0.5 (500/1000)
 P(Orange)      = 0.3
 P(Other Fruit) = 0.2

Probability of "Evidence"

p(Long)   = 0.5
P(Sweet)  = 0.65
P(Yellow) = 0.8

Probability of "Likelihood"

P(Long|Banana) = 0.8
P(Long|Orange) = 0  [Oranges are never long in all the fruit we have seen.]

P(Yellow|Other Fruit)     =  50/200 = 0.25
P(Not Yellow|Other Fruit) = 0.75

Given a Fruit, how to classify it?

Let's say that we are given the properties of an unknown fruit, and asked to classify it. We are told that the fruit is Long, Sweet and Yellow. Is it a Banana? Is it an Orange? Or Is it some Other Fruit?

We can simply run the numbers for each of the 3 outcomes, one by one. Then we choose the highest probability and 'classify' our unknown fruit as belonging to the class that had the highest probability based on our prior evidence (our 1000 fruit training set):

P(Banana|Long, Sweet and Yellow) 
      P(Long|Banana) * P(Sweet|Banana) * P(Yellow|Banana) * P(banana)
    = _______________________________________________________________
                      P(Long) * P(Sweet) * P(Yellow)
    = 0.8 * 0.7 * 0.9 * 0.5 / P(evidence)

    = 0.252 / P(evidence)

P(Orange|Long, Sweet and Yellow) = 0

P(Other Fruit|Long, Sweet and Yellow)
      P(Long|Other fruit) * P(Sweet|Other fruit) * P(Yellow|Other fruit) * P(Other Fruit)
    = ____________________________________________________________________________________

    = (100/200 * 150/200 * 50/200 * 200/1000) / P(evidence)

    = 0.01875 / P(evidence)

By an overwhelming margin (0.252 >> 0.01875), we classify this Sweet/Long/Yellow fruit as likely to be a Banana.

Why is Bayes Classifier so popular?

Look at what it eventually comes down to. Just some counting and multiplication. We can pre-compute all these terms, and so classifying becomes easy, quick and efficient.

Let z = 1 / P(evidence). Now we quickly compute the following three quantities.

P(Banana|evidence) = z * Prob(Banana) * Prob(Evidence1|Banana) * Prob(Evidence2|Banana) ...
P(Orange|Evidence) = z * Prob(Orange) * Prob(Evidence1|Orange) * Prob(Evidence2|Orange) ...
P(Other|Evidence)  = z * Prob(Other)  * Prob(Evidence1|Other)  * Prob(Evidence2|Other)  ...

Assign the class label of whichever is the highest number, and you are done.

Despite the name, Naive Bayes turns out to be excellent in certain applications. Text classification is one area where it really shines.

Hope that helps in understanding the concepts behind the Naive Bayes algorithm.

How do I view executed queries within SQL Server Management Studio?

Run the following query from Management Studio on a running process:

DBCC inputbuffer( spid# )

This will return the SQL currently being run against the database for the SPID provided. Note that you need appropriate permissions to run this command.

This is better than running a trace since it targets a specific SPID. You can see if it's long running based on its CPUTime and DiskIO.

Example to get details of SPID 64:

DBCC inputbuffer(64)

How to check syslog in Bash on Linux?

How about less /var/log/syslog?

Child with max-height: 100% overflows parent

When you specify a percentage for max-height on a child, it is a percentage of the parent's actual height, not the parent's max-height, oddly enough. The same applies to max-width.

So, when you don't specify an explicit height on the parent, then there's no base height for the child's max-height to be calculated from, so max-height computes to none, allowing the child to be as tall as possible. The only other constraint acting on the child now is the max-width of its parent, and since the image itself is taller than it is wide, it overflows the container's height downwards, in order to maintain its aspect ratio while still being as large as possible overall.

When you do specify an explicit height for the parent, then the child knows it has to be at most 100% of that explicit height. That allows it to be constrained to the parent's height (while still maintaining its aspect ratio).

Making an iframe responsive

The code below will make the fixed width content of a non-responsive website within an iframe resize to the viewport width, only if its width is larger than the viewport width. For demo purposes the website is a single image 800 pixels wide. You can test by resizing your browser window or load the page in your phone:

<meta name="viewport" content="width=device-width, initial-scale=1">
body, html {width: 100%; height: 100%; margin: 0; padding: 0}
iframe {width: 100%; transform-origin: left top;}
<script type="text/javascript" src=""></script>   
    function nsZoomZoom(){
        htmlWidth = $('html').innerWidth();
        iframeWidth = 800;
        if (htmlWidth > iframeWidth)
            scale = 1;
        else {
            scale = htmlWidth / (iframeWidth); 
        $("iframe").css('transform', 'scale(' + scale + ')');
        $("iframe").css('width', '800');
<div class=imgbox>
    <iframe src="" scrolling=no width=800 height=600 frameborder=no></iframe>

Change the spacing of tick marks on the axis of a plot?

With base graphics, the easiest way is to stop the plotting functions from drawing axes and then draw them yourself.

plot(1:10, 1:10, axes = FALSE)
axis(side = 1, at = c(1,5,10))
axis(side = 2, at = c(1,3,7,10))

An error occurred while executing the command definition. See the inner exception for details

Look at the Inner Exception and find out what object might have caused the problem, you might have changed its name.

JAXB: How to ignore namespace during unmarshalling XML document?

I believe you must add the namespace to your xml document, with, for example, the use of a SAX filter.

That means:

  • Define a ContentHandler interface with a new class which will intercept SAX events before JAXB can get them.
  • Define a XMLReader which will set the content handler

then link the two together:

public static Object unmarshallWithFilter(Unmarshaller unmarshaller, source) throws FileNotFoundException, JAXBException 
    FileReader fr = null;
    try {
        fr = new FileReader(source);
        XMLReader reader = new NamespaceFilterXMLReader();
        InputSource is = new InputSource(fr);
        SAXSource ss = new SAXSource(reader, is);
        return unmarshaller.unmarshal(ss);
    } catch (SAXException e) {
        //not technically a jaxb exception, but close enough
        throw new JAXBException(e);
    } catch (ParserConfigurationException e) {
        //not technically a jaxb exception, but close enough
        throw new JAXBException(e);
    } finally {
        FileUtil.close(fr); //replace with this some safe close method you have

How to sort two lists (which reference each other) in the exact same way

If you are using numpy you can use np.argsort to get the sorted indices and apply those indices to the list. This works for any number of list that you would want to sort.

import numpy as np

arr1 = np.array([4,3,1,32,21])
arr2 = arr1 * 10
sorted_idxs = np.argsort(arr1)

>>> array([2, 1, 0, 4, 3])

>>> array([ 1,  3,  4, 21, 32])

>>> array([ 10,  30,  40, 210, 320])

Session 'app': Error Launching activity

I had the same error as in the headline. after I changed the version name and version code in the gradle, the sync happened and then it worked. so maybe even only sync can help sometimes.

Using AJAX to pass variable to PHP and retrieve those using AJAX again

In your PhP file there's going to be a variable called $_REQUEST and it contains an array with all the data send from Javascript to PhP using AJAX.

Try this: var_dump($_REQUEST); and check if you're receiving the values.

Get names of all keys in the collection

I extended Carlos LM's solution a bit so it's more detailed.

Example of a schema:

var schema = {
    _id: 123,
    id: 12,
    t: 'title',
    p: 4.5,
    ls: [{
            l: 'lemma',
            p: {
                pp: 8.9
            l: 'lemma2',
            p: {
               pp: 8.3

Type into the console:

var schemafy = function(schema, i, limit) {
    var i = (typeof i !== 'undefined') ? i : 1;
    var limit = (typeof limit !== 'undefined') ? limit : false;
    var type = '';
    var array = false;

    for (key in schema) {
        type = typeof schema[key];
        array = (schema[key] instanceof Array) ? true : false;

        if (type === 'object') {
            print(Array(i).join('    ') + key+' <'+((array) ? 'array' : type)+'>:');
            schemafy(schema[key], i+1, array);
        } else {
            print(Array(i).join('    ') + key+' <'+type+'>');

        if (limit) {




_id <number>
id <number>
t <string>
p <number>
ls <object>:
    0 <object>:
    l <string>
    p <object>:
        pp <number> 

How to Replace Multiple Characters in SQL?

While this question was asked about SQL Server 2005, it's worth noting that as of Sql Server 2017, the request can be done with the new TRANSLATE function.

I hope this information helps people who get to this page in the future.

How to cancel/abort jQuery AJAX request?

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

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

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

        //abort request


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

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


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

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

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

Serializing with Jackson (JSON) - getting "No serializer found"?

Please use this at class level for the bean:


Searching for file in directories recursively

You could use this overload of Directory.GetFiles which searches subdirectories for you, for example:

string[] files = Directory.GetFiles(sDir, "*.xml", SearchOption.AllDirectories);

Only one extension can be searched for like that, but you could use something like:

var extensions = new List<string> { ".txt", ".xml" };
string[] files = Directory.GetFiles(sDir, "*.*", SearchOption.AllDirectories)
                    .Where(f => extensions.IndexOf(Path.GetExtension(f)) >= 0).ToArray();

to select files with the required extensions (N.B. that is case-sensitive for the extension).

In some cases it can be desirable to enumerate over the files with the Directory.EnumerateFiles Method:

foreach(string f in Directory.EnumerateFiles(sDir, "*.xml", SearchOption.AllDirectories))
    // do something

Consult the documentation for exceptions which can be thrown, such as UnauthorizedAccessException if the code is running under an account which does not have appropriate access permissions.

NodeJS: How to get the server's port?

const express = require('express');                                                                                                                           
const morgan = require('morgan')
const PORT = 3000;

morgan.token('port', (req) => { 

const app = express();
app.locals.port = PORT;
app.use(morgan(':method :url :port'))
app.get('/app', function(req, res) {
    res.send("Hello world from server");


Converting date between DD/MM/YYYY and YYYY-MM-DD?

I am new to programming. I wanted to convert from yyyy-mm-dd to dd/mm/yyyy to print out a date in the format that people in my part of the world use and recognise.

The accepted answer above got me on the right track.

The answer I ended up with to my problem is:

import datetime

today_date =

new_today_date = today_date.strftime("%d/%m/%Y")
print (new_today_date)

The first two lines after the import statement gives today's date in the USA format (2017-01-26). The last two lines convert this to the format recognised in the UK and other countries (26/01/2017).

You can shorten this code, but I left it as is because it is helpful to me as a beginner. I hope this helps other beginner programmers starting out!

PHP code to remove everything but numbers

Try this:

preg_replace('/[^0-9]/', '', '604-619-5135');

preg_replace uses PCREs which generally start and end with a /.

How to convert datetime to timestamp using C#/.NET (ignoring current timezone)

I'm not exactly sure what it is that you want. Do you want a TimeStamp? Then you can do something simple like:

TimeStamp ts = TimeStamp.FromTicks(value.ToUniversalTime().Ticks);

Since you named a variable epoch, do you want the Unix time equivalent of your date?

DateTime unixStart = DateTime.SpecifyKind(new DateTime(1970, 1, 1), DateTimeKind.Utc);
long epoch = (long)Math.Floor((value.ToUniversalTime() - unixStart).TotalSeconds);

Getting the last revision number in SVN?

You can use either commands:

> svn info | awk '/Revision:/ { print $2 }' =>returns the latest version

> svn log -l 1 | grep '^r[0-9]\+' | awk '{print $1}'

svn log -l 1     => returns the latest version commit 
grep '^r[0-9]\+' => greps the r4324 (revision) number
awk '{print $1}' => prints the match found

Get class name of object as string in Swift

Try reflect().summary on Class self or instance dynamicType. Unwrap optionals before getting dynamicType otherwise the dynamicType is the Optional wrapper.

class SampleClass { class InnerClass{} }
let sampleClassName = reflect(SampleClass.self).summary;
let instance = SampleClass();
let instanceClassName = reflect(instance.dynamicType).summary;
let innerInstance = SampleClass.InnerClass();
let InnerInstanceClassName = reflect(innerInstance.dynamicType).summary.pathExtension;
let tupleArray = [(Int,[String:Int])]();
let tupleArrayTypeName = reflect(tupleArray.dynamicType).summary;

The summary is a class path with generic types described. To get a simple class name from the summary try this method.

func simpleClassName( complexClassName:String ) -> String {
    var result = complexClassName;
    var range = result.rangeOfString( "<" );
    if ( nil != range ) { result = result.substringToIndex( range!.startIndex ); }
    range = result.rangeOfString( "." );
    if ( nil != range ) { result = result.pathExtension; }
    return result;

How to get value of Radio Buttons?

You need to check one if you have two




You need to check all the checkboxes if more then two


else if(rb2.Checked)

else if(rb3.Checked)


How to split page into 4 equal parts?

try this... obviously you need to set each div to 25%. You then will need to add your content as needed :) Hope that helps.

   <title>CSS devide window by 25% horizontally</title>
   <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
   <style type="text/css" media="screen"> 
     body {
     <div id="top_div">Top- height is 25% of window height</div>
     <div id="mid1_div">Middle 1 - height is 25% of window height</div>
     <div id="mid2_div">Middle 2 - height is 25% of window height</div>
     <div id="bottom_div">Bottom - height is 25% of window height</div>

Tested and works fine, copy the code above into a HTML file, and open with your browser.

autocomplete ='off' is not working when the input type is password and make the input field above it to enable autocomplete

I know this is an old question, but browsers have been changing over time. Although some of the answers to this question mentioned here like: creating a temporary text box above the password field and hiding it may have worked in the past, currently the easiest way to prevent the browser from popping up the password manager is to have at least three separate additional hidden password inputs, each with different dummy values, like so:

<form method="post" autocomplete="off" action="">
    <ul class="field-set">
        <input type="text" name="acct" id="username" maxlength="100" size="20">
        <input type="password" name="pswd" id="password" maxlength="16" size="20" >
        <input type="password" style="display: none;" value="dummyinput1"/>
        <input type="password" style="display: none;" value="dummyinput2"/>
        <input type="password" style="display: none;" value="dummyinput3"/>
        <input type="submit" class="button" value="Login" id="Login" name="Login">

How to install PyQt4 in anaconda?

For windows users, there is an easy fix. Download whl files from:

run from anaconda prompt pip install PyQt4-4.11.4-cp37-cp37m-win_amd64.whl

ORA-12170: TNS:Connect timeout occurred

Issue because connection establishment or communication with a client failed to complete within the allotted time interval. This may be a result of network or system delays.

Cloning git repo causes error - Host key verification failed. fatal: The remote end hung up unexpectedly

Well, from sourceTree I couldn't resolve this issue but I created sshkey from bash and at least it works from git-bash.

Create timestamp variable in bash script

And for my fellow Europeans, try using this:

timestamp=$(date +%d-%m-%Y_%H-%M-%S)

will give a format of the format: "15-02-2020_19-21-58"

You call the variable and get the string representation like this


Java 8: Difference between two LocalDateTime in multiple units

Here is a very simple answer to your question. It works.

import java.time.*;
import java.util.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;

public class MyClass {
public static void main(String args[]) {
    DateTimeFormatter T = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm");
    Scanner h = new Scanner(;

    System.out.print("Enter date of birth[dd/mm/yyyy hh:mm]: ");
    String b = h.nextLine();

    LocalDateTime bd = LocalDateTime.parse(b,T);
    LocalDateTime cd =;

    long minutes = ChronoUnit.MINUTES.between(bd, cd);
    long hours = ChronoUnit.HOURS.between(bd, cd);

    System.out.print("Age is: "+hours+ " hours, or " +minutes+ " minutes old");

E11000 duplicate key error index in mongodb mongoose

This is because there is already a collection with the same name with configuration..Just remove the collection from your mongodb through mongo shell and try again.


now run your application it should work

Format SQL in SQL Server Management Studio

There is a special trick I discovered by accident.

  1. Select the query you wish to format.
  2. Ctrl+Shift+Q (This will open your query in the query designer)
  3. Then just go OK Voila! Query designer will format your query for you. Caveat is that you can only do this for statements and not procedural code, but its better than nothing.

get parent's view from a layout

Just write


Form Google Maps URL that searches for a specific places near specific coordinates

You can use the new URL for Google Maps:,-74.86084,18z equivalent to,-74.86084.

39.774769 is the latitude and -74.86084 is longitude and 18z is 18 zoom level.

Loop over html table and get checked checkboxes (JQuery)

Use this instead:

$('#save').click(function () {
    $('#mytable').find('input[type="checkbox"]:checked') //...

Let me explain you what the selector does: input[type="checkbox"] means that this will match each <input /> with type attribute type equals to checkbox After that: :checked will match all checked checkboxes.

You can loop over these checkboxes with:

$('#save').click(function () {
    $('#mytable').find('input[type="checkbox"]:checked').each(function () {
       //this is the current checkbox

Here is demo in JSFiddle.

And here is a demo which solves exactly your problem

$('#save').click(function () {
    $('#mytable').find('tr').each(function () {
        var row = $(this);
        if (row.find('input[type="checkbox"]').is(':checked') &&
            row.find('textarea').val().length <= 0) {
            alert('You must fill the text area!');

Extract public/private key from PKCS12 file for later use in SSH-PK-Authentication

As far as I know PKCS#12 is just a certificate/public/private key store. If you extracted a public key from PKCS#12 file, OpenSSH should be able to use it as long as it was extracted in PEM format. You probably already know that you also need a corresponding private key (also in PEM) in order to use it for ssh-public-key authentication.

SOAP-UI - How to pass xml inside parameter

NOTE: This one is just an alternative for the previous provided .NET framework 3.5 and above

You can send it as raw xml

<test>or like this</test>

If you declare the paramater2 as XElement data type

How to use CURL via a proxy?

I have explained use of various CURL options required for CURL PROXY.

$url = '';
$proxy = '';
$proxyauth = 'user:password';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);         // URL for CURL call
curl_setopt($ch, CURLOPT_PROXY, $proxy);     // PROXY details with port
curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyauth);   // Use if proxy have username and password
curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5); // If expected to call with specific PROXY type
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);  // If url has redirects then go to the final redirected URL.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);  // Do not outputting it out directly on screen.
curl_setopt($ch, CURLOPT_HEADER, 1);   // If you want Header information of response else make 0
$curl_scraped_page = curl_exec($ch);

echo $curl_scraped_page;

Selecting non-blank cells in Excel with VBA

If you are looking for the last row of a column, use:

Sub SelectFirstColumn()
   SelectEntireColumn (1)
End Sub

Sub SelectSecondColumn()
    SelectEntireColumn (2)
End Sub

Sub SelectEntireColumn(columnNumber)
    Dim LastRow
    LastRow = ActiveSheet.Columns(columnNumber).SpecialCells(xlLastCell).Row

    ActiveSheet.Range(Cells(1, columnNumber), Cells(LastRow, columnNumber)).Select
End Sub

Other commands you will need to get familiar with are copy and paste commands:

Sub CopyOneToTwo()
    SelectEntireColumn (1)

    ActiveSheet.Range("B1").PasteSpecial Paste:=xlPasteValues
End Sub

Finally, you can reference worksheets in other workbooks by using the following syntax:

Dim book2
Set book2 = Workbooks.Open("C:\book2.xls")

Element count of an array in C++

First off, you can circumvent that problem by using std::vector instead of an array. Second, if you put objects of a derived class into an array of a super class, you will experience slicing, but the good news is, your formula will work. Polymorphic collections in C++ are achieved using pointers. There are three major options here:

Non-resolvable parent POM using Maven 3.0.3 and relativePath notation

Here is answer to your question.

By default maven looks in ../pom.xml for relativePath. Use empty <relativePath/> tag instead.

Creating a new database and new connection in Oracle SQL Developer

Open Oracle SQLDeveloper

Right click on connection tab and select new connection

Enter HR_ORCL in connection name and HR for the username and password.

Specify localhost for your Hostname and enter ORCL for the SID.

Click Test.

The status of the connection Test Successfully.

The connection was not saved however click on Save button to save the connection. And then click on Connect button to connect your database.

The connection is saved and you see the connection list.

SQL Server 2008 can't login with newly created user

If you haven't restarted your SQL database Server after you make login changes, then make sure you do that. Start->Programs->Microsoft SQL Server -> Configuration tools -> SQL Server configuration manager -> Restart Server.

It looks like you only added the user to the server. You need to add them to the database too. Either open the database/Security/User/Add New User or open the server/Security/Logins/Properties/User Mapping.

Creating a SearchView that looks like the material design guidelines

The following will create a SearchView identical to the one in Gmail and add it to the given Toolbar. You'll just have to implement your own "ViewUtil.convertDpToPixel" method.

private SearchView createMaterialSearchView(Toolbar toolbar, String hintText) {

    ActionBar actionBar = getSupportActionBar();

    SearchView searchView = new SearchView(this);

    int rightMarginFrame = 0;
    View frame = searchView.findViewById(getResources().getIdentifier("android:id/search_edit_frame", null, null));
    if (frame != null) {
        LinearLayout.LayoutParams frameParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        rightMarginFrame = ((LinearLayout.LayoutParams) frame.getLayoutParams()).rightMargin;
        frameParams.setMargins(0, 0, 0, 0);

    View plate = searchView.findViewById(getResources().getIdentifier("android:id/search_plate", null, null));
    if (plate != null) {
        plate.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        plate.setPadding(0, 0, rightMarginFrame, 0);

    int autoCompleteId = getResources().getIdentifier("android:id/search_src_text", null, null);
    if (searchView.findViewById(autoCompleteId) != null) {
        EditText autoComplete = (EditText) searchView.findViewById(autoCompleteId);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, (int) ViewUtil.convertDpToPixel(36));
        params.weight = 1;
        params.gravity = Gravity.CENTER_VERTICAL;
        params.leftMargin = rightMarginFrame;

    int searchMagId = getResources().getIdentifier("android:id/search_mag_icon", null, null);
    if (searchView.findViewById(searchMagId) != null) {
        ImageView v = (ImageView) searchView.findViewById(searchMagId);
        v.setPadding(0, 0, 0, 0);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        params.setMargins(0, 0, 0, 0);

    toolbar.setContentInsetsAbsolute(0, 0);

    return searchView;

Remove spacing between table cells and rows

It looks like the DOCTYPE is causing the image to display as an inline element. If I add display: block to the image, problem solved.

Find the least number of coins required that can make any change from 1 to 99 cents

Edit: As the commenters have noted, I have misinterpreted the question. (The question is very similar to a basic CS problem I see students at the college having to solve...) waves hand This is not the answer you are looking for. That said, while the original answer is wrong, we can use it as a stepping stone to an O(n) solution.

So, take the wrong answer below, which only solves for a single value (ie, the minimum coinage required for 68 cents) and simply run it for every value.

changes = []
for amount in xrange(1, 100): # [1, 99]
    changes.append( run_the_algo_below( amount ) )
# Take the maximum for each coin type.
# ie, if run_the_algo_below returns (q, d, n, p):
change = [0, 0, 0, 0]
for c in changes:
    change = [max(c[i], change[i] for i in xrange(0, 4)]

Now, this will certainly give you a valid answer, but is it a minimal answer? (this is the harder part. Currently my gut says yes, but I'm still thinking about this one...)

(The wrong answer)

Wow. Loops? Dynamic programming? Really folks?

In Python:

amount = ( your_amount_in_cents )

quarters = amount // 25
dimes = amount % 25 // 10
nickels = amount % 25 % 10 // 5
pennies = amount % 25 % 10 % 5

Probably some of those modulo operations can be simplified...

This isn't hard, you just need to think about how you make change in real life. You give out quarters until adding another quarter would put you over the desired amount, you give out dimes until adding another dime would put you over the desired amount, so on. Then, convert to mathematical operations: modulo and division. Same solution applies for dollars, converting seconds into HH:MM:SS, etc.

Cell color changing in Excel using C#

For text:

[RangeObject].Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);

For cell background

[RangeObject].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);

How to bind Dataset to DataGridView in windows application

following will show one table of dataset

DataGridView1.AutoGenerateColumns = true;
DataGridView1.DataSource = ds; // dataset
DataGridView1.DataMember = "TableName"; // table name you need to show

if you want to show multiple tables, you need to create one datatable or custom object collection out of all tables.

if two tables with same table schema

dtAll = dtOne.Copy(); // dtOne = ds.Tables[0]
dtAll.Merge(dtTwo); // dtTwo = dtOne = ds.Tables[1]

DataGridView1.AutoGenerateColumns = true;
DataGridView1.DataSource = dtAll ; // datatable

sample code to mode all tables

DataTable dtAll = ds.Tables[0].Copy();
for (var i = 1; i < ds.Tables.Count; i++)
DataGridView1.AutoGenerateColumns = true;
DataGridView1.DataSource = dtAll ;

Best way to read a large file into a byte array in C#?

In case with 'a large file' is meant beyond the 4GB limit, then my following written code logic is appropriate. The key issue to notice is the LONG data type used with the SEEK method. As a LONG is able to point beyond 2^32 data boundaries. In this example, the code is processing first processing the large file in chunks of 1GB, after the large whole 1GB chunks are processed, the left over (<1GB) bytes are processed. I use this code with calculating the CRC of files beyond the 4GB size. (using for the crc32c calculation in this example)

private uint Crc32CAlgorithmBigCrc(string fileName)
    uint hash = 0;
    byte[] buffer = null;
    FileInfo fileInfo = new FileInfo(fileName);
    long fileLength = fileInfo.Length;
    int blockSize = 1024000000;
    decimal div = fileLength / blockSize;
    int blocks = (int)Math.Floor(div);
    int restBytes = (int)(fileLength - (blocks * blockSize));
    long offsetFile = 0;
    uint interHash = 0;
    Crc32CAlgorithm Crc32CAlgorithm = new Crc32CAlgorithm();
    bool firstBlock = true;
    using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
        buffer = new byte[blockSize];
        using (BinaryReader br = new BinaryReader(fs))
            while (blocks > 0)
                blocks -= 1;
                fs.Seek(offsetFile, SeekOrigin.Begin);
                buffer = br.ReadBytes(blockSize);
                if (firstBlock)
                    firstBlock = false;
                    interHash = Crc32CAlgorithm.Compute(buffer);
                    hash = interHash;
                    hash = Crc32CAlgorithm.Append(interHash, buffer);
                offsetFile += blockSize;
            if (restBytes > 0)
                Array.Resize(ref buffer, restBytes);
                fs.Seek(offsetFile, SeekOrigin.Begin);
                buffer = br.ReadBytes(restBytes);
                hash = Crc32CAlgorithm.Append(interHash, buffer);
            buffer = null;
    return hash;

Beginner Python Practice?

I used . A great website that not only takes one answer, like Project Euler, but also checks your code for more robustness by running it through multiple tests. It asks for much broader code than Project Euler, but its also much simpler than most Euler problems. It also has progress graphs which are pretty cool.

How to Create an excel dropdown list that displays text with a numeric hidden value

There are two types of drop down lists available (I am not sure since which version).

ActiveX Drop Down
You can set the column widths, so your hidden column can be set to 0.

Form Drop Down
You could set the drop down range to a hidden sheet and reference the cell adjacent to the selected item. This would also work with the ActiveX type control.

Swift 3 URLSession.shared() Ambiguous reference to member 'dataTask(with:completionHandler:) error (bug)

The compiler is confused by the function signature. You can fix it like this:

let task = URLSession.shared.dataTask(with: request as URLRequest) {

But, note that we don't have to cast "request" as URLRequest in this signature if it was declared earlier as URLRequest instead of NSMutableURLRequest:

var request = URLRequest(url:myUrl!)

This is the automatic casting between NSMutableURLRequest and the new URLRequest that is failing and which forced us to do this casting here.

Should I use Python 32bit or Python 64bit

In my experience, using the 32-bit version is more trouble-free. Unless you are working on applications that make heavy use of memory (mostly scientific computing, that uses more than 2GB memory), you're better off with 32-bit versions because:

  1. You generally use less memory.
  2. You have less problems using COM (since you are on Windows).
  3. If you have to load DLLs, they most probably are also 32-bit. Python 64-bit can't load 32-bit libraries without some heavy hacks running another Python, this time in 32-bit, and using IPC.
  4. If you have to load DLLs that you compile yourself, you'll have to compile them to 64-bit, which is usually harder to do (specially if using MinGW on Windows).
  5. If you ever use PyInstaller or py2exe, those tools will generate executables with the same bitness of your Python interpreter.

How to pass objects to functions in C++?

Rules of thumb for C++11:

Pass by value, except when

  1. you do not need ownership of the object and a simple alias will do, in which case you pass by const reference,
  2. you must mutate the object, in which case, use pass by a non-const lvalue reference,
  3. you pass objects of derived classes as base classes, in which case you need to pass by reference. (Use the previous rules to determine whether to pass by const reference or not.)

Passing by pointer is virtually never advised. Optional parameters are best expressed as a std::optional (boost::optional for older std libs), and aliasing is done fine by reference.

C++11's move semantics make passing and returning by value much more attractive even for complex objects.

Rules of thumb for C++03:

Pass arguments by const reference, except when

  1. they are to be changed inside the function and such changes should be reflected outside, in which case you pass by non-const reference
  2. the function should be callable without any argument, in which case you pass by pointer, so that users can pass NULL/0/nullptr instead; apply the previous rule to determine whether you should pass by a pointer to a const argument
  3. they are of built-in types, which can be passed by copy
  4. they are to be changed inside the function and such changes should not be reflected outside, in which case you can pass by copy (an alternative would be to pass according to the previous rules and make a copy inside of the function)

(here, "pass by value" is called "pass by copy", because passing by value always creates a copy in C++03)

There's more to this, but these few beginner's rules will get you quite far.

Good Java graph algorithm library?

If you are actually looking for Charting libraries and not for Node/Edge Graph libraries I would suggest splurging on Big Faceless Graph library (BFG). It's way easier to use than JFreeChart, looks nicer, runs faster, has more output options, really no comparison.

Traversing text in Insert mode

While in insert mode, use CtrlO to go to normal mode for just one command:

CTRL-O h  move cursor left 
CTRL-O l  move cursor right
CTRL-O j  move cursor down
CTRL-O k  move cursor up

which is probably the simplest way to do what you want and is easy to remember.

Other very useful control keys in insert mode:

CTRL-W    delete word to the left of cursor
CTRL-O D  delete everything to the right of cursor
CTRL-U    delete everything to the left of cursor
CTRL-H    backspace/delete
CTRL-J    insert newline (easier than reaching for the return key)
CTRL-T    indent current line
CTRL-D    un-indent current line

these will eliminate many wasteful switches back to normal mode.

How to correctly assign a new string value?

The first example doesn't work because you can't assign values to arrays - arrays work (sort of) like const pointers in this respect. What you can do though is copy a new value into the array:

strcpy(, "Jane");

Char arrays are fine to use if you know the maximum size of the string in advance, e.g. in the first example you are 100% sure that the name will fit into 19 characters (not 20 because one character is always needed to store the terminating zero value).

Conversely, pointers are better if you don't know the possible maximum size of your string, and/or you want to optimize your memory usage, e.g. avoid reserving 512 characters for the name "John". However, with pointers you need to dynamically allocate the buffer they point to, and free it when not needed anymore, to avoid memory leaks.

Update: example of dynamically allocated buffers (using the struct definition in your 2nd example):

char* firstName = "Johnnie";
char* surname = "B. Goode";
person p; = malloc(strlen(firstName) + 1);
p.surname = malloc(strlen(surname) + 1);

p.age = 25;
strcpy(, firstName);
strcpy(p.surname, surname);

printf("Name: %s; Age: %d\n",,p.age);


Angularjs if-then-else construction in expression

You can easily use ng-show such as :

    <div ng-repeater="item in items">
        <div ng-show="isExists(item)">available</div>
        <div ng-show="!isExists(item)">oh no, you don't have it</div>

For more complex tests, you can use ng-switch statements :

    <div ng-repeater="item in items">
        <div ng-switch on="isExists(item)">
            <span ng-switch-when="true">Available</span>
            <span ng-switch-default>oh no, you don't have it</span>

OAuth 2.0 Authorization Header

You can still use the Authorization header with OAuth 2.0. There is a Bearer type specified in the Authorization header for use with OAuth bearer tokens (meaning the client app simply has to present ("bear") the token). The value of the header is the access token the client received from the Authorization Server.

It's documented in this spec:


   GET /resource HTTP/1.1
   Authorization: Bearer mF_9.B5f-4.1JqM

Where mF_9.B5f-4.1JqM is your OAuth access token.

how to fetch data from database in Hibernate

try the class-name

Query query = session.createQuery("from Employee");

instead of the table name

Query query = session.createQuery("from EMPLOYEE");

Plot size and resolution with R markdown, knitr, pandoc, beamer

Figure sizes are specified in inches and can be included as a global option of the document output format. For example:

title: "My Document"
    fig_width: 6
    fig_height: 4

And the plot's size in the graphic device can be increased at the chunk level:

```{r, fig.width=14, fig.height=12}          #Expand the plot width to 14 inches

ggplot(aes(x=mycolumn1, y=mycolumn2)) +     #specify the x and y aesthetic
geom_line(size=2) +                         #makes the line thicker
theme_grey(base_size = 25)                  #increases the size of the font

You can also use the out.width and out.height arguments to directly define the size of the plot in the output file:

```{r, out.width="200px", out.height="200px"} #Expand the plot width to 200 pixels

ggplot(aes(x=mycolumn1, y=mycolumn2)) +     #specify the x and y aesthetic
geom_line(size=2) +                         #makes the line thicker
theme_grey(base_size = 25)                  #increases the size of the font

TypeError: unsupported operand type(s) for -: 'list' and 'list'

You can't subtract a list from a list.

>>> [3, 7] - [1, 2]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for -: 'list' and 'list'

Simple way to do it is using numpy:

>>> import numpy as np
>>> np.array([3, 7]) - np.array([1, 2])
array([2, 5])

You can also use list comprehension, but it will require changing code in the function:

>>> [a - b for a, b in zip([3, 7], [1, 2])]
[2, 5]

>>> import numpy as np
>>> def Naive_Gauss(Array,b):
...     n = len(Array)
...     for column in xrange(n-1):
...         for row in xrange(column+1, n):
...             xmult = Array[row][column] / Array[column][column]
...             Array[row][column] = xmult
...             #print Array[row][col]
...             for col in xrange(0, n):
...                 Array[row][col] = Array[row][col] - xmult*Array[column][col]
...             b[row] = b[row]-xmult*b[column]
...     print Array
...     print b
...     return Array, b  # <--- Without this, the function will return `None`.
>>> print Naive_Gauss(np.array([[2,3],[4,5]]),
...                   np.array([[6],[7]]))
[[ 2  3]
 [-2 -1]]
[[ 6]
(array([[ 2,  3],
       [-2, -1]]), array([[ 6],

How to capture the android device screen content?

For newer Android platforms, one can execute a system utility screencap in /system/bin to get the screenshot without root permission. You can try /system/bin/screencap -h to see how to use it under adb or any shell.

By the way, I think this method is only good for single snapshot. If we want to capture multiple frames for screen play, it will be too slow. I don't know if there exists any other approach for a faster screen capture.

Compare if BigDecimal is greater than zero

 BigDecimal obj = new BigDecimal("100");

Powershell get ipv4 address into a variable

$a = ipconfig
$result = $a[8] -replace "IPv4 Address. . . . . . . . . . . :",""

Also check which index of ipconfig has the IPv4 Address

Where can I find error log files?

For unix cli users:

Most probably the error_log ini entry isn't set. To verify:

php -i | grep error_log
// error_log => no value => no value

You can either set it in your php.ini cli file, or just simply quickly pipe all STDERR yourself to a file:

./myprog 2> myerror.log

Then quickly:

tail -f myerror.log

Hide console window from Process.Start C#

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

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

C++: variable 'std::ifstream ifs' has initializer but incomplete type

This seems to be answered - #include <fstream>.

The message means :-

incomplete type - the class has not been defined with a full class. The compiler has seen statements such as class ifstream; which allow it to understand that a class exists, but does not know how much memory the class takes up.

The forward declaration allows the compiler to make more sense of :-

void BindInput( ifstream & inputChannel ); 

It understands the class exists, and can send pointers and references through code without being able to create the class, see any data within the class, or call any methods of the class.

The has initializer seems a bit extraneous, but is saying that the incomplete object is being created.

Send Email Intent

This is quoted from Android official doc, I've tested it on Android 4.4, and works perfectly. See more examples at

public void composeEmail(String[] addresses, String subject) {
    Intent intent = new Intent(Intent.ACTION_SENDTO);
    intent.setData(Uri.parse("mailto:")); // only email apps should handle this
    intent.putExtra(Intent.EXTRA_EMAIL, addresses);
    intent.putExtra(Intent.EXTRA_SUBJECT, subject);
    if (intent.resolveActivity(getPackageManager()) != null) {

PHP multidimensional array search by value

Try this

 function recursive_array_search($needle,$haystack) {
    foreach($haystack as $key=>$value) {
        if($needle===$value OR (is_array($value) && 
            recursive_array_search($needle,$value) !== false)) {
             return $current_key;
    return false;

Initial bytes incorrect after Java AES/CBC decryption

It's often the good idea to rely on standard library provided solution:

private static void stackOverflow15554296()
        NoSuchAlgorithmException, NoSuchPaddingException,        
        InvalidKeyException, IllegalBlockSizeException,

    // prepare key
    KeyGenerator keygen = KeyGenerator.getInstance("AES");
    SecretKey aesKey = keygen.generateKey();
    String aesKeyForFutureUse = Base64.getEncoder().encodeToString(

    // cipher engine
    Cipher aesCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");

    // cipher input
    aesCipher.init(Cipher.ENCRYPT_MODE, aesKey);
    byte[] clearTextBuff = "Text to encode".getBytes();
    byte[] cipherTextBuff = aesCipher.doFinal(clearTextBuff);

    // recreate key
    byte[] aesKeyBuff = Base64.getDecoder().decode(aesKeyForFutureUse);
    SecretKey aesDecryptKey = new SecretKeySpec(aesKeyBuff, "AES");

    // decipher input
    aesCipher.init(Cipher.DECRYPT_MODE, aesDecryptKey);
    byte[] decipheredBuff = aesCipher.doFinal(cipherTextBuff);
    System.out.println(new String(decipheredBuff));

This prints "Text to encode".

Solution is based on Java Cryptography Architecture Reference Guide and answer.

Can I use a binary literal in C or C++?

I extended the good answer given by @renato-chandelier by ensuring the support of:

  • _NIBBLE_(…) – 4 bits, 1 nibble as argument
  • _BYTE_(…) – 8 bits, 2 nibbles as arguments
  • _SLAB_(…) – 12 bits, 3 nibbles as arguments
  • _WORD_(…) – 16 bits, 4 nibbles as arguments
  • _QUINTIBBLE_(…) – 20 bits, 5 nibbles as arguments
  • _DSLAB_(…) – 24 bits, 6 nibbles as arguments
  • _SEPTIBBLE_(…) – 28 bits, 7 nibbles as arguments
  • _DWORD_(…) – 32 bits, 8 nibbles as arguments

I am actually not so sure about the terms “quintibble” and “septibble”. If anyone knows any alternative please let me know.

Here is the macro rewritten:

#define __CAT__(A, B) A##B
#define _CAT_(A, B) __CAT__(A, B)

#define __HEX_0000 0
#define __HEX_0001 1
#define __HEX_0010 2
#define __HEX_0011 3
#define __HEX_0100 4
#define __HEX_0101 5
#define __HEX_0110 6
#define __HEX_0111 7
#define __HEX_1000 8
#define __HEX_1001 9
#define __HEX_1010 a
#define __HEX_1011 b
#define __HEX_1100 c
#define __HEX_1101 d
#define __HEX_1110 e
#define __HEX_1111 f

#define _NIBBLE_(N1) _CAT_(0x, _CAT_(__HEX_, N1))
#define _BYTE_(N1, N2) _CAT_(_NIBBLE_(N1), _CAT_(__HEX_, N2))
#define _SLAB_(N1, N2, N3) _CAT_(_BYTE_(N1, N2), _CAT_(__HEX_, N3))
#define _WORD_(N1, N2, N3, N4) _CAT_(_SLAB_(N1, N2, N3), _CAT_(__HEX_, N4))
#define _QUINTIBBLE_(N1, N2, N3, N4, N5) _CAT_(_WORD_(N1, N2, N3, N4), _CAT_(__HEX_, N5))
#define _DSLAB_(N1, N2, N3, N4, N5, N6) _CAT_(_QUINTIBBLE_(N1, N2, N3, N4, N5), _CAT_(__HEX_, N6))
#define _SEPTIBBLE_(N1, N2, N3, N4, N5, N6, N7) _CAT_(_DSLAB_(N1, N2, N3, N4, N5, N6), _CAT_(__HEX_, N7))
#define _DWORD_(N1, N2, N3, N4, N5, N6, N7, N8) _CAT_(_SEPTIBBLE_(N1, N2, N3, N4, N5, N6, N7), _CAT_(__HEX_, N8))

And here is Renato's using example:

char b = _BYTE_(0100, 0001); /* equivalent to b = 65; or b = 'A'; or b = 0x41; */
unsigned int w = _WORD_(1101, 1111, 0100, 0011); /* equivalent to w = 57155; or w = 0xdf43; */
unsigned long int dw = _DWORD_(1101, 1111, 0100, 0011, 1111, 1101, 0010, 1000); /* Equivalent to dw = 3745774888; or dw = 0xdf43fd28; */

JavaFX FXML controller - constructor vs initialize method

In Addition to the above answers, there probably should be noted that there is a legacy way to implement the initialization. There is an interface called Initializable from the fxml library.

import javafx.fxml.Initializable;

class MyController implements Initializable {
    @FXML private TableView<MyModel> tableView;

    public void initialize(URL location, ResourceBundle resources) {


location - The location used to resolve relative paths for the root object, or null if the location is not known.
resources - The resources used to localize the root object, or null if the root object was not localized. 

And the note of the docs why the simple way of using @FXML public void initialize() works:

NOTE This interface has been superseded by automatic injection of location and resources properties into the controller. FXMLLoader will now automatically call any suitably annotated no-arg initialize() method defined by the controller. It is recommended that the injection approach be used whenever possible.

W3WP.EXE using 100% CPU - where to start?

We had this on a recursive query that was dumping tons of data to the output - have you double checked everything does exit and no infinite loops exist?

Might try to narrow it down with a single page - we found ANTS to not be much help in that same case either - what we ended up doing was running the site hit a page watch the CPU - hit the next page watch CPU - very methodical and time consuming but if you cant find it with some code tracing you might be out of luck -

We were able to use IIS log files to track it to a set of pages that were suspect -

Hope that helps !

What does "atomic" mean in programming?

If you have several threads executing the methods m1 and m2 in the code below:

class SomeClass {
    private int i = 0;

    public void m1() { i = 5; }
    public int m2() { return i; }

you have the guarantee that any thread calling m2 will either read 0 or 5.

On the other hand, with this code (where i is a long):

class SomeClass {
    private long i = 0;

    public void m1() { i = 1234567890L; }
    public long m2() { return i; }

a thread calling m2 could read 0, 1234567890L, or some other random value because the statement i = 1234567890L is not guaranteed to be atomic for a long (a JVM could write the first 32 bits and the last 32 bits in two operations and a thread might observe i in between).

iOS Remote Debugging

Many remote consoles work fine. is my project, and I was able to successfully debug issues specific to Crome iOS and not happening in safari using it. (and probably all other mobile browsers)

The problem is that injecting the debugging code is slightly tricky since Chrome doesn't allow you to install bookmarklets.

Instead you could open one tab on the page that you would debug, and another on and then click "the bookmarklet"

Copy the bookmarklet JS code, get back to the first tab, with the page that should be debugged, and paste the bookmarklet code in the location bar.

Last step is to scroll to the beginning of the location bar and add "javascript:", since Chrome will remove it.

Insert data through ajax into mysql database

Why use normal jquery ajax feature. Why not use jquery ajax form plugin, which post the form data by ajax to the form action link.

Check it here:

It is very easy to use and support several data formats including json, html xml etc. Checkout the example and you will find it very easy to use.

Thank you

Plotting lines connecting points

I realize this question was asked and answered a long time ago, but the answers don't give what I feel is the simplest solution. It's almost always a good idea to avoid loops whenever possible, and matplotlib's plot is capable of plotting multiple lines with one command. If x and y are arrays, then plot draws one line for every column.

In your case, you can do the following:

x=np.array([-1 ,0.5 ,1,-0.5])
xx = np.vstack([x[[0,2]],x[[1,3]]])
y=np.array([ 0.5,  1, -0.5, -1])
yy = np.vstack([y[[0,2]],y[[1,3]]])
plt.plot(xx,yy, '-o')

Have a long list of x's and y's, and want to connect adjacent pairs?

xx = np.vstack([x[0::2],x[1::2]])
yy = np.vstack([y[0::2],y[1::2]])

Want a specified (different) color for the dots and the lines?

plt.plot(xx,yy, '-ok', mfc='C1', mec='C1')

Plot of two pairs of points, each connected by a separate line

Android - How to achieve setOnClickListener in Kotlin?

Here is an example on how to use the onClickListener in Kotlin

button1.setOnClickListener(object : View.OnClickListener{
            override fun onClick(v: View?) {
                //Your code here

What does body-parser do with express?

Yes we can work without body-parser. When you don't use that you get the raw request, and your body and headers are not in the root object of request parameter . You will have to individually manipulate all the fields.

Or you can use body-parser, as the express team is maintaining it .

What body-parser can do for you: It simplifies the request.
How to use it: Here is example:

Install npm install body-parser --save

This how to use body-parser in express:

const express = require('express'),
      app = express(),
      bodyParser = require('body-parser');

// support parsing of application/json type post data

//support parsing of application/x-www-form-urlencoded post data
app.use(bodyParser.urlencoded({ extended: true }));


And then you can get body and headers in root request object . Example"/posturl",function(req,res,next){

Kotlin - How to correctly concatenate a String

yourString += "newString"

This way you can concatenate a string

Why dividing two integers doesn't get a float?

Use casting of types:

int main() {
    int a;
    float b, c, d;
    a = 750;
    b = a / (float)350;
    c = 750;
    d = c / (float)350;
    printf("%.2f %.2f", b, d);
    // output: 2.14 2.14

This is another way to solve that:

 int main() {
        int a;
        float b, c, d;
        a = 750;
        b = a / 350.0; //if you use 'a / 350' here, 
                       //then it is a division of integers, 
                       //so the result will be an integer
        c = 750;
        d = c / 350;
        printf("%.2f %.2f", b, d);
        // output: 2.14 2.14

However, in both cases you are telling the compiler that 350 is a float, and not an integer. Consequently, the result of the division will be a float, and not an integer.

Python add item to the tuple

Tuple can only allow adding tuple to it. The best way to do it is:

mytuple =(u'2',)
mytuple +=(,)

I tried the same scenario with the below data it all seems to be working fine.

>>> mytuple = (u'2',)
>>> mytuple += ('example text',)
>>> print mytuple
(u'2','example text')

Android Facebook integration with invalid key hash

This is how I solved this problem:

First you have to get the SHA-1 value. For that there are two ways.

To get the SHA-1 value in Android Studio.

  1. Click Gradle
  2. Click Signing Report
  3. Copy the SHA-1 value


To get the SHA-1 value from the keystore file.

keytool -list -v -keystore keystore_file_name.jks -alias key0

Copy the SHA-1 value to your clipboard like this:


And open Hexadecimal -> Base64 string decoder to convert your SHA-1 value to Base64.

This is what Facebook requires.

Get the generated hash " ********************= " and copy the key hash to the Facebook app.

Importing a GitHub project into Eclipse

I encountered the same problem, and finally found a way:

  1. Add or create git repository in git view.
  2. Click new java project menu, uncheck "use default location", select the git repo location, click finish.

Ecplise Version: Mars.2 Release (4.5.2)

JavaScript push to array

object["property"] = value;

or = value;

Object and Array in JavaScript are different in terms of usage. Its best if you understand them:

Object vs Array: JavaScript

How to find first element of array matching a boolean condition in JavaScript?

Since ES6 there is the native find method for arrays; this stops enumerating the array once it finds the first match and returns the value.

const result = someArray.find(isNotNullNorUndefined);

Old answer:

I have to post an answer to stop these filter suggestions :-)

since there are so many functional-style array methods in ECMAScript, perhaps there's something out there already like this?

You can use the some Array method to iterate the array until a condition is met (and then stop). Unfortunately it will only return whether the condition was met once, not by which element (or at what index) it was met. So we have to amend it a little:

function find(arr, test, ctx) {
    var result = null;
    arr.some(function(el, i) {
        return, el, i, arr) ? ((result = el), true) : false;
    return result;
var result = find(someArray, isNotNullNorUndefined);

Express.js req.body undefined

var bodyParser = require('body-parser');

This saved my day.

SQL query, if value is null then return 1

You can use a CASE statement.

    CASE WHEN currate.currentrate IS NULL THEN 1 ELSE currate.currentrate END
FROM ...

"Cannot open include file: 'config-win.h': No such file or directory" while installing mysql-python

building '_mysql' extension
creating build\
creating build\\Release
C:\Users\TimHuang\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0\VC\Bin\amd64\cl.exe /c /nologo /Ox /MD /W3 /GS- /DNDEBUG -Dversion_info=(1,2,5,'final',1) -D__version__=1.2.5 "-IC:\Program Files (x86)\MySQL\MySQL Connector C 6.0.2\include" -Ic:\python27\include -Ic:\python27\PC /Tc_mysql.c /Fobuild\\Release\_mysql.obj /Zl
_mysql.c(42) : fatal error C1083: Cannot open include file: 'config-win.h': No such file or directory

If you see this when you try pip install mysql-python, the easiest way is to copy

C:\Program Files\MySQL\MySQL Connector C 6.0.2 to C:\Program Files (x86)\MySQL\MySQL Connector C 6.0.2

I tried to create the symbolic link but Windows keeps throwing me C:\WINDOWS\system32>mklink /d "C:\Program Files (x86)\MySQL\MySQL Connector C 6.0.2\include" "C:\Program Files\MySQL\MySQL Connector C 6.0.2\include" The system cannot find the path specified.

Min and max value of input in angular4 application

[I assume the reader has basic knowledge of Angular2+ and Forms]

It is easy to show a numerical input and put the limits, but you have to also take care of things may happen out of your predictions.

  1. Implement the tag in your 'html':
<input type="number" [min]="0.00" [max]="100.00" [step]="0.01" formControlName="rateFC">
  1. But as Adrien said, still user can enter manually a wrong number. You can validate input by Validators easily. In your '.ts':
import { FormGroup, FormControl, Validators } from '@angular/forms';

//many other things...

this.myFG = new FormGroup({
   //other form controls...,
   rateFC  : new FormControl(0, [Validators.min(0), Validators.max(100)])
  1. Up to now everything is ok, but it is better to let the user know the input is wrong, then draw a red line around the invalid input element by adding to your style:{
    border:2px solid red;
  1. And to make it perfect, prevent the user to submit the wrong data.
<button type="submit" [disabled]="!myFG.valid">Submit</button>

How do I get unique elements in this array?

Have you looked at this page?

That might save you some time?

eg db.addresses.distinct("zip-code");

Entitlements file do not match those specified in your provisioning profile.(0xE8008016)

As others have pointed out, if you get this error, you need to check that the Bundle ID value in both your .plist file and also here:

Xcode project Build Settings tab with Product Bundle Identifier focused

Get input type="file" value when it has multiple files selected

The files selected are stored in an array: [input].files

For example, you can access the items

// assuming there is a file input with the ID `my-input`...
var files = document.getElementById("my-input").files;

for (var i = 0; i < files.length; i++)

For jQuery-comfortable people, it's similarly easy

// assuming there is a file input with the ID `my-input`...
var files = $("#my-input")[0].files;

for (var i = 0; i < files.length; i++)

How can I do time/hours arithmetic in Google Spreadsheet?

I had a similar issue and i just fixed it for now

  1. format each of the cell to time
  2. format the total cell (sum of all the time) to Duration

RecyclerView - Get view at particular position

To get a View from a specific position of recyclerView you need to call findViewHolderForAdapterPosition(position) on recyclerView object that will return RecyclerView.ViewHolder

from the returned RecyclerView.ViewHolder object with itemView you can access all Views at that particular position

RecyclerView.ViewHolder rv_view = recyclerView.findViewHolderForAdapterPosition(position);

ImageView iv_wish = rv_view.itemView.findViewById(;

How can I throw a general exception in Java?

You can define your own exception class extending java.lang.Exception (that's for a checked exception - these which must be caught), or extending java.lang.RuntimeException - these exceptions does not have to be caught.

The other solution is to review the Java API and finding an appropriate exception describing your situation: in this particular case I think that the best one would be IllegalArgumentException.

C++ calling base class constructors

Imagine it like this: When your sub-class inherits properties from a super-class, they don't magically appear. You still have to construct the object. So, you call the base constructor. Imagine if you class inherits a variable, which your super-class constructor initializes to an important value. If we didn't do this, your code could fail because the variable wasn't initialized.

Java - Abstract class to contain variables?

Of course. The whole idea of abstract classes is that they can contain some behaviour or data which you require all sub-classes to contain. Think of the simple example of WheeledVehicle - it should have a numWheels member variable. You want all sub classes to have this variable. Remember that abstract classes are a very useful feature when developing APIs, as they can ensure that people who extend your API won't break it.

Entity Framework is Too Slow. What are my options?

I have found the answer by @Slauma here very useful for speeding things up. I used the same sort of pattern for both inserts and updates - and performance rocketed.

Changing :hover to touch/click for mobile devices

Well I agree with above answers but still there can be an another way to do this and it is by using media queries.

Suppose this is what you want to do :

body.nontouch nav a:hover {
    background: yellow;

then you can do this by media query as :

@media(hover: hover) and (pointer: fine) {
    nav a:hover {
        background: yellow;

And for more details you can visit this page.

ImportError: No module named 'django.core.urlresolvers'

You need replace all occurrences of:

from django.core.urlresolvers import reverse


from django.urls import reverse

enter image description here

NOTE: The same apply to reverse_lazy

in Pycharm Cmd+Shift+R for starting replacment in Path.

How do you put an image file in a json object?

To upload files directly to Mongo DB you can make use of Grid FS. Although I will suggest you to upload the file anywhere in file system and put the image's url in the JSON object for every entry and then when you call the data for specific object you can call for the image using URL.

Tell me which backend technology are you using? I can give more suggestions based on that.

How can I determine the direction of a jQuery scroll event?

This works in all pc or phones browsers, expanding on the top answers. One can build a more complex event object window["scroll_evt"] then call it in the handleScroll() function. This one triggers for 2 concurrent conditions, if certain delay has elapsed or certain delta is passed to eliminate some unwanted triggers.

$(window).scroll(function() {

    var currentScroll = $(this).scrollTop();
    var currentTime =;
    var boolRun=(window["scroll_evt"]["min_delay"]>0)?(Math.abs(currentTime - window["scroll_evt"]["time"])>window["scroll_evt"]["min_delay"]):false;
    boolRun = boolRun && ((window["scroll_evt"]["min_delta"]>0)?(Math.abs(currentScroll - window["scroll_evt"]["pos"])>window["scroll_evt"]["min_delta"]):false);
        window["scroll_evt"]["delta"] = currentScroll - window["scroll_evt"]["pos"];
        window["scroll_evt"]["direction"] = window["scroll_evt"]["delta"]>0?'down':'up';
        window["scroll_evt"]["delay"] =currentTime - window["scroll_evt"]["time"];//in milisecs!!!
        window["scroll_evt"]["pos"] = currentScroll;
        window["scroll_evt"]["time"] = currentTime;

function handleScroll(){

Java: Date from unix timestamp

This is the right way:

Date date = new Date ();

How to use *ngIf else?

<div *ngIf="show; else elseBlock">Text to show</div>
<ng-template #elseBlock>Alternate text while primary text is hidden</ng-template>

Performing Breadth First Search recursively

Here's a Scala 2.11.4 implementation of recursive BFS. I've sacrificed tail-call optimization for brevity, but the TCOd version is very similar. See also @snv's post.

import scala.collection.immutable.Queue

object RecursiveBfs {
  def bfs[A](tree: Tree[A], target: A): Boolean = {
    bfs(Queue(tree), target)

  private def bfs[A](forest: Queue[Tree[A]], target: A): Boolean = {
    forest.dequeueOption exists {
      case (E, tail) => bfs(tail, target)
      case (Node(value, _, _), _) if value == target => true
      case (Node(_, l, r), tail) => bfs(tail.enqueue(List(l, r)), target)

  sealed trait Tree[+A]
  case class Node[+A](data: A, left: Tree[A], right: Tree[A]) extends Tree[A]
  case object E extends Tree[Nothing]

Origin <origin> is not allowed by Access-Control-Allow-Origin

For PHP, use this to set headers.

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: PUT, GET, POST");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");

Django: Get list of model fields?

At least with Django 1.9.9 -- the version I'm currently using --, note that .get_fields() actually also "considers" any foreign model as a field, which may be problematic. Say you have:

class Parent(models.Model):
    id = UUIDField(primary_key=True)

class Child(models.Model):
    parent = models.ForeignKey(Parent)

It follows that

>>> map(lambda, Parent._model._meta.get_fields())
['id', 'child']

while, as shown by @Rockallite

>>> map(lambda, Parent._model._meta.local_fields)

Place cursor at the end of text in EditText

 * Set cursor to end of text in edittext when user clicks Next on Keyboard.
View.OnFocusChangeListener onFocusChangeListener = new View.OnFocusChangeListener() {
    public void onFocusChange(View view, boolean b) {
        if (b) {
            ((EditText) view).setSelection(((EditText) view).getText().length());


It work good for me!

No module named _sqlite3

sqlite3 ships with Python. I also had the same problem, I just uninstalled python3.6 and installed it again.

Uninstall existing python:

sudo apt-get remove --purge python3.6

Install python3.6:

sudo apt install build-essential checkinstall
sudo apt install libreadline-gplv2-dev libncursesw5-dev libssl-dev libsqlite3-dev tk-dev libgdbm-dev libc6-dev libbz2-dev
tar xvf Python-3.6.0.tar.xz
cd Python-3.6.0/
sudo make altinstall

"sed" command in bash

sed is a stream editor. I would say try man sed.If you didn't find this man page in your system refer this URL:

Django ManyToMany filter()

Just restating what Tomasz said.

There are many examples of FOO__in=... style filters in the many-to-many and many-to-one tests. Here is syntax for your specific problem:

users_in_1zone = User.objects.filter(zones__id=<id1>)
# same thing but using in
users_in_1zone = User.objects.filter(zones__in=[<id1>])

# filtering on a few zones, by id
users_in_zones = User.objects.filter(zones__in=[<id1>, <id2>, <id3>])
# and by zone object (object gets converted to pk under the covers)
users_in_zones = User.objects.filter(zones__in=[zone1, zone2, zone3])

The double underscore (__) syntax is used all over the place when working with querysets.

Using the "With Clause" SQL Server 2008

Try the sp_foreachdb procedure.

What are the file limits in Git (number and size)?

I have a generous amount of data that's stored in my repo as individual JSON fragments. There's about 75,000 files sitting under a few directories and it's not really detrimental to performance.

Checking them in the first time was, obviously, a little slow.

Top 5 time-consuming SQL queries in Oracle

You could take the average buffer gets per execution during a period of activity of the instance:

SELECT username,
       -- elapsed_time, cpu_time, user_io_wait_time, ,
  FROM (SELECT sql_text,
               trunc(a.buffer_gets / a.executions) buffer_get_per_exec,
               100 - ROUND (100 * a.disk_reads / a.buffer_gets, 2) hit_ratio,
               -- cpu_time, elapsed_time, user_io_wait_time
          FROM v$sqlarea a, dba_users b
         WHERE a.parsing_user_id = b.user_id
           AND b.username NOT IN ('SYS', 'SYSTEM', 'RMAN','SYSMAN')
           AND a.buffer_gets > 10000
         ORDER BY buffer_get_per_exec DESC)

C# how to wait for a webpage to finish loading before continuing

Assuming the "commit" element represents a standard Form submit button then you can attach an event handler to the WebBrowsers Navigated event.

What is the difference between "Form Controls" and "ActiveX Control" in Excel 2010?

Google is full of information on this. As Hans Passant said, Form controls are built in to Excel whereas ActiveX controls are loaded separately.

Generally you'll use Forms controls, they're simpler. ActiveX controls allow for more flexible design and should be used when the job just can't be done with a basic Forms control.

Many user's computers by default won't trust ActiveX, and it will be disabled; this sometimes needs to be manually added to the trust center. ActiveX is a microsoft-based technology and, as far as I'm aware, is not supported on the Mac. This is something you'll have to also consider, should you (or anyone you provide a workbook to) decide to use it on a Mac.

Print PDF directly from JavaScript

I used this function to download pdf stream from server.

function printPdf(url) {
        var iframe = document.createElement('iframe');
        // = 'pdfIframe'
        document.body.appendChild(iframe); = 'none';
        iframe.onload = function () {
            setTimeout(function () {
                // document.body.removeChild(iframe)
            }, 1);
        iframe.src = url;
        // URL.revokeObjectURL(url)

How to insert a new line in Linux shell script?

You could use the printf(1) command, e.g. like

printf "Hello times %d\nHere\n" $[2+3] 

The  printf command may accept arguments and needs a format control string similar (but not exactly the same) to the one for the standard C printf(3) function...

Matrix Transpose in Python

def showmatrix (a,m,n):
    for i in range (m):
        for j in range (n):
            k=int(input("enter the number")
print (a[i][j]),


def showtranspose(a,m,n):
    for j in range(n):
        for i in range(m):

print("given matrix of order 4x3 is :")

print("Transpose matrix is:")

How to load/edit/run/save text files (.py) into an IPython notebook cell?

I have not found a satisfying answer for this question, i.e how to load edit, run and save. Overwriting either using %%writefile or %save -f doesn't work well if you want to show incremental changes in git. It would look like you delete all the lines in and add all new lines, even though you just edit 1 line.

Aliases in Windows command prompt

First, you could create a file named np.cmd and put it in the folder which in PATH search list. Then, edit the np.cmd file as below:

@echo off

How to save SELECT sql query results in an array in C#

Normally i use a class for this:

public class ClassName
    public string Col1 { get; set; }
    public int Col2 { get; set; }

Now you can use a loop to fill a list and ToArray if you really need an array:

ClassName[] allRecords = null;
string sql = @"SELECT col1,col2
               FROM  some table";
using (var command = new SqlCommand(sql, con))
    using (var reader = command.ExecuteReader())
        var list = new List<ClassName>();
        while (reader.Read())
            list.Add(new ClassName { Col1 = reader.GetString(0), Col2 = reader.GetInt32(1) });
        allRecords = list.ToArray();

Note that i've presumed that the first column is a string and the second an integer. Just to demonstrate that C# is typesafe and how you use the DataReader.GetXY methods.

How would you count occurrences of a string (actually a char) within a string?

If you check out this webpage, 15 different ways of doing this are benchmarked, including using parallel loops.

The fastest way appears to be using either a single threaded for-loop (if you have .Net version < 4.0) or a parallel.for loop (if using .Net > 4.0 with thousands of checks).

Assuming "ss" is your Search String, "ch" is your character array (if you have more than one char you're looking for), here's the basic gist of the code that had the fastest run time single threaded:

for (int x = 0; x < ss.Length; x++)
    for (int y = 0; y < ch.Length; y++)
        for (int a = 0; a < ss[x].Length; a++ )
        if (ss[x][a] == ch[y])
            //it's found. DO what you need to here.

The benchmark source code is provided too so you can run your own tests.

Clear listview content?

Simple its works me:)


phpmailer - The following SMTP Error: Data not accepted

set phpmailer to work in debug to see the "real" error behind the generic message 'SMTP Error: data not accepted' in our case the text in the message was triggering the smtp server spam filter.

  $email->SMTPDebug = true;

How can I keep my branch up to date with master with git?

If you just want the bug fix to be integrated into the branch, git cherry-pick the relevant commit(s).

Cannot connect to repo with TortoiseSVN

As stated by David W. "First of all, check your URL" - Our dns entry changed breaking all svn repo connections. Connecting on ip instead of url as Wes stated worked - (now we have to fix our dns)

Python : List of dict, if exists increment a dict value, if not append a new dict

To do it exactly your way? You could use the for...else structure

for url in list_of_urls:
    for url_dict in urls:
        if url_dict['url'] == url:
            url_dict['nbr'] += 1
        urls.append(dict(url=url, nbr=1))

But it is quite inelegant. Do you really have to store the visited urls as a LIST? If you sort it as a dict, indexed by url string, for example, it would be way cleaner:

urls = {'': dict(url='', nbr=1)}

for url in list_of_urls:
    if url in urls:
        urls[url]['nbr'] += 1
        urls[url] = dict(url=url, nbr=1)

A few things to note in that second example:

  • see how using a dict for urls removes the need for going through the whole urls list when testing for one single url. This approach will be faster.
  • Using dict( ) instead of braces makes your code shorter
  • using list_of_urls, urls and url as variable names make the code quite hard to parse. It's better to find something clearer, such as urls_to_visit, urls_already_visited and current_url. I know, it's longer. But it's clearer.

And of course I'm assuming that dict(url='', nbr=1) is a simplification of your own data structure, because otherwise, urls could simply be:

urls = {'':1}

for url in list_of_urls:
    if url in urls:
        urls[url] += 1
        urls[url] = 1

Which can get very elegant with the defaultdict stance:

urls = collections.defaultdict(int)
for url in list_of_urls:
    urls[url] += 1

C++ Fatal Error LNK1120: 1 unresolved externals

I have faced this particular error when I didn't defined the main() function. Check if the main() function exists or check the name of the function letter by letter as Timothy described above or check if the file where the main function is located is included to your project.

"CSV file does not exist" for a filename with embedded quotes

Just change the CSV file name. Once I changed it for me, it worked fine. Previously I gave data.csv then I changed it to CNC_1.csv.

Most Useful Attributes


as this allows you to ignore (in any xml serialisation) 'parent' objects that would otherwise cause exceptions when saving.

Generate Controller and Model


make:model {{SingularName}}


make:model Video

Using Linq to group a list of objects into a new grouped list of list of objects

var groupedCustomerList = userList
    .GroupBy(u => u.GroupID)
    .Select(grp => grp.ToList())

When should I use File.separator and when File.pathSeparator?

You use separator when you are building a file path. So in unix the separator is /. So if you wanted to build the unix path /var/temp you would do it like this:

String path = File.separator + "var"+ File.separator + "temp"

You use the pathSeparator when you are dealing with a list of files like in a classpath. For example, if your app took a list of jars as argument the standard way to format that list on unix is: /path/to/jar1.jar:/path/to/jar2.jar:/path/to/jar3.jar

So given a list of files you would do something like this:

String listOfFiles = ...
String[] filePaths = listOfFiles.split(File.pathSeparator);

MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED]

This one helped me. Try creating a new folder, if your MongoDB is installed in C:\Program Files the folder should be called db and in a folder data. C:\data\db

When you start the mongod there should be a log where the db 'isnt found'.

git checkout tag, git pull fails in branch

You need to set up your tracking (upstream) for the current branch

git branch --set-upstream master origin/master

Is already deprecated instead of that you can use --track flag

git branch --track master origin/master

I also like the doc reference that @casey notice:

-u <upstream>
  Set up <branchname>'s tracking information so <upstream> is considered  
  <branchname>'s upstream branch. If no <branchname> is specified,  
  then it defaults to the current branch.

How to write text on a image in windows using python opencv2

I know this is a really old question but i think i have a solution In the newer versions of openCV fonts are repesented by a number like this

    FONT_ITALIC = 16

so all you have to do is replace the font name with the corresponding number

cv2.putText(image,"Hello World!!!", (x,y), 0, 2, 255)

again i know its an old question but it may help someone in the future

How to calculate percentage with a SQL statement

SELECT Grade, GradeCount / SUM(GradeCount)
FROM (SELECT Grade, COUNT(*) As GradeCount
      FROM myTable
      GROUP BY Grade) Grades

How can I simulate an array variable in MySQL?

Inspired by the function ELT(index number, string1, string2, string3,…),I think the following example works as an array example:

set @i := 1;
while @i <= 3
  insert into table(val) values (ELT(@i ,'val1','val2','val3'...));
set @i = @i + 1;
end while;

Hope it help.

Convert Little Endian to Big Endian

I am assuming you are on linux

Include "byteswap.h" & Use int32_t bswap_32(int32_t argument);

It is logical view, In actual see, /usr/include/byteswap.h

Gradle Build Android Project "Could not resolve all dependencies" error

compileSdkVersion 17
targetSdkVersion 17

change the compile version from 18 to 17

compile ""
compile ""

"This SqlTransaction has completed; it is no longer usable."... configuration error?

Also check for any long running processes executed from your .NET app against the DB. For example you may be calling a stored procedure or query which does not have enough time to finish which can show in your logs as:

  • Execution Timeout Expired. The timeout period elapsed prior to completion of the operation or the server is not responding.

    • This SqlTransaction has completed; it is no longer usable.

Check the command timeout settings Try to run a trace (profiler) and see what is happening on the DB side...

What are the options for storing hierarchical data in a relational database?

Adjacency Model + Nested Sets Model

I went for it because I could insert new items to the tree easily (you just need a branch's id to insert a new item to it) and also query it quite fast.

| category_id | name                 | parent | lft | rgt |
|           1 | ELECTRONICS          |   NULL |   1 |  20 |
|           2 | TELEVISIONS          |      1 |   2 |   9 |
|           3 | TUBE                 |      2 |   3 |   4 |
|           4 | LCD                  |      2 |   5 |   6 |
|           5 | PLASMA               |      2 |   7 |   8 |
|           6 | PORTABLE ELECTRONICS |      1 |  10 |  19 |
|           7 | MP3 PLAYERS          |      6 |  11 |  14 |
|           8 | FLASH                |      7 |  12 |  13 |
|           9 | CD PLAYERS           |      6 |  15 |  16 |
|          10 | 2 WAY RADIOS         |      6 |  17 |  18 |
  • Every time you need all children of any parent you just query the parent column.
  • If you needed all descendants of any parent you query for items which have their lft between lft and rgt of parent.
  • If you needed all parents of any node up to the root of the tree, you query for items having lft lower than the node's lft and rgt bigger than the node's rgt and sort the by parent.

I needed to make accessing and querying the tree faster than inserts, that's why I chose this

The only problem is to fix the left and right columns when inserting new items. well I created a stored procedure for it and called it every time I inserted a new item which was rare in my case but it is really fast. I got the idea from the Joe Celko's book, and the stored procedure and how I came up with it is explained here in DBA SE

How do I prevent mails sent through PHP mail() from going to spam?

You must to add a needle headers:

Sample code :

$headers = "From: [email protected]\r\n";
$headers .= "Reply-To: [email protected]\r\n";
$headers .= "Return-Path: [email protected]\r\n";
$headers .= "CC: [email protected]\r\n";
$headers .= "BCC: [email protected]\r\n";

if ( mail($to,$subject,$message,$headers) ) {
   echo "The email has been sent!";
   } else {
   echo "The email has failed!";

Powershell: A positional parameter cannot be found that accepts argument "xxx"

I had to use

powershell.AddParameter("Identity", "complete id path with OU in it");

to get past this error

How to load URL in UIWebView in Swift?

in swift 5

import UIKit
import WebKit
class ViewController: UIViewController, WKUIDelegate {
   var webView: WKWebView!
   override func viewDidLoad() {
      let myURL = URL(string:"")
      let myRequest = URLRequest(url: myURL!)
   override func loadView() {
      let webConfiguration = WKWebViewConfiguration()
      webView = WKWebView(frame: .zero, configuration: webConfiguration)
      webView.uiDelegate = self
      view = webView

javax.naming.NameNotFoundException: Name is not bound in this Context. Unable to find

ugh, just to iterate over my own case, which gave out approximately the same error - in the Resource declaration (server.xml) make sure to NOT omit driverClassName, and that e.g. for Oracle it is "oracle.jdbc.OracleDriver", and that the right JAR file (e.g. ojdbc14.jar) exists in %CATALINA_HOME%/lib

nuget 'packages' element is not declared warning

None of the answers will solve your problem permanently. If you go to the path of adding XSD (From Xml menu, select "Create schema"), you will end up having problems with the package manager as it will clean up your packages.config file when you add a new package.

The best solution is just ignore by closing the file when you don't use it.

How to vertically align a html radio button to it's label?

Something like this should work


input {
    float: left;
    clear: left;
    width: 50px;
    line-height: 20px;

label {
    float: left;
    vertical-align: middle;

Random shuffling of an array

You can use java 8 now:

Collections.addAll(list, arr);

CSS transition when class removed

In my case i had some problem with opacity transition so this one fix it:

#dropdown {
    transition:.6s opacity;
#dropdown.ns {
    transition:.6s all;
#dropdown.fade {

Mouse Enter


Mouse Leave


How to concatenate and minify multiple CSS and JavaScript files with Grunt.js (0.3.x)

I want to mention here a very, VERY, interesting technique that is being used in huge projects like jQuery and Modernizr for concatenate things.

Both of this projects are entirely developed with requirejs modules (you can see that in their github repos) and then they use the requirejs optimizer as a very smart concatenator. The interesting thing is that, as you can see, nor jQuery neither Modernizr needs on requirejs to work, and this happen because they erase the requirejs syntatic ritual in order to get rid of requirejs in their code. So they end up with a standalone library that was developed with requirejs modules! Thanks to this they are able to perform cutsom builds of their libraries, among other advantages.

For all those interested in concatenation with the requirejs optimizer, check out this post

Also there is a small tool that abstracts all the boilerplate of the process: AlbanilJS

Windows command to get service status?

look also hier:

NET START | FIND "Service name" > nul IF errorlevel 1 ECHO The service is not running

just copied from:

How do I make a JSON object with multiple arrays?

A good book I'm reading: Professional JavaScript for Web Developers by Nicholas C. Zakas 3rd Edition has the following information regarding JSON Syntax:

"JSON Syntax allows the representation of three types of values".

Regarding the one you're interested in, Arrays it says:

"Arrays are represented in JSON using array literal notation from JavaScript. For example, this is an array in JavaScript:

var values = [25, "hi", true];

You can represent this same array in JSON using a similar syntax:

[25, "hi", true]

Note the absence of a variable or a semicolon. Arrays and objects can be used together to represent more complex collections of data, such as:

                    "title": "Professional JavaScript",
                    "authors": [
                        "Nicholas C. Zakas"
                    "edition": 3,
                    "year": 2011
                    "title": "Professional JavaScript",
                    "authors": [
                        "Nicholas C.Zakas"
                    "edition": 2,
                    "year": 2009
                    "title": "Professional Ajax",
                    "authors": [
                        "Nicholas C. Zakas",
                        "Jeremy McPeak",
                        "Joe Fawcett"
                    "edition": 2,
                    "year": 2008

This Array contains a number of objects representing books, Each object has several keys, one of which is "authors", which is another array. Objects and arrays are typically top-level parts of a JSON data structure (even though this is not required) and can be used to create a large number of data structures."

To serialize (convert) a JavaScript object into a JSON string you can use the JSON object stringify() method. For the example from Mark Linus answer:

var cars = [{
    color: 'gray',
    model: '1',
    nOfDoors: 4
    color: 'yellow',
    model: '2',
    nOfDoors: 4

cars is now a JavaScript object. To convert it into a JSON object you could do:

var jsonCars = JSON.stringify(cars);

Which yields:


To do the opposite, convert a JSON object into a JavaScript object (this is called parsing), you would use the parse() method. Search for those terms if you need more information... or get the book, it has many examples.

Visual Studio build fails: unable to copy exe-file from obj\debug to bin\debug

I'd suggest download Process Explorer to find out exactly what process is locking the file. It can be found at:

How to access the last value in a vector?

Combining lindelof's and Gregg Lind's ideas:

last <- function(x) { tail(x, n = 1) }

Working at the prompt, I usually omit the n=, i.e. tail(x, 1).

Unlike last from the pastecs package, head and tail (from utils) work not only on vectors but also on data frames etc., and also can return data "without first/last n elements", e.g.

but.last <- function(x) { head(x, n = -1) }

(Note that you have to use head for this, instead of tail.)

Resizing an image in an HTML5 canvas

The problem with some of this solutions is that they access directly the pixel data and loop through it to perform the downsampling. Depending on the size of the image this can be very resource intensive, and it would be better to use the browser's internal algorithms.

The drawImage() function is using a linear-interpolation, nearest-neighbor resampling method. That works well when you are not resizing down more than half the original size.

If you loop to only resize max one half at a time, the results would be quite good, and much faster than accessing pixel data.

This function downsample to half at a time until reaching the desired size:

  function resize_image( src, dst, type, quality ) {
     var tmp = new Image(),
         canvas, context, cW, cH;

     type = type || 'image/jpeg';
     quality = quality || 0.92;

     cW = src.naturalWidth;
     cH = src.naturalHeight;

     tmp.src = src.src;
     tmp.onload = function() {

        canvas = document.createElement( 'canvas' );

        cW /= 2;
        cH /= 2;

        if ( cW < src.width ) cW = src.width;
        if ( cH < src.height ) cH = src.height;

        canvas.width = cW;
        canvas.height = cH;
        context = canvas.getContext( '2d' );
        context.drawImage( tmp, 0, 0, cW, cH );

        dst.src = canvas.toDataURL( type, quality );

        if ( cW <= src.width || cH <= src.height )

        tmp.src = dst.src;

  // The images sent as parameters can be in the DOM or be image objects
  resize_image( $( '#original' )[0], $( '#smaller' )[0] );

Credits to this post

JSF(Primefaces) ajax update of several elements by ID's

If the to-be-updated component is not inside the same NamingContainer component (ui:repeat, h:form, h:dataTable, etc), then you need to specify the "absolute" client ID. Prefix with : (the default NamingContainer separator character) to start from root.

<p:ajax process="@this" update="count :subTotal"/>

To be sure, check the client ID of the subTotal component in the generated HTML for the actual value. If it's inside for example a h:form as well, then it's prefixed with its client ID as well and you would need to fix it accordingly.

<p:ajax process="@this" update="count :formId:subTotal"/>

Space separation of IDs is more recommended as <f:ajax> doesn't support comma separation and starters would otherwise get confused.

Endless loop in C/C++

Everyone seems to like while (true):

According to SLaks, they compile identically.

Ben Zotto also says it doesn't matter:

It's not faster. If you really care, compile with assembler output for your platform and look to see. It doesn't matter. This never matters. Write your infinite loops however you like.

In response to user1216838, here's my attempt to reproduce his results.

Here's my machine:

cat /etc/*-release
CentOS release 6.4 (Final)

gcc version:

Target: x86_64-unknown-linux-gnu
Thread model: posix
gcc version 4.8.2 (GCC)

And test files:

// testing.cpp
#include <iostream>

int main() {
    do { break; } while(1);

// testing2.cpp
#include <iostream>

int main() {
    while(1) { break; }

// testing3.cpp
#include <iostream>

int main() {
    while(true) { break; }

The commands:

gcc -S -o test1.asm testing.cpp
gcc -S -o test2.asm testing2.cpp
gcc -S -o test3.asm testing3.cpp

cmp test1.asm test2.asm

The only difference is the first line, aka the filename.

test1.asm test2.asm differ: byte 16, line 1


        .file   "testing2.cpp"
        .local  _ZStL8__ioinit
        .comm   _ZStL8__ioinit,1,1
        .globl  main
        .type   main, @function
        pushq   %rbp
        .cfi_def_cfa_offset 16
        .cfi_offset 6, -16
        movq    %rsp, %rbp
        .cfi_def_cfa_register 6
        movl    $0, %eax
        popq    %rbp
        .cfi_def_cfa 7, 8
        .size   main, .-main
        .type   _Z41__static_initialization_and_destruction_0ii, @function
        pushq   %rbp
        .cfi_def_cfa_offset 16
        .cfi_offset 6, -16
        movq    %rsp, %rbp
        .cfi_def_cfa_register 6
        subq    $16, %rsp
        movl    %edi, -4(%rbp)
        movl    %esi, -8(%rbp)
        cmpl    $1, -4(%rbp)
        jne     .L3
        cmpl    $65535, -8(%rbp)
        jne     .L3
        movl    $_ZStL8__ioinit, %edi
        call    _ZNSt8ios_base4InitC1Ev
        movl    $__dso_handle, %edx
        movl    $_ZStL8__ioinit, %esi
        movl    $_ZNSt8ios_base4InitD1Ev, %edi
        call    __cxa_atexit
        .cfi_def_cfa 7, 8
        .size   _Z41__static_initialization_and_destruction_0ii, .-_Z41__static_initialization_and_destruction_0ii
        .type   _GLOBAL__sub_I_main, @function
        pushq   %rbp
        .cfi_def_cfa_offset 16
        .cfi_offset 6, -16
        movq    %rsp, %rbp
        .cfi_def_cfa_register 6
        movl    $65535, %esi
        movl    $1, %edi
        call    _Z41__static_initialization_and_destruction_0ii
        popq    %rbp
        .cfi_def_cfa 7, 8
        .size   _GLOBAL__sub_I_main, .-_GLOBAL__sub_I_main
        .section        .ctors,"aw",@progbits
        .align 8
        .quad   _GLOBAL__sub_I_main
        .hidden __dso_handle
        .ident  "GCC: (GNU) 4.8.2"
        .section        .note.GNU-stack,"",@progbits

With -O3, the output is considerably smaller of course, but still no difference.

How to get response body using HttpURLConnection, when code other than 2xx is returned?

This is an easy way to get a successful response from the server like PHP echo otherwise an error message.

BufferedReader br = null;
if (conn.getResponseCode() == 200) {
    br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String strCurrentLine;
        while ((strCurrentLine = br.readLine()) != null) {
} else {
    br = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
    String strCurrentLine;
        while ((strCurrentLine = br.readLine()) != null) {

How to merge every two lines into one from the command line?

"ex" is a scriptable line editor that is in the same family as sed, awk, grep, etc. I think it might be what you are looking for. Many modern vi clone/successors also have a vi mode.

 ex -c "%g/KEY/j" -c "wq" data.txt

This says for each line, if it matches "KEY" perform a j oin of the following line. After that command completes (against all lines), issue a w rite and q uit.

How can I plot data with confidence intervals?

Here is a plotrix solution:

x <- 1:10
F <- runif(10,1,2) 
L <- runif(10,0,1)
U <- runif(10,2,3)

plotCI(x, F, ui=U, li=L)

enter image description here

And here is a ggplot solution:

df <- data.frame(x =1:10,
                 F =runif(10,1,2),
                 L =runif(10,0,1),
                 U =runif(10,2,3))

ggplot(df, aes(x = x, y = F)) +
  geom_point(size = 4) +
  geom_errorbar(aes(ymax = U, ymin = L))

enter image description here

UPDATE: Here is a base solution to your edits:

x <- rnorm(20)
df <- data.frame(x = x,
                 y = x + rnorm(20))

plot(y ~ x, data = df)

# model
mod <- lm(y ~ x, data = df)

# predicts + interval
newx <- seq(min(df$x), max(df$x), length.out=100)
preds <- predict(mod, newdata = data.frame(x=newx), 
                 interval = 'confidence')

# plot
plot(y ~ x, data = df, type = 'n')
# add fill
polygon(c(rev(newx), newx), c(rev(preds[ ,3]), preds[ ,2]), col = 'grey80', border = NA)
# model
# intervals
lines(newx, preds[ ,3], lty = 'dashed', col = 'red')
lines(newx, preds[ ,2], lty = 'dashed', col = 'red')

enter image description here

PHP mailer multiple address

You need to call the AddAddress method once for every recipient. Like so:

$mail->AddAddress('[email protected]', 'Person One');
$mail->AddAddress('[email protected]', 'Person Two');
// ..

Better yet, add them as Carbon Copy recipients.

$mail->AddCC('[email protected]', 'Person One');
$mail->AddCC('[email protected]', 'Person Two');
// ..

To make things easy, you should loop through an array to do this.

$recipients = array(
   '[email protected]' => 'Person One',
   '[email protected]' => 'Person Two',
   // ..
foreach($recipients as $email => $name)
   $mail->AddCC($email, $name);

Append column to pandas dataframe

You can also use:

dat1 = pd.concat([dat1, dat2], axis=1)

UTF-8 encoding problem in Spring MVC

When you try to send special characters like è,à,ù, etc etc, may be you see in your Jsp Post page many characters like '£','Ä’ or ‘Æ’. To solve this problem in 99% of cases you may move in your web.xml this piece of code at the head of file:


For complete example see here :

Circle line-segment collision detection algorithm?

Weirdly I can answer but not comment... I liked Multitaskpro's approach of shifting everything to make the centre of the circle fall on the origin. Unfortunately there are two problems in his code. First in the under-the-square-root part you need to remove the double power. So not:

var underRadical = Math.pow((Math.pow(r,2)*(Math.pow(m,2)+1)),2)-Math.pow(b,2));


var underRadical = Math.pow(r,2)*(Math.pow(m,2)+1)) - Math.pow(b,2);

In the final coordinates he forgets to shift the solution back. So not:

var i1 = {x:t1,y:m*t1+b}


var i1 = {x:t1+c.x, y:m*t1+b+c.y};

The whole function then becomes:

function interceptOnCircle(p1, p2, c, r) {
    //p1 is the first line point
    //p2 is the second line point
    //c is the circle's center
    //r is the circle's radius

    var p3 = {x:p1.x - c.x, y:p1.y - c.y}; //shifted line points
    var p4 = {x:p2.x - c.x, y:p2.y - c.y};

    var m = (p4.y - p3.y) / (p4.x - p3.x); //slope of the line
    var b = p3.y - m * p3.x; //y-intercept of line

    var underRadical = Math.pow(r,2)*Math.pow(m,2) + Math.pow(r,2) - Math.pow(b,2); //the value under the square root sign 

    if (underRadical < 0) {
        //line completely missed
        return false;
    } else {
        var t1 = (-m*b + Math.sqrt(underRadical))/(Math.pow(m,2) + 1); //one of the intercept x's
        var t2 = (-m*b - Math.sqrt(underRadical))/(Math.pow(m,2) + 1); //other intercept's x
        var i1 = {x:t1+c.x, y:m*t1+b+c.y}; //intercept point 1
        var i2 = {x:t2+c.x, y:m*t2+b+c.y}; //intercept point 2
        return [i1, i2];

MySQL Select all columns from one table and some from another table

Just use the table name:

SELECT myTable.*,,

That would select all columns from myTable and columns foo and bar from otherTable.

Execution Failed for task :app:compileDebugJavaWithJavac in Android Studio

I faced a similar problem, but I had to set manually the jdk folder on program files, so I recommend to everybody specially the ones that are upgrading to java 8, to point directly in the project settings of the android studio, either using the embed option or choosing the folder

What is the difference between a "function" and a "procedure"?

In most contexts: a function returns a value, while a procedure doesn't. Both are pieces of code grouped together to do the same thing.

In functional programming context (where all functions return values), a function is an abstract object:


Here, f is the same function as g, but is a different procedure.

How can I use LTRIM/RTRIM to search and replace leading/trailing spaces?

LTrim function and RTrim function :

  • The LTrim function to remove leading spaces and the RTrim function to remove trailing spaces from a string variable.
  • It uses the Trim function to remove both types of spaces.

                  select LTRIM(RTRIM(' SQL Server '))


                             SQL Server

Java balanced expressions check {[()]}

Do you mind, if I will add my freaky-style solution based on JavaScript?

It's an ad-hoc stuff, not for production, but for the interviews or something like that. Or just for fun.

The code:

function reduceStr (str) {
  const newStr = str.replace('()', '').replace('{}', '').replace('[]', '')
  if (newStr !== str) return reduceStr(newStr)
  return newStr

function verifyNesting (str) {
  return reduceStr(str).length === 0


console.log(verifyNesting('[{{[(){}]}}[]{}{{(())}}]')) //correct
console.log(verifyNesting('[{{[(){}]}}[]{}{({())}}]')) //incorrect


It will recursively remove closes pairs "()", "[]" and "{}":


If at the end string's length will be empty - it's true, if not - it's false.

P.S. Few answers

  • Why not for production?

Because it's slow, and don't care about the possibility of some other characters between pairs.

  • Why JS? We love Java

Because I'm a frontend developer but met the same task, so perhaps it can be useful for somebody. And JS is also JVM lang =)

  • But why...

Because all JS developers are crazy, that's why.

Django upgrading to 1.9 error "AppRegistryNotReady: Apps aren't loaded yet."

I tried tons of things, but only downgrading Django to 1.8.18 fixed this issue for me:

pip install django==1.8.18

It is one of the installed apps that is failing, but I could not find which one.

Adding a public key to ~/.ssh/authorized_keys does not log me in automatically

Make sure you've copied the whole public key to authorized_keys; the ssh rsa prefix is necessary for the key to work.

Capturing a form submit with jquery and .submit

Just replace the form.submit function with your own implementation:

var form = document.getElementById('form');
var formSubmit = form.submit; //save reference to original submit function

form.onsubmit = function(e)
    return false;

var formHandler = form.submit = function()
    alert('hi there');
    formSubmit(); //optionally submit the form

converting date time to 24 hour format

With Calendar it works as follows:

    //create first Calendar object
    Calendar calendar = Calendar.getInstance();

    calendar.set(Calendar.HOUR_OF_DAY, 15); // 3 PM
    // the same is
    calendar.set(Calendar.AM_PM, Calendar.PM); // choose PM mode
    calendar.set(Calendar.HOUR, 3); // 3 PM

    System.out.println( calendar.get(Calendar.HOUR) ); // AM_PM format
    System.out.println( calendar.get(Calendar.HOUR_OF_DAY) ); // 0-23 format

RelativeLayout center vertical


            android:src="@drawable/google" />

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

How organize uploaded media in WP?

Currently, media organisation is possible.

The "problem" with the media library in wordpress is always interesting. Check the following plugin to solve this: WordPress Real Media Library. WP RML creates a virtual folder structure based on an own taxonomy.

Drag & Drop your files

It allows you to organize your wordpress media library in a nice way with folders. It is easy to use, just drag&drop your files and move it to a specific folder. Filter when inserting media or create a gallery from a folder.

Turn your WordPress media library to the next level with folders / categories. Get organized with thousands of images.

RML (Real Media Library) is one of the most wanted media wordpress plugins. It is easy to use and it allows you to organize your thousands of images in folders. It is similar to wordpress categories like in the posts.

Use your mouse (or touch) to drag and drop your files. Create, rename, delete or reorder your folders If you want to select a image from the “Select a image”-dialog (e. g. featured image) you can filter when inserting media. Just install this plugin and it works fine with all your image and media files. It also supports multisite.

If you buy, you get: Forever FREE updates and high quality and fast support.

From the product description i can quote. If you want to try the plugin, there is also a demo on the plugin page.

Update #1 (2017-01-27): Manage your uploads physically

A long time ago I started to open this thread and now there is a usable extension plugin for Real Media Library which allows you to physically manage your uploads folder.

enter image description here

Check out this plugin:

Do you know the wp-content/uploads folder? There, the files are stored in year/month based folders. This can be a very complicated and mass process, especially when you are working with a FTP client like FileZilla.

Moving already uploaded files: This plugin does not allow to move the files physically when you move a file in the Real Media Library because WordPress uses the URL's in different places. It is very hard to maintain such a process. So this only works for new uploads.

Physical organisation on server?

(Please read on if you are developer) I as developer thought about a solution about this. Does it make sense to organize the uploads on server, too? Yes, i think. Many people ask to organize it physically. I think also that the process of moving files on server and updating the image references is very hard to develop. There are many plugins out now, which are saving the URLs in their own-created database-tables.

Please check this thread where i explained the problem:

Code for best fit straight line of a scatter plot in python

from sklearn.linear_model import LinearRegression

X, Y = x.reshape(-1,1), y.reshape(-1,1)
plt.plot( X, LinearRegression().fit(X, Y).predict(X) )

'Static readonly' vs. 'const'

A few more relevant things to be noted:

const int a

  • must be initialized.
  • initialization must be at compile time.

readonly int a

  • can use a default value, without initializing.
  • initialization can be done at run time (Edit: within constructor only).

Navigation bar show/hide

This code will help you.

UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] 
initWithTarget:self action:@selector(showHideNavbar:)];
[self.view addGestureRecognizer:tapGesture];

-(void) showHideNavbar:(id) sender 
// write code to show/hide nav bar here 
// check if the Navigation Bar is shown
if (self.navigationController.navigationBar.hidden == NO)
// hide the Navigation Bar
[self.navigationController setNavigationBarHidden:YES animated:YES];
// if Navigation Bar is already hidden
else if (self.navigationController.navigationBar.hidden == YES)
// Show the Navigation Bar
[self.navigationController setNavigationBarHidden:NO animated:YES];

How to use the read command in Bash?

The read in your script command is fine. However, you execute it in the pipeline, which means it is in a subshell, therefore, the variables it reads to are not visible in the parent shell. You can either

  • move the rest of the script in the subshell, too:

    echo hello | { read str
      echo $str
  • or use command substitution to get the value of the variable out of the subshell

    str=$(echo hello)
    echo $str

    or a slightly more complicated example (Grabbing the 2nd element of ls)

    str=$(ls | { read a; read a; echo $a; })
    echo $str

XAMPP - Error: MySQL shutdown unexpectedly

I am new to XAMPP, but I find that a combination of these suggestions works best (At least on Windows 8.1 with the latest version of XAMPP. Note that the computer I tested this on, also had skype).

First logon to skype and navigate to "Tools < Options < Advanced < Connection." Then check the box that says "Use port 80 and 443 for additional incoming connections." Save, close, and quit skype.

Next, on your XAMPP control panel, click "config < my.ini" and change lines 19 and 27 (should have port = 3306) from "3306" to "3307."

Also, you will need to navigate to xampp < phpMyAdmin < and change line 27, which should like something like this:

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

You will need to add "3307" as follows:

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

Now, open your browser and you should see the xampp page when you type in "localhost." Additionally, if this is your first time using xampp, you may see a warning about your lack of password (highlighted in pink) on your localhost/phpmyadmin/ page. This is easily remedied by going to the "user accounts" tab in phpmyadmin, clicking on "edit privileges" and entering password. Remember to save the hashed version of any and all passwords you create as we will use this next! -I opened a notepad and saved (and numbered) them. Note that phpMyadmin will notify you of when you are changing the password for your current session (this will be displayed at the top of your phpMyadmin page and is very important, as you will need THAT specific hashed version of your password).

Next, you will need to navigate to the following location "xampp < phpMyAdmin <" on your computer and open and edit the file with a text editor. You will want to put in the hashed version of your password between the single quotes for password and change "AllowNoPassword" from true to false.

And, that ought to do it.

What is the ellipsis (...) for in this method signature?

The three dot (...) notation is actually borrowed from mathematics, and it means "...and so on".

As for its use in Java, it stands for varargs, meaning that any number of arguments can be added to the method call. The only limitations are that the varargs must be at the end of the method signature and there can only be one per method.

How can I check if a view is visible or not in Android?

Although View.getVisibility() does get the visibility, its not a simple true/false. A view can have its visibility set to one of three things.

View.VISIBLE The view is visible.

View.INVISIBLE The view is invisible, but any spacing it would normally take up will still be used. Its "invisible"

View.GONE The view is gone, you can't see it and it doesn't take up the "spot".

So to answer your question, you're looking for:

if (myImageView.getVisibility() == View.VISIBLE) {
    // Its visible
} else {
    // Either gone or invisible

check / uncheck checkbox using jquery?

You can use prop() for this, as Before jQuery 1.6, the .attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.

var prop=false;
if(value == 1) {

or simply,

$('#checkbox').prop('checked',(value == 1));


$(document).ready(function() {_x000D_
  var chkbox = $('.customcheckbox');_x000D_
  $(".customvalue").keyup(function() {_x000D_
    chkbox.prop('checked', this.value==1);_x000D_
<script src=""></script>_x000D_
<h4>This is a domo to show check box is checked_x000D_
if you enter value 1 else check box will be unchecked </h4>_x000D_
Enter a value:_x000D_
<input type="text" value="" class="customvalue">_x000D_
<br>checkbox output :_x000D_
<input type="checkbox" class="customcheckbox">

Exception of type 'System.OutOfMemoryException' was thrown. Why?

Perhaps you're not disposing of the previous connection/ result classes from the previous run which means their still hanging around in memory.

Tree implementation in Java (root, parents and children)

Here is my implementation in java for your requirement. In the treeNode class i used generic array to store the tree data. we can also use arraylist or dynamic array to store the tree value.

public class TreeNode<T> {
   private T value = null;
   private TreeNode[] childrens = new TreeNode[100];
   private int childCount = 0;

    TreeNode(T value) {
        this.value = value;

    public TreeNode addChild(T value) {
        TreeNode newChild = new TreeNode(value, this);
        childrens[childCount++] = newChild;
        return newChild;

    static void traverse(TreeNode obj) {
        if (obj != null) {
            for (int i = 0; i < obj.childCount; i++) {

    void printTree(TreeNode obj) {

And the client class for the above implementation.

public class Client {
    public static void main(String[] args) {
        TreeNode menu = new TreeNode("Menu");
        TreeNode item = menu.addChild("Starter");
            item = item.addChild("Veg");
                item.addChild("Paneer Tikka");
                item.addChild("Malai Paneer Tikka");
            item = item.addChild("Non-veg");
                item.addChild("Chicken Tikka");
                item.addChild("Malai Chicken Tikka");
        item = menu.addChild("Main Course");
            item = item.addChild("Veg");
                item.addChild("Mili Juli Sabzi");
                item.addChild("Aloo Shimla Mirch");
            item = item.addChild("Non-veg");
                item.addChild("Chicken Do Pyaaza");
                item.addChild("Chicken Chettinad");
        item = menu.addChild("Desserts");
                item = item.addChild("Cakes");
                        item.addChild("Black Forest");
                        item.addChild("Black Current");
                item = item.addChild("Ice Creams");


Paneer Tikka                                                        
Malai Paneer Tikka                                                    
Chicken Tikka                                                      
Malai Chicken Tikka                                                 
Main Course                                                      
Mili Juli Sabzi                                                   
Aloo Shimla Mirch                                                  
Chicken Do Pyaaza                                                   
Chicken Chettinad                                                    
Black Forest                                                     
Black Current                                                   
Ice Creams                                                      

MySQL Query to select data from last week?

i Use this for the week start from SUNDAY:

date >= curdate() - INTERVAL DAYOFWEEK(curdate())+5 DAY  
AND date < curdate() - INTERVAL DAYOFWEEK(curdate())-2 DAY

Delete default value of an input text on click

we can do it without using js in the following way using the "placeholder" attribute of html5 ( the default text disappears when the user starts to type in ,but not on just clicking )

<input type="email" id="email" placeholder="[email protected]">

see this:

Displaying tooltip on mouse hover of a text


ToolTip tip = new ToolTip();
private void richTextBox1_MouseMove(object sender, MouseEventArgs e)
    Cursor a = System.Windows.Forms.Cursor.Current;
    if (a == Cursors.Hand)
        Point p = richTextBox1.Location;
            p.X + e.X,
            p.Y + e.Y + 32,

Use the GetWord function from my other answer to get the hovered word. Use timer logic to disable reshow the tooltip as in prev. example.

In this example right above, the tool tip shows the hovered word by checking the mouse pointer.

If this answer is still not what you are looking fo, please specify the condition that characterizes the word you want to use tooltip on. If you want it for bolded word, please tell me.

Correct file permissions for WordPress

For those who have their wordpress root folder under their home folder:

** Ubuntu/apache

  1. Add your user to www-data group:

CREDIT Granting write permissions to www-data group

You want to call usermod on your user. So that would be:

sudo usermod -aG www-data yourUserName

** Assuming www-data group exists

  1. Check your user is in www-data group:

    groups yourUserName

You should get something like:

youUserName : youUserGroupName www-data

** youUserGroupName is usually similar to you user name

  1. Recursively change group ownership of the wp-content folder keeping your user ownership

    chown yourUserName:www-data -R youWebSiteFolder/wp-content/*

  2. Change directory to youWebSiteFolder/wp-content/

    cd youWebSiteFolder/wp-content

  3. Recursively change group permissions of the folders and sub-folders to enable write permissions:

    find . -type d -exec chmod -R 775 {} \;

** mode of `/home/yourUserName/youWebSiteFolder/wp-content/' changed from 0755 (rwxr-xr-x) to 0775 (rwxrwxr-x)

  1. Recursively change group permissions of the files and sub-files to enable write permissions:

    find . -type f -exec chmod -R 664 {} \;

The result should look something like:

-rw-r--r--  1 yourUserName www-data  7192 Oct  4 00:03 filename.html
-rw-rw-r--  1 yourUserName www-data  7192 Oct  4 00:03 filename.html

Equivalent to:

chmod -R ug+rw foldername

Permissions will be like 664 for files or 775 for directories.

P.s. if anyone encounters error 'could not create directory' when updating a plugin, do:
server@user:~/$ sudo chown username:www-data -R wp-content
when you are at the root of your domain.
Assuming: wp-config.php has
FTP credentials on LocalHost

How to reference a method in javadoc?

The general format, from the @link section of the javadoc documentation, is:

{@link package.class#member label}


Method in the same class:

/** See also {@link #myMethod(String)}. */
void foo() { ... }

Method in a different class, either in the same package or imported:

/** See also {@link MyOtherClass#myMethod(String)}. */
void foo() { ... }

Method in a different package and not imported:

/** See also {@link com.mypackage.YetAnotherClass#myMethod(String)}. */
void foo() { ... }

Label linked to method, in plain text rather than code font:

/** See also this {@linkplain #myMethod(String) implementation}. */
void foo() { ... }

A chain of method calls, as in your question. We have to specify labels for the links to methods outside this class, or we get getFoo().Foo.getBar().Bar.getBaz(). But these labels can be fragile during refactoring -- see "Labels" below.

 * A convenience method, equivalent to 
 * {@link #getFoo()}.{@link Foo#getBar() getBar()}.{@link Bar#getBaz() getBaz()}.
 * @return baz
public Baz fooBarBaz()


Automated refactoring may not affect labels. This includes renaming the method, class or package; and changing the method signature.

Therefore, provide a label only if you want different text than the default.

For example, you might link from human language to code:

/** You can also {@linkplain #getFoo() get the current foo}. */
void setFoo( Foo foo ) { ... }

Or you might link from a code sample with text different than the default, as shown above under "A chain of method calls." However, this can be fragile while APIs are evolving.

Type erasure and #member

If the method signature includes parameterized types, use the erasure of those types in the javadoc @link. For example:

int bar( Collection<Integer> receiver ) { ... }

/** See also {@link #bar(Collection)}. */
void foo() { ... }

How do I find Waldo with Mathematica?

I have a quick solution for finding Waldo using OpenCV.

I used the template matching function available in OpenCV to find Waldo.

To do this a template is needed. So I cropped Waldo from the original image and used it as a template.

enter image description here

Next I called the cv2.matchTemplate() function along with the normalized correlation coefficient as the method used. It returned a high probability at a single region as shown in white below (somewhere in the top left region):

enter image description here

The position of the highest probable region was found using cv2.minMaxLoc() function, which I then used to draw the rectangle to highlight Waldo:

enter image description here

How to change status bar color to match app in Lollipop? [Android]

Also if you want different status-bar color for different activity (fragments) you can do it with following steps (work on API 21 and above):

First create values21/style.xml and put following code:

 <style name="AIO" parent="AIOBase">
            <item name="android:windowDrawsSystemBarBackgrounds">true</item>
            <item name="android:windowContentTransitions">true</item>

Then define White|Dark themes in your values/style.xml like following:

 <style name="AIOBase" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="colorPrimary">@color/color_primary</item>
        <item name="colorPrimaryDark">@color/color_primary_dark</item>
        <item name="colorAccent">@color/color_accent</item>
        <item name="android:textColorPrimary">@android:color/black</item>
        <item name="android:statusBarColor" tools:targetApi="lollipop">@color/color_primary_dark
        <item name="android:textColor">@color/gray_darkest</item>
        <item name="android:windowBackground">@color/default_bg</item>
        <item name="android:colorBackground">@color/default_bg</item>

    <style name="AIO" parent="AIOBase" />

    <style name="AIO.Dark" parent="AIOBase">
        <item name="android:statusBarColor" tools:targetApi="lollipop">#171717

    <style name="AIO.White" parent="AIOBase">
        <item name="android:statusBarColor" tools:targetApi="lollipop">#bdbdbd

Also don't forget to apply themes in your manifest.xml.

what is Array.any? for javascript

I believe this to be the cleanest and readable option:

var empty = [];
empty.some(x => x); //returns false