Programs & Examples On #Hierarchical

For issues relating to arranging data and/or resources in a hierarchy.

Angular ForEach in Angular4/Typescript?

In Typescript use the For Each like below.

selectChildren(data, $event) {
let parentChecked = data.checked;
for(var obj in this.hierarchicalData)
    {
        for (var childObj in obj )
        {
            value.checked = parentChecked;
        }
    }
}

How to loop and render elements in React.js without an array of objects to map?

Array.from() takes an iterable object to convert to an array and an optional map function. You could create an object with a .length property as follows:

return Array.from({length: this.props.level}, (item, index) => 
  <span className="indent" key={index}></span>
);

Make sure that the controller has a parameterless public constructor error

I had the same problem. I googled it for two days. At last I accidentally noticed that the problem was access modifier of the constructor of the Controller. I didn’t put the public key word behind the Controller’s constructor.

public class MyController : ApiController
    {
        private readonly IMyClass _myClass;

        public MyController(IMyClass myClass)
        {
            _myClass = myClass;
        }
    }

I add this experience as another answer maybe someone else made a similar mistake.

pandas three-way joining multiple dataframes on columns

The three dataframes are

enter image description here

enter image description here

Let's merge these frames using nested pd.merge

enter image description here

Here we go, we have our merged dataframe.

Happy Analysis!!!

How can I add a table of contents to a Jupyter / JupyterLab notebook?

Here is my approach, clunky as it is and available in github:

Put in the very first notebook cell, the import cell:

from IPythonTOC import IPythonTOC

toc = IPythonTOC()

Somewhere after the import cell, put in the genTOCEntry cell but don't run it yet:

''' if you called toc.genTOCMarkdownCell before running this cell, 
the title has been set in the class '''

print toc.genTOCEntry()

Below the genTOCEntry cell`, make a TOC cell as a markdown cell:

<a id='TOC'></a>

#TOC

As the notebook is developed, put this genTOCMarkdownCell before starting a new section:

with open('TOCMarkdownCell.txt', 'w') as outfile:

    outfile.write(toc.genTOCMarkdownCell('Introduction'))

!cat TOCMarkdownCell.txt

!rm TOCMarkdownCell.txt

Move the genTOCMarkdownCell down to the point in your notebook where you want to start a new section and make the argument to genTOCMarkdownCell the string title for your new section then run it. Add a markdown cell right after it and copy the output from genTOCMarkdownCell into the markdown cell that starts your new section. Then go to the genTOCEntry cell near the top of your notebook and run it. For example, if you make the argument to genTOCMarkdownCell as shown above and run it, you get this output to paste into the first markdown cell of your newly indexed section:

<a id='Introduction'></a>

###Introduction

Then when you go to the top of your notebook and run genTocEntry, you get the output:

[Introduction](#Introduction)

Copy this link string and paste it into the TOC markdown cell as follows:

<a id='TOC'></a>

#TOC

[Introduction](#Introduction)

After you edit the TOC cell to insert the link string and then you press shift-enter, the link to your new section will appear in your notebook Table of Contents as a web link and clicking it will position the browser to your new section.

One thing I often forget is that clicking a line in the TOC makes the browser jump to that cell but doesn't select it. Whatever cell was active when we clicked on the TOC link is still active, so a down or up arrow or shift-enter refers to still active cell, not the cell we got by clicking on the TOC link.

Woocommerce get products

Always use tax_query to get posts/products from a particular category or any other taxonomy. You can also get the products using ID/slug of particular taxonomy...

$the_query = new WP_Query( array(
    'post_type' => 'product',
    'tax_query' => array(
        array (
            'taxonomy' => 'product_cat',
            'field' => 'slug',
            'terms' => 'accessories',
        )
    ),
) );

while ( $the_query->have_posts() ) :
    $the_query->the_post();
    the_title(); echo "<br>";
endwhile;


wp_reset_postdata();

Reading a resource file from within jar

You can use class loader which will read from classpath as ROOT path (without "/" in the beginning)

InputStream in = getClass().getClassLoader().getResourceAsStream("file.txt"); 
BufferedReader reader = new BufferedReader(new InputStreamReader(in));

How to create a MySQL hierarchical recursive query?

Did the same thing for another quetion here

Mysql select recursive get all child with multiple level

The query will be :

SELECT GROUP_CONCAT(lv SEPARATOR ',') FROM (
  SELECT @pv:=(
    SELECT GROUP_CONCAT(id SEPARATOR ',')
    FROM table WHERE parent_id IN (@pv)
  ) AS lv FROM table 
  JOIN
  (SELECT @pv:=1)tmp
  WHERE parent_id IN (@pv)
) a;

How to get coordinates of an svg element?

svg.selectAll("rect")
.attr('x',function(d,i){
    // get x coord
    console.log(this.getBBox().x, 'or', d3.select(this).attr('x'))
})
.attr('y',function(d,i){
    // get y coord
    console.log(this.getBBox().y)
})
.attr('dx',function(d,i){
    // get dx coord
    console.log(parseInt(d3.select(this).attr('dx')))
})

How to get raw text from pdf file using java

For the newer versions of Apache pdfbox. Here is the example from the original source

/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.pdfbox.examples.util;

import java.io.File;
import java.io.IOException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.encryption.AccessPermission;
import org.apache.pdfbox.text.PDFTextStripper;

/**
 * This is a simple text extraction example to get started. For more advance usage, see the
 * ExtractTextByArea and the DrawPrintTextLocations examples in this subproject, as well as the
 * ExtractText tool in the tools subproject.
 *
 * @author Tilman Hausherr
 */
public class ExtractTextSimple
{
    private ExtractTextSimple()
    {
        // example class should not be instantiated
    }

    /**
     * This will print the documents text page by page.
     *
     * @param args The command line arguments.
     *
     * @throws IOException If there is an error parsing or extracting the document.
     */
    public static void main(String[] args) throws IOException
    {
        if (args.length != 1)
        {
            usage();
        }

        try (PDDocument document = PDDocument.load(new File(args[0])))
        {
            AccessPermission ap = document.getCurrentAccessPermission();
            if (!ap.canExtractContent())
            {
                throw new IOException("You do not have permission to extract text");
            }

            PDFTextStripper stripper = new PDFTextStripper();

            // This example uses sorting, but in some cases it is more useful to switch it off,
            // e.g. in some files with columns where the PDF content stream respects the
            // column order.
            stripper.setSortByPosition(true);

            for (int p = 1; p <= document.getNumberOfPages(); ++p)
            {
                // Set the page interval to extract. If you don't, then all pages would be extracted.
                stripper.setStartPage(p);
                stripper.setEndPage(p);

                // let the magic happen
                String text = stripper.getText(document);

                // do some nice output with a header
                String pageStr = String.format("page %d:", p);
                System.out.println(pageStr);
                for (int i = 0; i < pageStr.length(); ++i)
                {
                    System.out.print("-");
                }
                System.out.println();
                System.out.println(text.trim());
                System.out.println();

                // If the extracted text is empty or gibberish, please try extracting text
                // with Adobe Reader first before asking for help. Also read the FAQ
                // on the website: 
                // https://pdfbox.apache.org/2.0/faq.html#text-extraction
            }
        }
    }

    /**
     * This will print the usage for this document.
     */
    private static void usage()
    {
        System.err.println("Usage: java " + ExtractTextSimple.class.getName() + " <input-pdf>");
        System.exit(-1);
    }
}

Build tree array from flat array in javascript

You can use this "treeify" package from Github here or NPM.

Installation:

$ npm install --save-dev treeify-js

Recursively looping through an object to build a property list

With a little help from lodash...

/**
 * For object (or array) `obj`, recursively search all keys
 * and generate unique paths for every key in the tree.
 * @param {Object} obj
 * @param {String} prev
 */
export const getUniqueKeyPaths = (obj, prev = '') => _.flatten(
  Object
  .entries(obj)
  .map(entry => {
    const [k, v] = entry
    if (v !== null && typeof v === 'object') {
      const newK = prev ? `${prev}.${k}` : `${k}`
      // Must include the prev and current k before going recursive so we don't lose keys whose values are arrays or objects
      return [newK, ...getUniqueKeyPaths(v, newK)]
    }
    return `${prev}.${k}`
  })
)

Pandas - How to flatten a hierarchical index in columns

You could also do as below. Consider df to be your dataframe and assume a two level index (as is the case in your example)

df.columns = [(df.columns[i][0])+'_'+(datadf_pos4.columns[i][1]) for i in range(len(df.columns))]

Absolute position of an element on the screen using jQuery

BTW, if anyone want to get coordinates of element on screen without jQuery, please try this:

function getOffsetTop (el) {
    if (el.offsetParent) return el.offsetTop + getOffsetTop(el.offsetParent)
    return el.offsetTop || 0
}
function getOffsetLeft (el) {
    if (el.offsetParent) return el.offsetLeft + getOffsetLeft(el.offsetParent)
    return el.offsetleft || 0
}
function coordinates(el) {
    var y1 = getOffsetTop(el) - window.scrollY;
    var x1 = getOffsetLeft(el) - window.scrollX; 
    var y2 = y1 + el.offsetHeight;
    var x2 = x1 + el.offsetWidth;
    return {
        x1: x1, x2: x2, y1: y1, y2: y2
    }
}

Construct pandas DataFrame from items in nested dictionary

So I used to use a for loop for iterating through the dictionary as well, but one thing I've found that works much faster is to convert to a panel and then to a dataframe. Say you have a dictionary d

import pandas as pd
d
{'RAY Index': {datetime.date(2014, 11, 3): {'PX_LAST': 1199.46,
'PX_OPEN': 1200.14},
datetime.date(2014, 11, 4): {'PX_LAST': 1195.323, 'PX_OPEN': 1197.69},
datetime.date(2014, 11, 5): {'PX_LAST': 1200.936, 'PX_OPEN': 1195.32},
datetime.date(2014, 11, 6): {'PX_LAST': 1206.061, 'PX_OPEN': 1200.62}},
'SPX Index': {datetime.date(2014, 11, 3): {'PX_LAST': 2017.81,
'PX_OPEN': 2018.21},
datetime.date(2014, 11, 4): {'PX_LAST': 2012.1, 'PX_OPEN': 2015.81},
datetime.date(2014, 11, 5): {'PX_LAST': 2023.57, 'PX_OPEN': 2015.29},
datetime.date(2014, 11, 6): {'PX_LAST': 2031.21, 'PX_OPEN': 2023.33}}}

The command

pd.Panel(d)
<class 'pandas.core.panel.Panel'>
Dimensions: 2 (items) x 2 (major_axis) x 4 (minor_axis)
Items axis: RAY Index to SPX Index
Major_axis axis: PX_LAST to PX_OPEN
Minor_axis axis: 2014-11-03 to 2014-11-06

where pd.Panel(d)[item] yields a dataframe

pd.Panel(d)['SPX Index']
2014-11-03  2014-11-04  2014-11-05 2014-11-06
PX_LAST 2017.81 2012.10 2023.57 2031.21
PX_OPEN 2018.21 2015.81 2015.29 2023.33

You can then hit the command to_frame() to turn it into a dataframe. I use reset_index as well to turn the major and minor axis into columns rather than have them as indices.

pd.Panel(d).to_frame().reset_index()
major   minor      RAY Index    SPX Index
PX_LAST 2014-11-03  1199.460    2017.81
PX_LAST 2014-11-04  1195.323    2012.10
PX_LAST 2014-11-05  1200.936    2023.57
PX_LAST 2014-11-06  1206.061    2031.21
PX_OPEN 2014-11-03  1200.140    2018.21
PX_OPEN 2014-11-04  1197.690    2015.81
PX_OPEN 2014-11-05  1195.320    2015.29
PX_OPEN 2014-11-06  1200.620    2023.33

Finally, if you don't like the way the frame looks you can use the transpose function of panel to change the appearance before calling to_frame() see documentation here http://pandas.pydata.org/pandas-docs/dev/generated/pandas.Panel.transpose.html

Just as an example

pd.Panel(d).transpose(2,0,1).to_frame().reset_index()
major        minor  2014-11-03  2014-11-04  2014-11-05  2014-11-06
RAY Index   PX_LAST 1199.46    1195.323     1200.936    1206.061
RAY Index   PX_OPEN 1200.14    1197.690     1195.320    1200.620
SPX Index   PX_LAST 2017.81    2012.100     2023.570    2031.210
SPX Index   PX_OPEN 2018.21    2015.810     2015.290    2023.330

Hope this helps.

Is there any publicly accessible JSON data source to test with real world data?

Found one from Flickr that doesn't need registration / api.

Basic sample, Fiddle: http://jsfiddle.net/Braulio/vDr36/

More info: post

Pasted sample

HTML

<div id="images">

</div>

Javascript

// Querystring, "tags" search term, comma delimited
var query = "http://www.flickr.com/services/feeds/photos_public.gne?tags=soccer&format=json&jsoncallback=?";


// This function is called once the call is satisfied
// http://stackoverflow.com/questions/13854250/understanding-cross-domain-xhr-and-xml-data
var mycallback = function (data) {

    // Start putting together the HTML string
    var htmlString = "";

    // Now start cycling through our array of Flickr photo details
    $.each(data.items, function(i,item){

        // I only want the ickle square thumbnails
        var sourceSquare = (item.media.m).replace("_m.jpg", "_s.jpg");

        // Here's where we piece together the HTML
        htmlString += '<li><a href="' + item.link + '" target="_blank">';
        htmlString += '<img title="' + item.title + '" src="' + sourceSquare;
        htmlString += '" alt="'; htmlString += item.title + '" />';
        htmlString += '</a></li>';

    });

    // Pop our HTML in the #images DIV
    $('#images').html(htmlString);
};


// Ajax call to retrieve data
$.getJSON(query, mycallback);

Another very interesting is Star Wars Rest API:

https://swapi.co/

How to create a collapsing tree table in html/css/js?

In modern browsers, you need only very little to code to create a collapsible tree :

_x000D_
_x000D_
var tree = document.querySelectorAll('ul.tree a:not(:last-child)');_x000D_
for(var i = 0; i < tree.length; i++){_x000D_
    tree[i].addEventListener('click', function(e) {_x000D_
        var parent = e.target.parentElement;_x000D_
        var classList = parent.classList;_x000D_
        if(classList.contains("open")) {_x000D_
            classList.remove('open');_x000D_
            var opensubs = parent.querySelectorAll(':scope .open');_x000D_
            for(var i = 0; i < opensubs.length; i++){_x000D_
                opensubs[i].classList.remove('open');_x000D_
            }_x000D_
        } else {_x000D_
            classList.add('open');_x000D_
        }_x000D_
        e.preventDefault();_x000D_
    });_x000D_
}
_x000D_
body {_x000D_
    font-family: Arial;_x000D_
}_x000D_
_x000D_
ul.tree li {_x000D_
    list-style-type: none;_x000D_
    position: relative;_x000D_
}_x000D_
_x000D_
ul.tree li ul {_x000D_
    display: none;_x000D_
}_x000D_
_x000D_
ul.tree li.open > ul {_x000D_
    display: block;_x000D_
}_x000D_
_x000D_
ul.tree li a {_x000D_
    color: black;_x000D_
    text-decoration: none;_x000D_
}_x000D_
_x000D_
ul.tree li a:before {_x000D_
    height: 1em;_x000D_
    padding:0 .1em;_x000D_
    font-size: .8em;_x000D_
    display: block;_x000D_
    position: absolute;_x000D_
    left: -1.3em;_x000D_
    top: .2em;_x000D_
}_x000D_
_x000D_
ul.tree li > a:not(:last-child):before {_x000D_
    content: '+';_x000D_
}_x000D_
_x000D_
ul.tree li.open > a:not(:last-child):before {_x000D_
    content: '-';_x000D_
}
_x000D_
<ul class="tree">_x000D_
  <li><a href="#">Part 1</a>_x000D_
    <ul>_x000D_
      <li><a href="#">Item A</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
      <li><a href="#">Item B</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
      <li><a href="#">Item C</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
      <li><a href="#">Item D</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
      <li><a href="#">Item E</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
    </ul>_x000D_
  </li>_x000D_
_x000D_
  <li><a href="#">Part 2</a>_x000D_
    <ul>_x000D_
      <li><a href="#">Item A</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
      <li><a href="#">Item B</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
      <li><a href="#">Item C</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
      <li><a href="#">Item D</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
      <li><a href="#">Item E</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
    </ul>_x000D_
  </li>_x000D_
_x000D_
  <li><a href="#">Part 3</a>_x000D_
    <ul>_x000D_
      <li><a href="#">Item A</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
      <li><a href="#">Item B</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
      <li><a href="#">Item C</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
      <li><a href="#">Item D</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
      <li><a href="#">Item E</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
    </ul>_x000D_
  </li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

(see also this Fiddle)

Display an array in a readable/hierarchical format

Instead of

print_r($data);

try

print "<pre>";
print_r($data);
print "</pre>";

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

I am using PostgreSQL with closure tables for my hierarchies. I have one universal stored procedure for the whole database:

CREATE FUNCTION nomen_tree() RETURNS trigger
    LANGUAGE plpgsql
    AS $_$
DECLARE
  old_parent INTEGER;
  new_parent INTEGER;
  id_nom INTEGER;
  txt_name TEXT;
BEGIN
-- TG_ARGV[0] = name of table with entities with PARENT-CHILD relationships (TBL_ORIG)
-- TG_ARGV[1] = name of helper table with ANCESTOR, CHILD, DEPTH information (TBL_TREE)
-- TG_ARGV[2] = name of the field in TBL_ORIG which is used for the PARENT-CHILD relationship (FLD_PARENT)
    IF TG_OP = 'INSERT' THEN
    EXECUTE 'INSERT INTO ' || TG_ARGV[1] || ' (child_id,ancestor_id,depth) 
        SELECT $1.id,$1.id,0 UNION ALL
      SELECT $1.id,ancestor_id,depth+1 FROM ' || TG_ARGV[1] || ' WHERE child_id=$1.' || TG_ARGV[2] USING NEW;
    ELSE                                                           
    -- EXECUTE does not support conditional statements inside
    EXECUTE 'SELECT $1.' || TG_ARGV[2] || ',$2.' || TG_ARGV[2] INTO old_parent,new_parent USING OLD,NEW;
    IF COALESCE(old_parent,0) <> COALESCE(new_parent,0) THEN
      EXECUTE '
      -- prevent cycles in the tree
      UPDATE ' || TG_ARGV[0] || ' SET ' || TG_ARGV[2] || ' = $1.' || TG_ARGV[2]
        || ' WHERE id=$2.' || TG_ARGV[2] || ' AND EXISTS(SELECT 1 FROM '
        || TG_ARGV[1] || ' WHERE child_id=$2.' || TG_ARGV[2] || ' AND ancestor_id=$2.id);
      -- first remove edges between all old parents of node and its descendants
      DELETE FROM ' || TG_ARGV[1] || ' WHERE child_id IN
        (SELECT child_id FROM ' || TG_ARGV[1] || ' WHERE ancestor_id = $1.id)
        AND ancestor_id IN
        (SELECT ancestor_id FROM ' || TG_ARGV[1] || ' WHERE child_id = $1.id AND ancestor_id <> $1.id);
      -- then add edges for all new parents ...
      INSERT INTO ' || TG_ARGV[1] || ' (child_id,ancestor_id,depth) 
        SELECT child_id,ancestor_id,d_c+d_a FROM
        (SELECT child_id,depth AS d_c FROM ' || TG_ARGV[1] || ' WHERE ancestor_id=$2.id) AS child
        CROSS JOIN
        (SELECT ancestor_id,depth+1 AS d_a FROM ' || TG_ARGV[1] || ' WHERE child_id=$2.' 
        || TG_ARGV[2] || ') AS parent;' USING OLD, NEW;
    END IF;
  END IF;
  RETURN NULL;
END;
$_$;

Then for each table where I have a hierarchy, I create a trigger

CREATE TRIGGER nomenclature_tree_tr AFTER INSERT OR UPDATE ON nomenclature FOR EACH ROW EXECUTE PROCEDURE nomen_tree('my_db.nomenclature', 'my_db.nom_helper', 'parent_id');

For populating a closure table from existing hierarchy I use this stored procedure:

CREATE FUNCTION rebuild_tree(tbl_base text, tbl_closure text, fld_parent text) RETURNS void
    LANGUAGE plpgsql
    AS $$
BEGIN
    EXECUTE 'TRUNCATE ' || tbl_closure || ';
    INSERT INTO ' || tbl_closure || ' (child_id,ancestor_id,depth) 
        WITH RECURSIVE tree AS
      (
        SELECT id AS child_id,id AS ancestor_id,0 AS depth FROM ' || tbl_base || '
        UNION ALL 
        SELECT t.id,ancestor_id,depth+1 FROM ' || tbl_base || ' AS t
        JOIN tree ON child_id = ' || fld_parent || '
      )
      SELECT * FROM tree;';
END;
$$;

Closure tables are defined with 3 columns - ANCESTOR_ID, DESCENDANT_ID, DEPTH. It is possible (and I even advice) to store records with same value for ANCESTOR and DESCENDANT, and a value of zero for DEPTH. This will simplify the queries for retrieval of the hierarchy. And they are very simple indeed:

-- get all descendants
SELECT tbl_orig.*,depth FROM tbl_closure LEFT JOIN tbl_orig ON descendant_id = tbl_orig.id WHERE ancestor_id = XXX AND depth <> 0;
-- get only direct descendants
SELECT tbl_orig.* FROM tbl_closure LEFT JOIN tbl_orig ON descendant_id = tbl_orig.id WHERE ancestor_id = XXX AND depth = 1;
-- get all ancestors
SELECT tbl_orig.* FROM tbl_closure LEFT JOIN tbl_orig ON ancestor_id = tbl_orig.id WHERE descendant_id = XXX AND depth <> 0;
-- find the deepest level of children
SELECT MAX(depth) FROM tbl_closure WHERE ancestor_id = XXX;

How to view hierarchical package structure in Eclipse package explorer

Here is representation of screen eclipse to make hierarachical.

enter image description here

SQL recursive query on self referencing table (Oracle)

Do you want to do this?

SELECT id, parent_id, name, 
 (select Name from tbl where id = t.parent_id) parent_name
FROM tbl t start with id = 1 CONNECT BY PRIOR id = parent_id

Edit Another option based on OMG's one (but I think that will perform equally):

select 
           t1.id, 
           t1.parent_id, 
           t1.name,
           t2.name AS parent_name,
           t2.id AS parent_id
from 
    (select id, parent_id, name
    from tbl
    start with id = 1 
    connect by prior id = parent_id) t1
    left join
    tbl t2 on t2.id = t1.parent_id

Why is a "GRANT USAGE" created the first time I grant a user privileges?

I was trying to find the meaning of GRANT USAGE on *.* TO and found here. I can clarify that GRANT USAGE on *.* TO user IDENTIFIED BY PASSWORD password will be granted when you create the user with the following command (CREATE):

CREATE USER 'user'@'localhost' IDENTIFIED BY 'password'; 

When you grant privilege with GRANT, new privilege s will be added on top of it.

Are there any free Xml Diff/Merge tools available?

Pretty Diff tool was created with XML in mind. Just ensure you click the option for "markup".

http://prettydiff.com/

How do I prevent CSS inheritance?

There is a property called all in the CSS3 inheritance module. It works like this:

#sidebar ul li {
  all: initial;
}

As of 2016-12, all browsers but IE/Edge and Opera Mini support this property.

Relational Database Design Patterns?

There's a book in Martin Fowler's Signature Series called Refactoring Databases. That provides a list of techniques for refactoring databases. I can't say I've heard a list of database patterns so much.

I would also highly recommend David C. Hay's Data Model Patterns and the follow up A Metadata Map which builds on the first and is far more ambitious and intriguing. The Preface alone is enlightening.

Also a great place to look for some pre-canned database models is Len Silverston's Data Model Resource Book Series Volume 1 contains universally applicable data models (employees, accounts, shipping, purchases, etc), Volume 2 contains industry specific data models (accounting, healthcare, etc), Volume 3 provides data model patterns.

Finally, while this book is ostensibly about UML and Object Modelling, Peter Coad's Modeling in Color With UML provides an "archetype" driven process of entity modeling starting from the premise that there are 4 core archetypes of any object/data model

Keep only first n characters in a string?

var myString = "Hello, how are you?";
myString.slice(0,8);

Collections sort(List<T>,Comparator<? super T>) method example

You probably want something like this:

Collections.sort(students, new Comparator<Student>() {
                     public int compare(Student s1, Student s2) {
                           if(s1.getName() != null && s2.getName() != null && s1.getName().comareTo(s1.getName()) != 0) {
                               return s1.getName().compareTo(s2.getName());
                           } else {
                             return s1.getAge().compareTo(s2.getAge());
                          }
                      }
);

This sorts the students first by name. If a name is missing, or two students have the same name, they are sorted by their age.

Is Fortran easier to optimize than C for heavy calculations?

I haven't heard that Fortan is significantly faster than C, but it might be conceivable tht in certain cases it would be faster. And the key is not in the language features that are present, but in those that (usually) absent.

An example are C pointers. C pointers are used pretty much everywhere, but the problem with pointers is that the compiler usually can't tell if they're pointing to the different parts of the same array.

For example if you wrote a strcpy routine that looked like this:

strcpy(char *d, const char* s)
{
  while(*d++ = *s++);
}

The compiler has to work under the assumption that the d and s might be overlapping arrays. So it can't perform an optimization that would produce different results when the arrays overlap. As you'd expect, this considerably restricts the kind of optimizations that can be performed.

[I should note that C99 has a "restrict" keyword that explictly tells the compilers that the pointers don't overlap. Also note that the Fortran too has pointers, with semantics different from those of C, but the pointers aren't ubiquitous as in C.]

But coming back to the C vs. Fortran issue, it is conceivable that a Fortran compiler is able to perform some optimizations that might not be possible for a (straightforwardly written) C program. So I wouldn't be too surprised by the claim. However, I do expect that the performance difference wouldn't be all that much. [~5-10%]

How do I use the ternary operator ( ? : ) in PHP as a shorthand for "if / else"?

Note that when using nested conditional operators, you may want to use parenthesis to avoid possible issues!

It looks like PHP doesn't work the same way as at least Javascript or C#.

$score = 15;
$age = 5;

// The following will return "Exceptional"
echo 'Your score is: ' . ($score > 10 ? ($age > 10 ? 'Average' : 'Exceptional') : ($age > 10 ? 'Horrible' : 'Average'));

// The following will return "Horrible"
echo 'Your score is: ' . ($score > 10 ? $age > 10 ? 'Average' : 'Exceptional' : $age > 10 ? 'Horrible' : 'Average');

The same code in Javascript and C# return "Exceptional" in both cases.

In the 2nd case, what PHP does is (or at least that's what I understand):

  1. is $score > 10? yes
  2. is $age > 10? no, so the current $age > 10 ? 'Average' : 'Exceptional' returns 'Exceptional'
  3. then, instead of just stopping the whole statement and returning 'Exceptional', it continues evaluating the next statement
  4. the next statement becomes 'Exceptional' ? 'Horrible' : 'Average' which returns 'Horrible', as 'Exceptional' is truthy

From the documentation: http://php.net/manual/en/language.operators.comparison.php

It is recommended that you avoid "stacking" ternary expressions. PHP's behaviour when using more than one ternary operator within a single statement is non-obvious.

How to embed an autoplaying YouTube video in an iframe?

at the end of the iframe src, add &enablejsapi=1 to allow the js API to be used on the video

and then with jquery:

jQuery(document).ready(function( $ ) {
  $('.video-selector iframe')[0].contentWindow.postMessage('{"event":"command","func":"playVideo","args":""}', '*');
});

this should play the video automatically on document.ready

note, that you could also use this inside a click function to click on another element to start the video

More importantly, you cannot auto-start videos on a mobile device so users will always have to click on the video-player itself to start the video

Edit: I'm actually not 100% sure on document.ready the iframe will be ready, because YouTube could still be loading the video. I'm actually using this function inside a click function:

$('.video-container').on('click', function(){
  $('video-selector iframe')[0].contentWindow.postMessage('{"event":"command","func":"playVideo","args":""}', '*');
  // add other code here to swap a custom image, etc
});

jQuery Upload Progress and AJAX file upload

Uploading files is actually possible with AJAX these days. Yes, AJAX, not some crappy AJAX wannabes like swf or java.

This example might help you out: https://webblocks.nl/tests/ajax/file-drag-drop.html

(It also includes the drag/drop interface but that's easily ignored.)

Basically what it comes down to is this:

<input id="files" type="file" />

<script>
document.getElementById('files').addEventListener('change', function(e) {
    var file = this.files[0];
    var xhr = new XMLHttpRequest();
    (xhr.upload || xhr).addEventListener('progress', function(e) {
        var done = e.position || e.loaded
        var total = e.totalSize || e.total;
        console.log('xhr progress: ' + Math.round(done/total*100) + '%');
    });
    xhr.addEventListener('load', function(e) {
        console.log('xhr upload complete', e, this.responseText);
    });
    xhr.open('post', '/URL-HERE', true);
    xhr.send(file);
});
</script>

(demo: http://jsfiddle.net/rudiedirkx/jzxmro8r/)

So basically what it comes down to is this =)

xhr.send(file);

Where file is typeof Blob: http://www.w3.org/TR/FileAPI/

Another (better IMO) way is to use FormData. This allows you to 1) name a file, like in a form and 2) send other stuff (files too), like in a form.

var fd = new FormData;
fd.append('photo1', file);
fd.append('photo2', file2);
fd.append('other_data', 'foo bar');
xhr.send(fd);

FormData makes the server code cleaner and more backward compatible (since the request now has the exact same format as normal forms).

All of it is not experimental, but very modern. Chrome 8+ and Firefox 4+ know what to do, but I don't know about any others.

This is how I handled the request (1 image per request) in PHP:

if ( isset($_FILES['file']) ) {
    $filename = basename($_FILES['file']['name']);
    $error = true;

    // Only upload if on my home win dev machine
    if ( isset($_SERVER['WINDIR']) ) {
        $path = 'uploads/'.$filename;
        $error = !move_uploaded_file($_FILES['file']['tmp_name'], $path);
    }

    $rsp = array(
        'error' => $error, // Used in JS
        'filename' => $filename,
        'filepath' => '/tests/uploads/' . $filename, // Web accessible
    );
    echo json_encode($rsp);
    exit;
}

How to choose the right bean scope?

Introduction

It represents the scope (the lifetime) of the bean. This is easier to understand if you are familiar with "under the covers" working of a basic servlet web application: How do servlets work? Instantiation, sessions, shared variables and multithreading.


@Request/View/Flow/Session/ApplicationScoped

A @RequestScoped bean lives as long as a single HTTP request-response cycle (note that an Ajax request counts as a single HTTP request too). A @ViewScoped bean lives as long as you're interacting with the same JSF view by postbacks which call action methods returning null/void without any navigation/redirect. A @FlowScoped bean lives as long as you're navigating through the specified collection of views registered in the flow configuration file. A @SessionScoped bean lives as long as the established HTTP session. An @ApplicationScoped bean lives as long as the web application runs. Note that the CDI @Model is basically a stereotype for @Named @RequestScoped, so same rules apply.

Which scope to choose depends solely on the data (the state) the bean holds and represents. Use @RequestScoped for simple and non-ajax forms/presentations. Use @ViewScoped for rich ajax-enabled dynamic views (ajaxbased validation, rendering, dialogs, etc). Use @FlowScoped for the "wizard" ("questionnaire") pattern of collecting input data spread over multiple pages. Use @SessionScoped for client specific data, such as the logged-in user and user preferences (language, etc). Use @ApplicationScoped for application wide data/constants, such as dropdown lists which are the same for everyone, or managed beans without any instance variables and having only methods.

Abusing an @ApplicationScoped bean for session/view/request scoped data would make it to be shared among all users, so anyone else can see each other's data which is just plain wrong. Abusing a @SessionScoped bean for view/request scoped data would make it to be shared among all tabs/windows in a single browser session, so the enduser may experience inconsitenties when interacting with every view after switching between tabs which is bad for user experience. Abusing a @RequestScoped bean for view scoped data would make view scoped data to be reinitialized to default on every single (ajax) postback, causing possibly non-working forms (see also points 4 and 5 here). Abusing a @ViewScoped bean for request, session or application scoped data, and abusing a @SessionScoped bean for application scoped data doesn't affect the client, but it unnecessarily occupies server memory and is plain inefficient.

Note that the scope should rather not be chosen based on performance implications, unless you really have a low memory footprint and want to go completely stateless; you'd need to use exclusively @RequestScoped beans and fiddle with request parameters to maintain the client's state. Also note that when you have a single JSF page with differently scoped data, then it's perfectly valid to put them in separate backing beans in a scope matching the data's scope. The beans can just access each other via @ManagedProperty in case of JSF managed beans or @Inject in case of CDI managed beans.

See also:


@CustomScoped/NoneScoped/Dependent

It's not mentioned in your question, but (legacy) JSF also supports @CustomScoped and @NoneScoped, which are rarely used in real world. The @CustomScoped must refer a custom Map<K, Bean> implementation in some broader scope which has overridden Map#put() and/or Map#get() in order to have more fine grained control over bean creation and/or destroy.

The JSF @NoneScoped and CDI @Dependent basically lives as long as a single EL-evaluation on the bean. Imagine a login form with two input fields referring a bean property and a command button referring a bean action, thus with in total three EL expressions, then effectively three instances will be created. One with the username set, one with the password set and one on which the action is invoked. You normally want to use this scope only on beans which should live as long as the bean where it's being injected. So if a @NoneScoped or @Dependent is injected in a @SessionScoped, then it will live as long as the @SessionScoped bean.

See also:


Flash scope

As last, JSF also supports the flash scope. It is backed by a short living cookie which is associated with a data entry in the session scope. Before the redirect, a cookie will be set on the HTTP response with a value which is uniquely associated with the data entry in the session scope. After the redirect, the presence of the flash scope cookie will be checked and the data entry associated with the cookie will be removed from the session scope and be put in the request scope of the redirected request. Finally the cookie will be removed from the HTTP response. This way the redirected request has access to request scoped data which was been prepared in the initial request.

This is actually not available as a managed bean scope, i.e. there's no such thing as @FlashScoped. The flash scope is only available as a map via ExternalContext#getFlash() in managed beans and #{flash} in EL.

See also:

AngularJS ui-router login authentication

The easiest solution is to use $stateChangeStart and event.preventDefault() to cancel the state change when the user is not authenticated and redirect him to the auth state that is the login page.

angular
  .module('myApp', [
    'ui.router',
  ])
    .run(['$rootScope', 'User', '$state',
    function ($rootScope, User, $state) {
      $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
        if (toState.name !== 'auth' && !User.authenticaded()) {
          event.preventDefault();
          $state.go('auth');
        }
      });
    }]
  );

convert double to int

label8.Text = "" + years.ToString("00") + " years";

when you want to send it to a label, or something, and you don't want any fractional component, this is the best way

label8.Text = "" + years.ToString("00.00") + " years";

if you want with only 2, and it's always like that

How to order results with findBy() in Doctrine

$cRepo = $em->getRepository('KaleLocationBundle:Country');

// Leave the first array blank
$countries = $cRepo->findBy(array(), array('name'=>'asc'));

How do I check if a type is a subtype OR the type of an object?

Apparently, no.

Here's the options:

Type.IsSubclassOf

As you've already found out, this will not work if the two types are the same, here's a sample LINQPad program that demonstrates:

void Main()
{
    typeof(Derived).IsSubclassOf(typeof(Base)).Dump();
    typeof(Base).IsSubclassOf(typeof(Base)).Dump();
}

public class Base { }
public class Derived : Base { }

Output:

True
False

Which indicates that Derived is a subclass of Base, but that Baseis (obviously) not a subclass of itself.

Type.IsAssignableFrom

Now, this will answer your particular question, but it will also give you false positives. As Eric Lippert has pointed out in the comments, while the method will indeed return True for the two above questions, it will also return True for these, which you probably don't want:

void Main()
{
    typeof(Base).IsAssignableFrom(typeof(Derived)).Dump();
    typeof(Base).IsAssignableFrom(typeof(Base)).Dump();
    typeof(int[]).IsAssignableFrom(typeof(uint[])).Dump();
}

public class Base { }
public class Derived : Base { }

Here you get the following output:

True
True
True

The last True there would indicate, if the method only answered the question asked, that uint[] inherits from int[] or that they're the same type, which clearly is not the case.

So IsAssignableFrom is not entirely correct either.

is and as

The "problem" with is and as in the context of your question is that they will require you to operate on the objects and write one of the types directly in code, and not work with Type objects.

In other words, this won't compile:

SubClass is BaseClass
^--+---^
   |
   +-- need object reference here

nor will this:

typeof(SubClass) is typeof(BaseClass)
                    ^-------+-------^
                            |
                            +-- need type name here, not Type object

nor will this:

typeof(SubClass) is BaseClass
^------+-------^
       |
       +-- this returns a Type object, And "System.Type" does not
           inherit from BaseClass

Conclusion

While the above methods might fit your needs, the only correct answer to your question (as I see it) is that you will need an extra check:

typeof(Derived).IsSubclassOf(typeof(Base)) || typeof(Derived) == typeof(Base);

which of course makes more sense in a method:

public bool IsSameOrSubclass(Type potentialBase, Type potentialDescendant)
{
    return potentialDescendant.IsSubclassOf(potentialBase)
           || potentialDescendant == potentialBase;
}

Free Rest API to retrieve current datetime as string (timezone irrelevant)

If you're using Rails, you can just make an empty file in the public folder and use ajax to get that. Then parse the headers for the Date header. Files in the Public folder bypass the Rails stack, and so have lower latency.

MySQL Error: : 'Access denied for user 'root'@'localhost'

In your MySQL workbench, you can go to the left sidebar, under Management select "Users and Privileges", click root under User Accounts, the in the right section click tab "Account Limits" to increase the max queries, updates, etc, and then click tab "Administrative Roles" and check the boxes to give the account access. Hope that helps!

How do I use hexadecimal color strings in Flutter?

Use hexcolor for bringing hex colors to dart hexcolorPlugin

hexcolor: ^1.0.4

sample usage

import 'package:hexcolor/hexcolor.dart';
 Container(
          decoration: new BoxDecoration(
            color: Hexcolor('#34cc89'),
          ),
          child: Center(
            child: Text(
              'Running on: $_platformVersion\n',
              style: TextStyle(color: Hexcolor("#f2f2f2")),
            ),
          ),
        ),

How to convert a Datetime string to a current culture datetime string

This works for me,

DateTimeFormatInfo usDtfi = new CultureInfo("en-US", false).DateTimeFormat;
DateTimeFormatInfo ukDtfi = new CultureInfo("en-GB", false).DateTimeFormat;
string result = Convert.ToDateTime("26/09/2015",ukDtfi).ToString(usDtfi.ShortDatePattern);

"You tried to execute a query that does not include the specified aggregate function"

The error is because fName is included in the SELECT list, but is not included in a GROUP BY clause and is not part of an aggregate function (Count(), Min(), Max(), Sum(), etc.)

You can fix that problem by including fName in a GROUP BY. But then you will face the same issue with surname. So put both in the GROUP BY:

SELECT
    fName,
    surname,
    Count(*) AS num_rows
FROM
    author
    INNER JOIN book
    ON author.aID = book.authorID;
GROUP BY
    fName,
    surname

Note I used Count(*) where you wanted SUM(orders.quantity). However, orders isn't included in the FROM section of your query, so you must include it before you can Sum() one of its fields.

If you have Access available, build the query in the query designer. It can help you understand what features are possible and apply the correct Access SQL syntax.

Php artisan make:auth command is not defined

For Laravel >=6

composer require laravel/ui
php artisan ui vue --auth
php artisan migrate

Reference : Laravel Documentation for authentication

it looks you are not using Laravel 5.2, these are the available make commands in L5.2 and you are missing more than just the make:auth command

    make:auth           Scaffold basic login and registration views and routes
    make:console        Create a new Artisan command
    make:controller     Create a new controller class
    make:entity         Create a new entity.
    make:event          Create a new event class
    make:job            Create a new job class
    make:listener       Create a new event listener class
    make:middleware     Create a new middleware class
    make:migration      Create a new migration file
    make:model          Create a new Eloquent model class
    make:policy         Create a new policy class
    make:presenter      Create a new presenter.
    make:provider       Create a new service provider class
    make:repository     Create a new repository.
    make:request        Create a new form request class
    make:seeder         Create a new seeder class
    make:test           Create a new test class
    make:transformer    Create a new transformer.

Be sure you have this dependency in your composer.json file

    "laravel/framework": "5.2.*",

Then run

    composer update

How can I show a message box with two buttons?

Cannot be done. MsgBox buttons can only have specific values.
You'll have to roll your own form for this.

To create a MsgBox with two options (Yes/No):

MsgBox("Some Text", vbYesNo)

Convert base-2 binary number string to int

Just type 0b11111111 in python interactive interface:

>>> 0b11111111
    255

Unable to open debugger port in IntelliJ

I once have this problem too. My solution is to work around this problem by kill the application which is using the port. Here is a article to teach us how to check which application is using which port, find it and kill/close it.

What is ViewModel in MVC?

ViewModel is workaround that patches the conceptual clumsiness of the MVC framework. It represents the 4th layer in the 3-layer Model-View-Controller architecture. when Model (domain model) is not appropriate, too big (bigger than 2-3 fields) for the View, we create smaller ViewModel to pass it to the View.

Android Gallery on Android 4.4 (KitKat) returns different URI for Intent.ACTION_GET_CONTENT

This is a total hack, but here's what I did...

So while playing with setting up a DocumentsProvider, I noticed that the sample code (in getDocIdForFile, around line 450) generates a unique id for a selected document based on the file's (unique) path relative to the specified root you give it (that is, what you set mBaseDir to on line 96).

So the URI ends up looking something like:

content://com.example.provider/document/root:path/to/the/file

As the docs say, it's assuming only a single root (in my case that's Environment.getExternalStorageDirectory() but you may use somewhere else... then it takes the file path, starting at the root, and makes it the unique ID, prepending "root:". So I can determine the path by eliminating the "/document/root:" part from uri.getPath(), creating an actual file path by doing something like this:

public void onActivityResult(int requestCode, int resultCode, Intent data) {
// check resultcodes and such, then...
uri = data.getData();
if (uri.getAuthority().equals("com.example.provider"))  {
    String path = Environment.getExternalStorageDirectory(0.toString()
                 .concat("/")
                 .concat(uri.getPath().substring("/document/root:".length())));
    doSomethingWithThePath(path); }
else {
    // another provider (maybe a cloud-based service such as GDrive)
    // created this uri.  So handle it, or don't.  You can allow specific
    // local filesystem providers, filter non-filesystem path results, etc.
}

I know. It's shameful, but it worked. Again, this relies on you using your own documents provider in your app to generate the document ID.

(Also, there's a better way to build the path that don't assume "/" is the path separator, etc. But you get the idea.)

Best Practice to Use HttpClient in Multithreaded Environment

I think you will want to use ThreadSafeClientConnManager.

You can see how it works here: http://foo.jasonhudgins.com/2009/08/http-connection-reuse-in-android.html

Or in the AndroidHttpClient which uses it internally.

Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0

I had the same error after moving to a new laptop (Windows 10). In addition to setting Copy Local to true as mentioned above, I had to install the Crystal Reports 32-bit runtime engine for .Net Framework, even though everything else is set to run in a 64-bit environment. Hope that helps.

Windows Control Panel - Programs and Features

What does axis in pandas mean?

axis refers to the dimension of the array, in the case of pd.DataFrames axis=0 is the dimension that points downwards and axis=1 the one that points to the right.

Example: Think of an ndarray with shape (3,5,7).

a = np.ones((3,5,7))

a is a 3 dimensional ndarray, i.e. it has 3 axes ("axes" is plural of "axis"). The configuration of a will look like 3 slices of bread where each slice is of dimension 5-by-7. a[0,:,:] will refer to the 0-th slice, a[1,:,:] will refer to the 1-st slice etc.

a.sum(axis=0) will apply sum() along the 0-th axis of a. You will add all the slices and end up with one slice of shape (5,7).

a.sum(axis=0) is equivalent to

b = np.zeros((5,7))
for i in range(5):
    for j in range(7):
        b[i,j] += a[:,i,j].sum()

b and a.sum(axis=0) will both look like this

array([[ 3.,  3.,  3.,  3.,  3.,  3.,  3.],
       [ 3.,  3.,  3.,  3.,  3.,  3.,  3.],
       [ 3.,  3.,  3.,  3.,  3.,  3.,  3.],
       [ 3.,  3.,  3.,  3.,  3.,  3.,  3.],
       [ 3.,  3.,  3.,  3.,  3.,  3.,  3.]])

In a pd.DataFrame, axes work the same way as in numpy.arrays: axis=0 will apply sum() or any other reduction function for each column.

N.B. In @zhangxaochen's answer, I find the phrases "along the rows" and "along the columns" slightly confusing. axis=0 should refer to "along each column", and axis=1 "along each row".

Are SSL certificates bound to the servers ip address?

SSL certificates are bound to a 'common name', which is usually a fully qualified domain name but can be a wildcard name (eg. *.domain.com) or even an IP address, but it usually isn't.

In your case, you are accessing your LDAP server by a hostname and it sounds like your two LDAP servers have different SSL certificates installed. Are you able to view (or download and view) the details of the SSL certificate? Each SSL certificate will have a unique serial numbers and fingerprint which will need to match. I assume the certificate is being rejected as these details don't match with what's in your certificate store.

Your solution will be to ensure that both LDAP servers have the same SSL certificate installed.

BTW - you can normally override DNS entries on your workstation by editing a local 'hosts' file, but I wouldn't recommend this.

Android Studio - local path doesn't exist

If you have run into this problem while updating to android studio version 0.3.3 or 0.3.4 then you need to remove gradle 1.8 jars from android-studio/plugins/gradle/lib

rm android-studio/plugins/gradle/lib/gradle-*-1.8.jar 

UITableViewCell, show delete button on swipe

Swift 2.2 :

override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
    return true
}

override func tableView(tableView: UITableView,
    editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? {
    let delete = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: "DELETE"){(UITableViewRowAction,NSIndexPath) -> Void in

    print("Your action when user pressed delete")
}
let edit = UITableViewRowAction(style: UITableViewRowActionStyle.Normal, title: "EDIT"){(UITableViewRowAction,NSIndexPath) -> Void in

    print("Your action when user pressed edit")
}
    return [delete, block]
}

System.BadImageFormatException: Could not load file or assembly

It seems that you are using the 64-bit version of the tool to install a 32-bit/x86 architecture application. Look for the 32-bit version of the tool here:

C:\Windows\Microsoft.NET\Framework\v4.0.30319

and it should install your 32-bit application just fine.

How to add header data in XMLHttpRequest when using formdata?

Your error

InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable

appears because you must call setRequestHeader after calling open. Simply move your setRequestHeader line below your open line (but before send):

xmlhttp.open("POST", url);
xmlhttp.setRequestHeader("x-filename", photoId);
xmlhttp.send(formData);

getting error while updating Composer

The good solution for this error please run this command

composer install --ignore-platform-reqs

How to write/update data into cells of existing XLSX workbook using xlsxwriter in python

you can use this code to open (test.xlsx) file and modify A1 cell and then save it with a new name

import openpyxl
xfile = openpyxl.load_workbook('test.xlsx')

sheet = xfile.get_sheet_by_name('Sheet1')
sheet['A1'] = 'hello world'
xfile.save('text2.xlsx')

Difference between signed / unsigned char

This because a char is stored at all effects as a 8-bit number. Speaking about a negative or positive char doesn't make sense if you consider it an ASCII code (which can be just signed*) but makes sense if you use that char to store a number, which could be in range 0-255 or in -128..127 according to the 2-complement representation.

*: it can be also unsigned, it actually depends on the implementation I think, in that case you will have access to extended ASCII charset provided by the encoding used

How do I open phone settings when a button is clicked?

Swift 4.2, iOS 12

The open(url:options:completionHandler:) method has been updated to include a non-nil options dictionary, which as of this post only contains one possible option of type UIApplication.OpenExternalURLOptionsKey (in the example).

@objc func openAppSpecificSettings() {
    guard let url = URL(string: UIApplication.openSettingsURLString),
        UIApplication.shared.canOpenURL(url) else {
            return
    }
    let optionsKeyDictionary = [UIApplication.OpenExternalURLOptionsKey(rawValue: "universalLinksOnly"): NSNumber(value: true)]
    
    UIApplication.shared.open(url, options: optionsKeyDictionary, completionHandler: nil)
}

Explicitly constructing a URL, such as with "App-Prefs", has, AFAIK, gotten some apps rejected from the store.

Remove blue border from css custom-styled button in Chrome

If you want to delete same effect in input, you could add the following code as well as button.

input:focus {outline:0;}

How to ignore a property in class if null, using json.net

An alternate solution using the JsonProperty attribute:

[JsonProperty(NullValueHandling=NullValueHandling.Ignore)]
// or
[JsonProperty("property_name", NullValueHandling=NullValueHandling.Ignore)]

// or for all properties in a class
[JsonObject(ItemNullValueHandling = NullValueHandling.Ignore)]

As seen in this online doc.

SDK Location not found Android Studio + Gradle

If none of the answers work for you which happened to me on macbook pro in one of the projects you can always try to run Android Studio with an alias command passing sdk.dir with each run:

alias studio='launchctl setenv ANDROID_HOME '\''/Users/username/Library/Android/sdk'\'' && open -a '\''Android Studio'\'''

submit the form using ajax

You can catch form input values using FormData and send them by fetch

fetch(form.action,{method:'post', body: new FormData(form)});

_x000D_
_x000D_
function send(e,form) {_x000D_
  fetch(form.action,{method:'post', body: new FormData(form)});_x000D_
_x000D_
  console.log('We send post asynchronously (AJAX)');_x000D_
  e.preventDefault();_x000D_
}
_x000D_
<form method="POST" action="myapi/send" onsubmit="send(event,this)">_x000D_
    <input hidden name="crsfToken" value="a1e24s1">_x000D_
    <input name="email" value="[email protected]">_x000D_
    <input name="phone" value="123-456-789">_x000D_
    <input type="submit">    _x000D_
</form>_x000D_
_x000D_
Look on chrome console>network before 'submit'
_x000D_
_x000D_
_x000D_

Find element's index in pandas Series

If you use numpy, you can get an array of the indecies that your value is found:

import numpy as np
import pandas as pd
myseries = pd.Series([1,4,0,7,5], index=[0,1,2,3,4])
np.where(myseries == 7)

This returns a one element tuple containing an array of the indecies where 7 is the value in myseries:

(array([3], dtype=int64),)

SQL How to Select the most recent date item

With SQL Server try:

SELECT TOP 1 * FROM dbo.youTable WHERE user_id = 'userid' ORDER BY date_added desc

Convert char to int in C#

Comparison of some of the methods based on the result when the character is not an ASCII digit:

char c1 = (char)('0' - 1), c2 = (char)('9' + 1); 

Debug.Print($"{c1 & 15}, {c2 & 15}");                                   // 15, 10
Debug.Print($"{c1 ^ '0'}, {c2 ^ '0'}");                                 // 31, 10
Debug.Print($"{c1 - '0'}, {c2 - '0'}");                                 // -1, 10
Debug.Print($"{(uint)c1 - '0'}, {(uint)c2 - '0'}");                     // 4294967295, 10
Debug.Print($"{char.GetNumericValue(c1)}, {char.GetNumericValue(c2)}"); // -1, -1

Undefined reference to pow( ) in C, despite including math.h

You need to link with the math library:

gcc -o sphere sphere.c -lm

The error you are seeing: error: ld returned 1 exit status is from the linker ld (part of gcc that combines the object files) because it is unable to find where the function pow is defined.

Including math.h brings in the declaration of the various functions and not their definition. The def is present in the math library libm.a. You need to link your program with this library so that the calls to functions like pow() are resolved.

std::queue iteration

you can save the original queue to a temporary queue. Then you simply do your normal pop on the temporary queue to go through the original one, for example:

queue tmp_q = original_q; //copy the original queue to the temporary queue

while (!tmp_q.empty())
{
    q_element = tmp_q.front();
    std::cout << q_element <<"\n";
    tmp_q.pop();
} 

At the end, the tmp_q will be empty but the original queue is untouched.

How to split a string content into an array of strings in PowerShell?

As of PowerShell 2, simple:

$recipients = $addresses -split "; "

Note that the right hand side is actually a case-insensitive regular expression, not a simple match. Use csplit to force case-sensitivity. See about_Split for more details.

How do you make a div tag into a link

<div style="cursor:pointer" onclick="document.location='http://www.google.com'">Content Goes Here</div>

Remove 'standalone="yes"' from generated XML

In case you are getting property exception, add the following configuration:

jaxbMarshaller.setProperty("com.sun.xml.internal.bind.xmlHeaders",
              "<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
jaxbMarshaller.setProperty("com.sun.xml.internal.bind.xmlDeclaration", Boolean.FALSE);
jaxbMarshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);  

Check the current number of connections to MongoDb

In OS X, too see the connections directly on the network interface, just do:

$ lsof -n -i4TCP:27017

mongod     2191 inanc    7u  IPv4 0xab6d9f844e21142f  0t0  TCP 127.0.0.1:27017 (LISTEN)
mongod     2191 inanc   33u  IPv4 0xab6d9f84604cd757  0t0  TCP 127.0.0.1:27017->127.0.0.1:56078 (ESTABLISHED)
stores.te 18704 inanc    6u  IPv4 0xab6d9f84604d404f  0t0  TCP 127.0.0.1:56078->127.0.0.1:27017 (ESTABLISHED)
  • No need to use grep etc, just use the lsof's arguments.

  • Too see the connections on MongoDb's CLI, see @milan's answer (which I just edited).

What is the difference between public, protected, package-private and private in Java?

Access modifiers in Java.

Java access modifiers are used to provide access control in Java.

1. Default:

Accessible to the classes in the same package only.

For example,

// Saved in file A.java
package pack;

class A{
  void msg(){System.out.println("Hello");}
}

// Saved in file B.java
package mypack;
import pack.*;

class B{
  public static void main(String args[]){
   A obj = new A(); // Compile Time Error
   obj.msg(); // Compile Time Error
  }
}

This access is more restricted than public and protected, but less restricted than private.

2. Public

Can be accessed from anywhere. (Global Access)

For example,

// Saved in file A.java

package pack;
public class A{
  public void msg(){System.out.println("Hello");}
}

// Saved in file B.java

package mypack;
import pack.*;

class B{
  public static void main(String args[]){
    A obj = new A();
    obj.msg();
  }
}

Output:Hello

3. Private

Accessible only inside the same class.

If you try to access private members on one class in another will throw compile error. For example,

class A{
  private int data = 40;
  private void msg(){System.out.println("Hello java");}
}

public class Simple{
  public static void main(String args[]){
    A obj = new A();
    System.out.println(obj.data); // Compile Time Error
    obj.msg(); // Compile Time Error
  }
}

4. Protected

Accessible only to the classes in the same package and to the subclasses

For example,

// Saved in file A.java
package pack;
public class A{
  protected void msg(){System.out.println("Hello");}
}

// Saved in file B.java
package mypack;
import pack.*;

class B extends A{
  public static void main(String args[]){
    B obj = new B();
    obj.msg();
  }
}

Output: Hello

Enter image description here

How do I make a request using HTTP basic authentication with PHP curl?

Michael Dowling's very actively maintained Guzzle is a good way to go. Apart from the elegant interface, asynchronous calling and PSR compliance, it makes the authentication headers for REST calls dead simple:

// Create a client with a base URL
$client = new GuzzleHttp\Client(['base_url' => 'http://myservices.io']);

// Send a request to http://myservices.io/status with basic authentication
$response = $client->get('/status', ['auth' => ['username', 'password']]);

See the docs.

What's the difference between a null pointer and a void pointer?

I don't think AnT's answer is correct.

  1. NULL is just a pointer constant, otherwise how could we have ptr = NULL.
  2. As NULL is a pointer, what's its type. I think the type is just (void *), otherwise how could we have both int * ptr = NULL and (user-defined type)* ptr = NULL. void type is actually a universal type.
  3. Quoted in "C11(ISO/IEC 9899:201x) §6.3.2.3 Pointers Section 3":

    An integer constant expression with the value 0, or such an expression cast to type void *, is called a null pointer constant

So simply put: NULL pointer is a void pointer constant.

Change label text using JavaScript

Because a label element is not loaded when a script is executed. Swap the label and script elements, and it will work:

<label id="lbltipAddedComment"></label>
<script>
    document.getElementById('lbltipAddedComment').innerHTML = 'Your tip has been submitted!';
</script>

Ansible - read inventory hosts and variables to group_vars/all file

Considering your previous example:

inventory file:

[db]
10.112.83.37

group_vars/all

data_base_url=jdbc:oracle:thin:@{{ db }}:1521/ssdenwdb

template file:

oracle_url = {{ data_base_url }}

You might want to replace your group_vars/all with

data_base_url="jdbc:oracle:thin:@{{ groups['db'][0] }}:1521/ssdenwdb"

error: expected class-name before ‘{’ token

Replace

#include "Landing.h"

with

class Landing;

If you still get errors, also post Item.h, Flight.h and common.h

EDIT: In response to comment.

You will need to e.g. #include "Landing.h" from Event.cpp in order to actually use the class. You just cannot include it from Event.h

Missing XML comment for publicly visible type or member

Insert an XML comment. ;-)

/// <summary>
/// Describe your member here.
/// </summary>
public string Something
{
    get;
    set;
}

This may appear like a joke at the first glance, but it may actually be useful. For me it turned out to be helpful to think about what methods do even for private methods (unless really trivial, of course).

Unknown lifecycle phase "mvn". You must specify a valid lifecycle phase or a goal in the format <plugin-prefix>:<goal> or <plugin-group-id>

Thanks for the reply. I was using "mvn clean install" in the maven build configuration. we no need to use "mvn" command if running through eclipse.

After buiding the application using the command "clean install" , I got one more error -
"No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?"

I followed this link:- No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?

now application building is fine in eclipse.

How to change the decimal separator of DecimalFormat from comma to dot/point?

This worked for me...

    double num = 10025000;
    new DecimalFormat("#,###.##");
    DecimalFormat df = (DecimalFormat) DecimalFormat.getInstance(Locale.GERMAN);
    System.out.println(df.format(num));

iPhone is not available. Please reconnect the device

I am now using Xcode 11.6, macOS 10.15.6, and iOS 13.5.1.

First the problem was that I was on Xcode 11.4. But I couldn't upgrade since I wasn't on macOS v10.15 (Catalina) yet. (And I couldn't upgrade because my RAID went down and I couldn't make a backup, but that's another saga.)

After upgrading to Catalina, then to Xcode 11.6 I still couldn't build to the device. So I opened Devices and Simulators and unpaired the phone, as mentioned in the comments here. Then when I tried to re-pair, a warning message said that the device was busy (it was not). Finally, after rebooting the phone (had to untether it for it to come back on), cleaning Xcode, and re-pairing the phone, I finally, finally built to the device. So good luck!

Call async/await functions in parallel

I've created a gist testing some different ways of resolving promises, with results. It may be helpful to see the options that work.

How to remove an appended element with Jquery and why bind or live is causing elements to repeat

The live function is registering a click event handler. It'll do so every time you click the object. So if you click it twice, you're assigning two click handlers to the object. You're also assigning a click handler here:

onclick="feedback('the message html')";

And then that click handler is assigning another click handler via live().

Really what I think you want to do is this:

function feedback(message)
{
    $('#feedback').remove();

    $('.answers').append('<div id="feedback">'+message+'</div>');
}

Ok, per your comment, try taking out the onclick part of the <a> element and instead, putting this in a document.ready() handler.

$('#answer').live('click',function(){
                     $('#feedback').remove();
                     $('.answers').append('<div id="feedback">'+message+'</div>');
                 });

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

We basically use user controls when we have to use similar functionality on different locations of an app. Like we use master pages for consistent look and feel of app, similarly to avoid repeating the same functionality and UI all over the app, we use usercontrols. There might me much more usage too, but I know this one only...

For example, let's say your site has 4 levels of users and for each user there are different pages under different directories with different access mechanisms. Say you are requesting address info for all users, then creating address fields like Street, City, State, Zip, etc on each page. That would be a repetitive job. Instead you can create it as an ascx file (ext for user control) and in this control put the necessary UI and business code for add/update/delete/select the address role wise and then simply reference it all required page.

So, thought user controls, one can avoid code repetition for each role and UI creation for each role.

Remove IE10's "clear field" X button on certain inputs?

I would apply this rule to all input fields of type text, so it doesn't need to be duplicated later:

input[type=text]::-ms-clear { display: none; }

One can even get less specific by using just:

::-ms-clear { display: none; }

I have used the later even before adding this answer, but thought that most people would prefer to be more specific than that. Both solutions work fine.

Export to csv in jQuery

I recently posted a free software library for this: "html5csv.js" -- GitHub

It is intended to help streamline the creation of small simulator apps in Javascript that might need to import or export csv files, manipulate, display, edit the data, perform various mathematical procedures like fitting, etc.

After loading "html5csv.js" the problem of scanning a table and creating a CSV is a one-liner:

CSV.begin('#PrintDiv').download('MyData.csv').go();

Here is a JSFiddle demo of your example with this code.

Internally, for Firefox/Chrome this is a data URL oriented solution, similar to that proposed by @italo, @lepe, and @adeneo (on another question). For IE

The CSV.begin() call sets up the system to read the data into an internal array. That fetch then occurs. Then the .download() generates a data URL link internally and clicks it with a link-clicker. This pushes a file to the end user.

According to caniuse IE10 doesn't support <a download=...>. So for IE my library calls navigator.msSaveBlob() internally, as suggested by @Manu Sharma

How to change time in DateTime?

Alright I'm diving in with my suggestion, an extension method:

public static DateTime ChangeTime(this DateTime dateTime, int hours, int minutes, int seconds, int milliseconds)
{
    return new DateTime(
        dateTime.Year,
        dateTime.Month,
        dateTime.Day,
        hours,
        minutes,
        seconds,
        milliseconds,
        dateTime.Kind);
}

Then call:

DateTime myDate = DateTime.Now.ChangeTime(10,10,10,0);

It's important to note that this extension returns a new date object, so you can't do this:

DateTime myDate = DateTime.Now;
myDate.ChangeTime(10,10,10,0);

But you can do this:

DateTime myDate = DateTime.Now;
myDate = myDate.ChangeTime(10,10,10,0);

HTML text input allow only numeric input

Use this DOM

<input type='text' onkeypress='validate(event)' />

And this script

function validate(evt) {
  var theEvent = evt || window.event;

  // Handle paste
  if (theEvent.type === 'paste') {
      key = event.clipboardData.getData('text/plain');
  } else {
  // Handle key press
      var key = theEvent.keyCode || theEvent.which;
      key = String.fromCharCode(key);
  }
  var regex = /[0-9]|\./;
  if( !regex.test(key) ) {
    theEvent.returnValue = false;
    if(theEvent.preventDefault) theEvent.preventDefault();
  }
}

I can't find my git.exe file in my Github folder

The path for the latest version of Git is changed, In my laptop, I found it in

C:\Users\Anum Sheraz\AppData\Local\Programs\Git\bin\git.exe

This resolved my issue of path. Hope that helps to someone :)

Convert a secure string to plain text

You are close, but the parameter you pass to SecureStringToBSTR must be a SecureString. You appear to be passing the result of ConvertFrom-SecureString, which is an encrypted standard string. So call ConvertTo-SecureString on this before passing to SecureStringToBSTR.

$SecurePassword = ConvertTo-SecureString $PlainPassword -AsPlainText -Force
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecurePassword)
$UnsecurePassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)

Routing with multiple Get methods in ASP.NET Web API

There are lots of good answers already for this question. However nowadays Route configuration is sort of "deprecated". The newer version of MVC (.NET Core) does not support it. So better to get use to it :)

So I agree with all the answers which uses Attribute style routing. But I keep noticing that everyone repeated the base part of the route (api/...). It is better to apply a [RoutePrefix] attribute on top of the Controller class and don't repeat the same string over and over again.

[RoutePrefix("api/customers")]
public class MyController : Controller
{
 [HttpGet]
 public List<Customer> Get()
 {
   //gets all customer logic
 }

 [HttpGet]
 [Route("currentMonth")]
 public List<Customer> GetCustomerByCurrentMonth()
 {
     //gets some customer 
 }

 [HttpGet]
 [Route("{id}")]
 public Customer GetCustomerById(string id)
 {
  //gets a single customer by specified id
 }
 [HttpGet]
 [Route("customerByUsername/{username}")]
 public Customer GetCustomerByUsername(string username)
 {
    //gets customer by its username
 }
}

What does <T> (angle brackets) mean in Java?

It is related to generics in java. If I mentioned ArrayList<String> that means I can add only String type object to that ArrayList.

The two major benefits of generics in Java are:

  1. Reducing the number of casts in your program, thus reducing the number of potential bugs in your program.
  2. Improving code clarity

jQuery date formatting

I'm not quite sure if I'm allowed to answer a question that was asked like 2 years ago as this is my first answer on stackoverflow but, here's my solution;

If you once retrieved the date from your MySQL database, split it and then use the splitted values.

$(document).ready(function () {
    var datefrommysql = $('.date-from-mysql').attr("date");
    var arraydate = datefrommysql.split('.');
    var yearfirstdigit = arraydate[2][2];
    var yearlastdigit = arraydate[2][3];
    var day = arraydate[0];
    var month = arraydate[1];
    $('.formatted-date').text(day + "/" + month + "/" + yearfirstdigit + yearlastdigit);
});

Here's a fiddle.

How to detect escape key press with pure JS or jQuery?

The keydown event will work fine for Escape and has the benefit of allowing you to use keyCode in all browsers. Also, you need to attach the listener to document rather than the body.

Update May 2016

keyCode is now in the process of being deprecated and most modern browsers offer the key property now, although you'll still need a fallback for decent browser support for now (at time of writing the current releases of Chrome and Safari don't support it).

Update September 2018 evt.key is now supported by all modern browsers.

_x000D_
_x000D_
document.onkeydown = function(evt) {_x000D_
    evt = evt || window.event;_x000D_
    var isEscape = false;_x000D_
    if ("key" in evt) {_x000D_
        isEscape = (evt.key === "Escape" || evt.key === "Esc");_x000D_
    } else {_x000D_
        isEscape = (evt.keyCode === 27);_x000D_
    }_x000D_
    if (isEscape) {_x000D_
        alert("Escape");_x000D_
    }_x000D_
};
_x000D_
Click me then press the Escape key
_x000D_
_x000D_
_x000D_

What's the difference between a 302 and a 307 redirect?

The difference concerns redirecting POST, PUT and DELETE requests and what the expectations of the server are for the user agent behavior (RFC 2616):

Note: RFC 1945 and RFC 2068 specify that the client is not allowed to change the method on the redirected request. However, most existing user agent implementations treat 302 as if it were a 303 response, performing a GET on the Location field-value regardless of the original request method. The status codes 303 and 307 have been added for servers that wish to make unambiguously clear which kind of reaction is expected of the client.

Also, read Wikipedia article on the 30x redirection codes.

Why not use Double or Float to represent currency?

I'm troubled by some of these responses. I think doubles and floats have a place in financial calculations. Certainly, when adding and subtracting non-fractional monetary amounts there will be no loss of precision when using integer classes or BigDecimal classes. But when performing more complex operations, you often end up with results that go out several or many decimal places, no matter how you store the numbers. The issue is how you present the result.

If your result is on the borderline between being rounded up and rounded down, and that last penny really matters, you should be probably be telling the viewer that the answer is nearly in the middle - by displaying more decimal places.

The problem with doubles, and more so with floats, is when they are used to combine large numbers and small numbers. In java,

System.out.println(1000000.0f + 1.2f - 1000000.0f);

results in

1.1875

Best practices for circular shift (rotate) operations in C++

--- Substituting RLC in 8051 C for speed --- Rotate left carry
Here is an example using RLC to update a serial 8 bit DAC msb first:
                               (r=DACVAL, P1.4= SDO, P1.5= SCLK)
MOV     A, r
?1:
MOV     B, #8
RLC     A
MOV     P1.4, C
CLR     P1.5
SETB    P1.5
DJNZ    B, ?1

Here is the code in 8051 C at its fastest:
sbit ACC_7  = ACC ^ 7 ; //define this at the top to access bit 7 of ACC
ACC     =   r;
B       =   8;  
do  {
P1_4    =   ACC_7;  // this assembles into mov c, acc.7  mov P1.4, c 
ACC     <<= 1;
P1_5    =   0;
P1_5    =   1;
B       --  ; 
    } while ( B!=0 );
The keil compiler will use DJNZ when a loop is written this way.
I am cheating here by using registers ACC and B in c code.
If you cannot cheat then substitute with:
P1_4    =   ( r & 128 ) ? 1 : 0 ;
r     <<=   1;
This only takes a few extra instructions.
Also, changing B for a local var char n is the same.
Keil does rotate ACC left by ADD A, ACC which is the same as multiply 2.
It only takes one extra opcode i think.
Keeping code entirely in C keeps things simpler sometimes.

How can I close a dropdown on click outside?

I came across to another solution, inspired by examples with focus/blur event.

So, if you want to achieve the same functionality without attaching global document listener, you may consider as a valid the following example. It works also in Safari and Firefox on OSx, despite they have other handling of button focus event:https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button#Clicking_and_focus

Working example on stackbiz with angular 8: https://stackblitz.com/edit/angular-sv4tbi?file=src%2Ftoggle-dropdown%2Ftoggle-dropdown.directive.ts

HTML markup:

<div class="dropdown">
  <button class="btn btn-secondary dropdown-toggle" type="button" aria-haspopup="true" aria-expanded="false">Dropdown button</button>
  <div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
    <a class="dropdown-item" href="#">Action</a>
    <a class="dropdown-item" href="#">Another action</a>
    <a class="dropdown-item" href="#">Something else here</a>
  </div>
</div>

The directive will look like this:

import { Directive, HostBinding, ElementRef, OnDestroy, Renderer2 } from '@angular/core';

@Directive({
  selector: '.dropdown'
})
export class ToggleDropdownDirective {

  @HostBinding('class.show')
  public isOpen: boolean;

  private buttonMousedown: () => void;
  private buttonBlur: () => void;
  private navMousedown: () => void;
  private navClick: () => void;

  constructor(private element: ElementRef, private renderer: Renderer2) { }

  ngAfterViewInit() {
    const el = this.element.nativeElement;
    const btnElem = el.querySelector('.dropdown-toggle');
    const menuElem = el.querySelector('.dropdown-menu');

    this.buttonMousedown = this.renderer.listen(btnElem, 'mousedown', (evt) => {
      console.log('MOUSEDOWN BTN');
      this.isOpen = !this.isOpen;
      evt.preventDefault(); // prevents loose of focus (default behaviour) on some browsers
    });

    this.buttonMousedown = this.renderer.listen(btnElem, 'click', () => {
      console.log('CLICK BTN');
      // firefox OSx, Safari, Ie OSx, Mobile browsers.
      // Whether clicking on a <button> causes it to become focused varies by browser and OS.
      btnElem.focus();
    });

    // only for debug
    this.buttonMousedown = this.renderer.listen(btnElem, 'focus', () => {
      console.log('FOCUS BTN');
    });

    this.buttonBlur = this.renderer.listen(btnElem, 'blur', () => {
      console.log('BLUR BTN');
      this.isOpen = false;
    });

    this.navMousedown = this.renderer.listen(menuElem, 'mousedown', (evt) => {
      console.log('MOUSEDOWN MENU');
      evt.preventDefault(); // prevents nav element to get focus and button blur event to fire too early
    });
    this.navClick = this.renderer.listen(menuElem, 'click', () => {
      console.log('CLICK MENU');
      this.isOpen = false;
      btnElem.blur();
    });
  }

  ngOnDestroy() {
    this.buttonMousedown();
    this.buttonBlur();
    this.navMousedown();
    this.navClick();
  }
}

malloc for struct and pointer in C

No, you're not allocating memory for y->x twice.

Instead, you're allocating memory for the structure (which includes a pointer) plus something for that pointer to point to.

Think of it this way:

         1          2
        +-----+    +------+
y------>|  x------>|  *x  |
        |  n  |    +------+
        +-----+

So you actually need the two allocations (1 and 2) to store everything.

Additionally, your type should be struct Vector *y since it's a pointer, and you should never cast the return value from malloc in C since it can hide certain problems you don't want hidden - C is perfectly capable of implicitly converting the void* return value to any other pointer.

And, of course, you probably want to encapsulate the creation of these vectors to make management of them easier, such as with:

struct Vector {
    double *data;    // no place for x and n in readable code :-)
    size_t size;
};

struct Vector *newVector (size_t sz) {
    // Try to allocate vector structure.

    struct Vector *retVal = malloc (sizeof (struct Vector));
    if (retVal == NULL)
        return NULL;

    // Try to allocate vector data, free structure if fail.

    retVal->data = malloc (sz * sizeof (double));
    if (retVal->data == NULL) {
        free (retVal);
        return NULL;
    }

    // Set size and return.

    retVal->size = sz;
    return retVal;
}

void delVector (struct Vector *vector) {
    // Can safely assume vector is NULL or fully built.

    if (vector != NULL) {
        free (vector->data);
        free (vector);
    }
}

By encapsulating the creation like that, you ensure that vectors are either fully built or not built at all - there's no chance of them being half-built. It also allows you to totally change the underlying data structures in future without affecting clients (for example, if you wanted to make them sparse arrays to trade off space for speed).

How to add one day to a date?

This will increase any date by exactly one

String untildate="2011-10-08";//can take any date in current format    
SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd" );   
Calendar cal = Calendar.getInstance();    
cal.setTime( dateFormat.parse(untildate));    
cal.add( Calendar.DATE, 1 );    
String convertedDate=dateFormat.format(cal.getTime());    
System.out.println("Date increase by one.."+convertedDate);

What are the differences between LDAP and Active Directory?

Short Summary

Active Directory is a directory services implemented by Microsoft, and it supports Lightweight Directory Access Protocol (LDAP).

Long Answer

Firstly, one needs to know what's Directory Service.

Directory Service is a software system that stores, organises, and provides access to information in a computer operating system's directory. In software engineering, a directory is a map between names and values. It allows the lookup of named values, similar to a dictionary.

For more details, read https://en.wikipedia.org/wiki/Directory_service

Secondly,as one could imagine, different vendors implement all kinds of forms of directory service, which is harmful to multi-vendor interoperability.

Thirdly, so in the 1980s, the ITU and ISO came up with a set of standards - X.500, for directory services, initially to support the requirements of inter-carrier electronic messaging and network name lookup.

Fourthly, so based on this standard, Lightweight Directory Access Protocol, LDAP, is developed. It uses the TCP/IP stack and a string encoding scheme of the X.500 Directory Access Protocol (DAP), giving it more relevance on the Internet.

Lastly, based on this LDAP/X.500 stack, Microsoft implemented a modern directory service for Windows, originating from the X.500 directory, created for use in Exchange Server. And this implementation is called Active Directory.

So in a short summary, Active Directory is a directory services implemented by Microsoft, and it supports Lightweight Directory Access Protocol (LDAP).

PS[0]: This answer heavily copies content from the wikipedia page listed above.

PS[1]: To know why it may be better use directory service rather just using a relational database, read https://en.wikipedia.org/wiki/Directory_service#Comparison_with_relational_databases

Error: request entity too large

2016, none of the above worked for me until i explicity set the 'type' in addition to the 'limit' for bodyparser, example:

  var app = express();
  var jsonParser       = bodyParser.json({limit:1024*1024*20, type:'application/json'});
  var urlencodedParser = bodyParser.urlencoded({ extended:true,limit:1024*1024*20,type:'application/x-www-form-urlencoded' })

  app.use(jsonParser);
  app.use(urlencodedParser);

Oracle DateTime in Where Clause?

Yes: TIME_CREATED contains a date and a time. Use TRUNC to strip the time:

SELECT EMP_NAME, DEPT
FROM EMPLOYEE
WHERE TRUNC(TIME_CREATED) = TO_DATE('26/JAN/2011','dd/mon/yyyy')

UPDATE:
As Dave Costa points out in the comment below, this will prevent Oracle from using the index of the column TIME_CREATED if it exists. An alternative approach without this problem is this:

SELECT EMP_NAME, DEPT
FROM EMPLOYEE
WHERE TIME_CREATED >= TO_DATE('26/JAN/2011','dd/mon/yyyy') 
      AND TIME_CREATED < TO_DATE('26/JAN/2011','dd/mon/yyyy') + 1

Button button = findViewById(R.id.button) always resolves to null in Android Studio

This is because findViewById() searches in the activity_main layout, while the button is located in the fragment's layout fragment_main.

Move that piece of code in the onCreateView() method of the fragment:

//...

View rootView = inflater.inflate(R.layout.fragment_main, container, false);
Button buttonClick = (Button)rootView.findViewById(R.id.button);
buttonClick.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        onButtonClick((Button) view);
    }
});

Notice that now you access it through rootView view:

Button buttonClick = (Button)rootView.findViewById(R.id.button);

otherwise you would get again NullPointerException.

webpack is not recognized as a internal or external command,operable program or batch file

Sometimes npm install -g webpack does not save properly. Better to use npm install webpack --save . It worked for me.

Sites not accepting wget user agent header

I created a ~/.wgetrc file with the following content (obtained from askapache.com but with a newer user agent, because otherwise it didn’t work always):

header = Accept-Language: en-us,en;q=0.5
header = Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
header = Connection: keep-alive
user_agent = Mozilla/5.0 (X11; Fedora; Linux x86_64; rv:40.0) Gecko/20100101 Firefox/40.0
referer = /
robots = off

Now I’m able to download from most (all?) file-sharing (streaming video) sites.

Matplotlib scatterplot; colour as a function of a third variable

There's no need to manually set the colors. Instead, specify a grayscale colormap...

import numpy as np
import matplotlib.pyplot as plt

# Generate data...
x = np.random.random(10)
y = np.random.random(10)

# Plot...
plt.scatter(x, y, c=y, s=500)
plt.gray()

plt.show()

enter image description here

Or, if you'd prefer a wider range of colormaps, you can also specify the cmap kwarg to scatter. To use the reversed version of any of these, just specify the "_r" version of any of them. E.g. gray_r instead of gray. There are several different grayscale colormaps pre-made (e.g. gray, gist_yarg, binary, etc).

import matplotlib.pyplot as plt
import numpy as np

# Generate data...
x = np.random.random(10)
y = np.random.random(10)

plt.scatter(x, y, c=y, s=500, cmap='gray')
plt.show()

What is the difference between MOV and LEA?

It depends on the used assembler, because

mov ax,table_addr

in MASM works as

mov ax,word ptr[table_addr]

So it loads the first bytes from table_addr and NOT the offset to table_addr. You should use instead

mov ax,offset table_addr

or

lea ax,table_addr

which works the same.

lea version also works fine if table_addr is a local variable e.g.

some_procedure proc

local table_addr[64]:word

lea ax,table_addr

Docker CE on RHEL - Requires: container-selinux >= 2.9

I was getting the same error Requires: container-selinux >= 2.9 on amazon ec2 instance(Rhel7)

I tried to add extra package rmp repo by executing sudo yum-config-manager --enable rhui-REGION-rhel-server-extras
but it works. followed steps from https://installdocker.blogspot.com/ and I was able to install docker.

Issue with parsing the content from json file with Jackson & message- JsonMappingException -Cannot deserialize as out of START_ARRAY token

As said, JsonMappingException: out of START_ARRAY token exception is thrown by Jackson object mapper as it's expecting an Object {} whereas it found an Array [{}] in response.

A simpler solution could be replacing the method getLocations with:

public static List<Location> getLocations(InputStream inputStream) {
    ObjectMapper objectMapper = new ObjectMapper();
    try {
        TypeReference<List<Location>> typeReference = new TypeReference<>() {};
        return objectMapper.readValue(inputStream, typeReference);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

On the other hand, if you don't have a pojo like Location, you could use:

TypeReference<List<Map<String, Object>>> typeReference = new TypeReference<>() {};
return objectMapper.readValue(inputStream, typeReference);

jQuery: serialize() form and other parameters

serialize() effectively turns the form values into a valid querystring, as such you can simply append to the string:

$.ajax({
    type : 'POST',
    url : 'url',
    data : $('#form').serialize() + "&par1=1&par2=2&par3=232"
}

Unicode character as bullet for list-item in CSS

ul {
    list-style-type: none;    
}

ul li:before {
    content:'*'; /* Change this to unicode as needed*/
    width: 1em !important;
    margin-left: -1em;
    display: inline-block;
}

How to Set a Custom Font in the ActionBar Title?

The Calligraphy library let's you set a custom font through the app theme, which would also apply to the action bar.

<style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">
<item name="android:textViewStyle">@style/AppTheme.Widget.TextView</item>
</style>

<style name="AppTheme.Widget"/>

<style name="AppTheme.Widget.TextView" parent="android:Widget.Holo.Light.TextView">
   <item name="fontPath">fonts/Roboto-ThinItalic.ttf</item>
</style>

All it takes to activate Calligraphy is attaching it to your Activity context:

@Override
protected void attachBaseContext(Context newBase) {
    super.attachBaseContext(new CalligraphyContextWrapper(newBase));
}

The default custom attribute is fontPath, but you may provide your own custom attribute for the path by initializing it in your Application class with CalligraphyConfig.Builder. Usage of android:fontFamily has been discouraged.

Inline style to act as :hover in CSS

I'm afraid it can't be done, the pseudo-class selectors can't be set in-line, you'll have to do it on the page or on a stylesheet.

I should mention that technically you should be able to do it according to the CSS spec, but most browsers don't support it

Edit: I just did a quick test with this:

<a href="test.html" style="{color: blue; background: white} 
            :visited {color: green}
            :hover {background: yellow}
            :visited:hover {color: purple}">Test</a>

And it doesn't work in IE7, IE8 beta 2, Firefox or Chrome. Can anyone else test in any other browsers?

Can't open file 'svn/repo/db/txn-current-lock': Permission denied

3 Steps you can follow

  1. chmod -R 775 <repo path>  
    ---> change permissions of repository
    
  2. chown -R apache:apache <repo path>  
    ---> change owner of svn repository
    
  3. chcon -R -t httpd_sys_content_t <repo path>  
    ----> change SELinux security context of the svn repository
    

C++ variable has initializer but incomplete type?

It's not related to Ken's case directly, but such an error also can occur if you copied .h file and forgot to change #ifndef directive. In this case compiler will just skip definition of the class thinking that it's a duplication.

How to print to console using swift playground?

for displaying variables only in playground, just mention the variable name without anything

let stat = 100

stat // this outputs the value of stat on playground right window

Where does Chrome store cookies?

On Windows the path is:

C:\Users\<current_user>\AppData\Local\Google\Chrome\User Data\<Profile 1>\Cookies(Type:File)

Chrome doesn't store each cookies in separate text file. It stores all of the cookies together in a single file in the profile folder. That file is not readable.

string.IsNullOrEmpty(string) vs. string.IsNullOrWhiteSpace(string)

Check this out with IsNullOrEmpty and IsNullOrwhiteSpace

string sTestes = "I like sweat peaches";
    Stopwatch stopWatch = new Stopwatch();
    stopWatch.Start();
    for (int i = 0; i < 5000000; i++)
    {
        for (int z = 0; z < 500; z++)
        {
            var x = string.IsNullOrEmpty(sTestes);// OR string.IsNullOrWhiteSpace
        }
    }

    stopWatch.Stop();
    // Get the elapsed time as a TimeSpan value.
    TimeSpan ts = stopWatch.Elapsed;
    // Format and display the TimeSpan value. 
    string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
        ts.Hours, ts.Minutes, ts.Seconds,
        ts.Milliseconds / 10);
    Console.WriteLine("RunTime " + elapsedTime);
    Console.ReadLine();

You'll see that IsNullOrWhiteSpace is much slower :/

Find the maximum value in a list of tuples in Python

Use max():

 
Using itemgetter():

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

In [81]: from operator import itemgetter

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

using lambda:

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

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

timeit comparison:

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

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

Stream file using ASP.NET MVC FileContentResult in a browser with a name?

public FileContentResult GetImage(int productId) { 
     Product prod = repository.Products.FirstOrDefault(p => p.ProductID == productId); 
     if (prod != null) { 
         return File(prod.ImageData, prod.ImageMimeType); 
      } else { 
         return null; 
     } 
}

This compilation unit is not on the build path of a Java project

Another alternative to Loganathan Mohanraj's solution (which effectively does the same, but from the GUI):

  1. Right-Click on your project
  2. Go to "Properties"
  3. Choose "Project Natures"
  4. Click on "Add"
  5. Choose "Java"
  6. Click "Apply and Close"

Where can I find the default timeout settings for all browsers?

For Google Chrome (Tested on ver. 62)

I was trying to keep a socket connection alive from the google chrome's fetch API to a remote express server and found the request headers have to match Node.JS's native <net.socket> connection settings.

I set the headers object on my client-side script with the following options:

/* ----- */
head = new headers();
head.append("Connnection", "keep-alive")
head.append("Keep-Alive", `timeout=${1*60*5}`) //in seconds, not milliseconds
/* apply more definitions to the header */
fetch(url, {
    method: 'OPTIONS',
    credentials: "include",
    body: JSON.stringify(data),
    cors: 'cors',
    headers: head, //could be object literal too
    cache: 'default'
 })
 .then(response=>{
    ....
  }).catch(err=>{...});

And on my express server I setup my router as follows:

 router.head('absolute or regex', (request, response, next)=>{
  req.setTimeout(1000*60*5, ()=>{
     console.info("socket timed out");
   });
  console.info("Proceeding down the middleware chain link...\n\n");
  next();
 });

 /*Keep the socket alive by enabling it on the server, with an optional 
  delay on the last packet sent 
 */
server.on('connection', (socket)=>socket.setKeepAlive(true, 10))

WARNING

Please use common sense and make sure the users you're keeping the socket connection open to is validated and serialized. It works for Firefox as well, but it's really vulnerable if you keep the TCP connection open for longer than 5 minutes.

I'm not sure how some of the lesser known browsers operate, but I'll append to this answer with the Microsoft browser details as well.

Send response to all clients except sender

use this coding

io.sockets.on('connection', function (socket) {

    socket.on('mousemove', function (data) {

        socket.broadcast.emit('moving', data);
    });

this socket.broadcast.emit() will emit everthing in the function except to the server which is emitting

How to get the number of threads in a Java process

    public class MainClass {

        public static void main(String args[]) {

          Thread t = Thread.currentThread();
          t.setName("My Thread");

          t.setPriority(1);

          System.out.println("current thread: " + t);

          int active = Thread.activeCount();
          System.out.println("currently active threads: " + active);
          Thread all[] = new Thread[active];
          Thread.enumerate(all);

          for (int i = 0; i < active; i++) {
             System.out.println(i + ": " + all[i]);
          }
       }
   }

how to move elasticsearch data from one server to another

I tried on ubuntu to move data from ELK 2.4.3 to ELK 5.1.1

Following are the steps

$ sudo apt-get update

$ sudo apt-get install -y python-software-properties python g++ make

$ sudo add-apt-repository ppa:chris-lea/node.js

$ sudo apt-get update

$ sudo apt-get install npm

$ sudo apt-get install nodejs

$ npm install colors

$ npm install nomnom

$ npm install elasticdump

in home directory goto

$ cd node_modules/elasticdump/

execute the command

If you need basic http auth, you can use it like this:

--input=http://name:password@localhost:9200/my_index

Copy an index from production:

$ ./bin/elasticdump --input="http://Source:9200/Sourceindex" --output="http://username:password@Destination:9200/Destination_index"  --type=data

Generate Java classes from .XSD files...?

Using Eclipse IDE:-

  1. copy the xsd into a new/existing project.
  2. Make sure you have JAXB required JARs in you classpath. You can download one here.
  3. Right click on the XSD file -> Generate -> JAXB classes.

How to compare data between two table in different databases using Sql Server 2008?

Comparing the two Databases in SQL Database. Try this Query it may help.

SELECT T.[name] AS [table_name], AC.[name] AS [column_name],  TY.[name] AS 
   system_data_type FROM    [***Database Name 1***].sys.[tables] AS T  
   INNER JOIN [***Database Name 1***].sys.[all_columns] AC ON T.[object_id] = AC.[object_id]      
   INNER JOIN [***Database Name 1***].sys.[types] TY ON AC.[system_type_id] = TY.[system_type_id] 
   EXCEPT SELECT T.[name] AS [table_name], AC.[name] AS [column_name], TY.[name] AS system_data_type FROM    ***Database Name 2***.sys.[tables] AS T  
   INNER JOIN ***Database Name 2***.sys.[all_columns] AC ON T.[object_id] = AC.[object_id]  
   INNER JOIN ***Database Name 2***.sys.[types] TY ON AC.[system_type_id] = TY.[system_type_id]

How (and why) to use display: table-cell (CSS)

After days trying to find the answer, I finally found

display: table;

There was surprisingly very little information available online about how to actually getting it to work, even here, so on to the "How":

To use this fantastic piece of code, you need to think back to when tables were the only real way to structure HTML, namely the syntax. To get a table with 2 rows and 3 columns, you'd have to do the following:

<table>
    <tr>
        <td></td>
        <td></td>
        <td></td>
    </tr>
    <tr>
        <td></td>
        <td></td>
        <td></td>
    </tr>
</table>

Similarly to get CSS to do it, you'd use the following:

HTML

<div id="table">
    <div class="tr">
        <div class="td"></div>
        <div class="td"></div>
        <div class="td"></div>
    </div>
    <div class="tr">
        <div class="td"></div>
        <div class="td"></div>
        <div class="td"></div>
    </div>
</div>

CSS

#table{ 
    display: table; 
}
.tr{ 
    display: table-row; 
}
.td{ 
    display: table-cell; }

As you can see in the JSFiddle example below, the divs in the 3rd column have no content, yet are respecting the auto height set by the text in the first 2 columns. WIN!

http://jsfiddle.net/blyzz/1djs97yv/1/

It's worth noting that display: table; does not work in IE6 or 7 (thanks, FelipeAls), so depending on your needs with regards to browser compatibility, this may not be the answer that you are seeking.

Real mouse position in canvas

You can get the mouse positions by using this snippet:

function getMousePos(canvas, evt) {
    var rect = canvas.getBoundingClientRect();
    return {
        x: (evt.clientX - rect.left) / (rect.right - rect.left) * canvas.width,
        y: (evt.clientY - rect.top) / (rect.bottom - rect.top) * canvas.height
    };
}

This code takes into account both changing coordinates to canvas space (evt.clientX - rect.left) and scaling when canvas logical size differs from its style size (/ (rect.right - rect.left) * canvas.width see: Canvas width and height in HTML5).

Example: http://jsfiddle.net/sierawski/4xezb7nL/

Source: jerryj comment on http://www.html5canvastutorials.com/advanced/html5-canvas-mouse-coordinates/

Why would one mark local variables and method parameters as "final" in Java?

Because of the (occasionally) confusing nature of Java's "pass by reference" behavior I definitely agree with finalizing parameter var's.

Finalizing local var's seems somewhat overkill IMO.

Manually Set Value for FormBuilder Control

Tip: If you're using setValue but not providing every property on the form you'll get an error:

Must supply a value for form control with name: 'stateOrProvince'.

So you may be tempted to use patchValue, but this can be dangerous if you're trying to update a whole form. I have an address that may not have stateOrProvince or stateCd depending upon whether it is US or worldwide.

Instead you can update like this - which will use the nulls as defaults:

this.form.setValue( { stateOrProvince: null, stateCd: null, ...address } );

Remote debugging a Java application

For JDK 1.3 or earlier :

-Xnoagent -Djava.compiler=NONE -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=6006

For JDK 1.4

-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=6006

For newer JDK :

-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=6006

Please change the port number based on your needs.

From java technotes

From 5.0 onwards the -agentlib:jdwp option is used to load and specify options to the JDWP agent. For releases prior to 5.0, the -Xdebug and -Xrunjdwp options are used (the 5.0 implementation also supports the -Xdebug and -Xrunjdwp options but the newer -agentlib:jdwp option is preferable as the JDWP agent in 5.0 uses the JVM TI interface to the VM rather than the older JVMDI interface)

One more thing to note, from JVM Tool interface documentation:

JVM TI was introduced at JDK 5.0. JVM TI replaces the Java Virtual Machine Profiler Interface (JVMPI) and the Java Virtual Machine Debug Interface (JVMDI) which, as of JDK 6, are no longer provided.

BeautifulSoup getText from between <p>, not picking up subsequent paragraphs

This works well for specific articles where the text is all wrapped in <p> tags. Since the web is an ugly place, it's not always the case.

Often, websites will have text scattered all over, wrapped in different types of tags (e.g. maybe in a <span> or a <div>, or an <li>).

To find all text nodes in the DOM, you can use soup.find_all(text=True).

This is going to return some undesired text, like the contents of <script> and <style> tags. You'll need to filter out the text contents of elements you don't want.

blacklist = [
  'style',
  'script',
  # other elements,
]

text_elements = [t for t in soup.find_all(text=True) if t.parent.name not in blacklist]

If you are working with a known set of tags, you can tag the opposite approach:

whitelist = [
  'p'
]

text_elements = [t for t in soup.find_all(text=True) if t.parent.name in whitelist]

Having trouble setting working directory

This may help... use the following code and browse the folder you want to set as the working folder

setwd(choose.dir())

How to make div's percentage width relative to parent div and not viewport

Use position: relative on the parent element.

Also note that had you not added any position attributes to any of the divs you wouldn't have seen this behavior. Juan explains further.

Splitting a table cell into two columns in HTML

https://jsfiddle.net/SyedFayaz/ud0mpgoh/7/

<table class="table-bordered">
  <col />
  <col />
  <col />
  <colgroup span="4"></colgroup>
  <col />
  <tr>
    <th rowspan="2" style="vertical-align: middle; text-align: center">
      S.No.
    </th>
    <th rowspan="2" style="vertical-align: middle; text-align: center">Item</th>
    <th rowspan="2" style="vertical-align: middle; text-align: center">
      Description
    </th>
    <th
      colspan="3"
      style="horizontal-align: middle; text-align: center; width: 50%"
    >
      Items
    </th>
    <th rowspan="2" style="vertical-align: middle; text-align: center">
      Rejected Reason
    </th>
  </tr>
  <tr>
    <th scope="col">Order</th>
    <th scope="col">Received</th>
    <th scope="col">Accepted</th>
  </tr>
  <tr>
    <th>1</th>
    <td>Watch</td>
    <td>Analog</td>
    <td>100</td>
    <td>75</td>
    <td>25</td>
    <td>Not Functioning</td>
  </tr>
  <tr>
    <th>2</th>
    <td>Pendrive</td>
    <td>5GB</td>
    <td>250</td>
    <td>165</td>
    <td>85</td>
    <td>Not Working</td>
  </tr>
</table>

Android Studio says "cannot resolve symbol" but project compiles

Invalidate Caches didn't work for me (this time). For me it was enough changing the gradle and syncing again. Or https://stackoverflow.com/a/29565362/2000162

How to query MongoDB with "like"?

  • split name string by space and make array of words
  • map to iterate loop and convert string to regex of each word of name

_x000D_
_x000D_
let name = "My Name".split(" ").map(n => new RegExp(n));
console.log(name);
_x000D_
_x000D_
_x000D_

Result:

[/My/, /Name/]

Try $in Expressions, To include a regular expression in an $in query expression, you can only use JavaScript regular expression objects (i.e. /pattern/ ). For example:

db.users.find({ name: { $in: name } }); // name = [/My/, /Name/]

How do I manage MongoDB connections in a Node.js web application?

Best approach to implement connection pooling is you should create one global array variable which hold db name with connection object returned by MongoClient and then reuse that connection whenever you need to contact Database.

  1. In your Server.js define var global.dbconnections = [];

  2. Create a Service naming connectionService.js. It will have 2 methods getConnection and createConnection. So when user will call getConnection(), it will find detail in global connection variable and return connection details if already exists else it will call createConnection() and return connection Details.

  3. Call this service using db_name and it will return connection object if it already have else it will create new connection and return it to you.

Hope it helps :)

Here is the connectionService.js code:

var mongo = require('mongoskin');
var mongodb = require('mongodb');
var Q = require('q');
var service = {};
service.getConnection = getConnection ;
module.exports = service;

function getConnection(appDB){
    var deferred = Q.defer();
    var connectionDetails=global.dbconnections.find(item=>item.appDB==appDB)

    if(connectionDetails){deferred.resolve(connectionDetails.connection);
    }else{createConnection(appDB).then(function(connectionDetails){
            deferred.resolve(connectionDetails);})
    }
    return deferred.promise;
}

function createConnection(appDB){
    var deferred = Q.defer();
    mongodb.MongoClient.connect(connectionServer + appDB, (err,database)=> 
    {
        if(err) deferred.reject(err.name + ': ' + err.message);
        global.dbconnections.push({appDB: appDB,  connection: database});
        deferred.resolve(database);
    })
     return deferred.promise;
} 

Splitting a string into chunks of a certain size

Personally I prefer my solution :-)

It handles:

  • String lengths that are a multiple of the chunk size.
  • String lengths that are NOT a multiple of the chunk size.
  • String lengths that are smaller than the chunk size.
  • NULL and empty strings (throws an exception).
  • Chunk sizes smaller than 1 (throws an exception).

It is implemented as a extension method, and it calculates the number of chunks is going to generate beforehand. It checks the last chunk because in case the text length is not a multiple it needs to be shorter. Clean, short, easy to understand... and works!

    public static string[] Split(this string value, int chunkSize)
    {
        if (string.IsNullOrEmpty(value)) throw new ArgumentException("The string cannot be null.");
        if (chunkSize < 1) throw new ArgumentException("The chunk size should be equal or greater than one.");

        int remainder;
        int divResult = Math.DivRem(value.Length, chunkSize, out remainder);

        int numberOfChunks = remainder > 0 ? divResult + 1 : divResult;
        var result = new string[numberOfChunks];

        int i = 0;
        while (i < numberOfChunks - 1)
        {
            result[i] = value.Substring(i * chunkSize, chunkSize);
            i++;
        }

        int lastChunkSize = remainder > 0 ? remainder : chunkSize;
        result[i] = value.Substring(i * chunkSize, lastChunkSize);

        return result;
    }

Deleting multiple elements from a list

An alternative list comprehension method that uses list index values:

stuff = ['a', 'b', 'c', 'd', 'e', 'f', 'woof']
index = [0, 3, 6]
new = [i for i in stuff if stuff.index(i) not in index]

This returns:

['b', 'c', 'e', 'f']

Find first and last day for previous calendar month in SQL Server Reporting Services (VB.Net)

Randall, here are the VB expressions I found to work in SSRS to obtain the first and last days of any month, using the current month as a reference:

First day of last month:

=dateadd("m",-1,dateserial(year(Today),month(Today),1)) 

First day of this month:

=dateadd("m",0,dateserial(year(Today),month(Today),1)) 

First day of next month:

=dateadd("m",1,dateserial(year(Today),month(Today),1)) 

Last day of last month:

=dateadd("m",0,dateserial(year(Today),month(Today),0))

Last day of this month:

=dateadd("m",1,dateserial(year(Today),month(Today),0))

Last day of next month:

=dateadd("m",2,dateserial(year(Today),month(Today),0))

The MSDN documentation for the VisualBasic DateSerial(year,month,day) function explains that the function accepts values outside the expected range for the year, month, and day parameters. This allows you to specify useful date-relative values. For instance, a value of 0 for Day means "the last day of the preceding month". It makes sense: that's the day before day 1 of the current month.

Difference between <context:annotation-config> and <context:component-scan>

The difference between the two is really simple!.

<context:annotation-config /> 

Enables you to use annotations that are restricted to wiring up properties and constructors only of beans!.

Where as

<context:component-scan base-package="org.package"/> 

Enables everything that <context:annotation-config /> can do, with addition of using stereotypes eg.. @Component, @Service , @Repository. So you can wire entire beans and not just restricted to constructors or properties!.

XML Serialize generic list of serializable objects

You can't serialize a collection of objects without specifying the expected types. You must pass the list of expected types to the constructor of XmlSerializer (the extraTypes parameter) :

List<object> list = new List<object>();
list.Add(new Foo());
list.Add(new Bar());

XmlSerializer xs = new XmlSerializer(typeof(object), new Type[] {typeof(Foo), typeof(Bar)});
using (StreamWriter streamWriter = System.IO.File.CreateText(fileName))
{
    xs.Serialize(streamWriter, list);
}

If all the objects of your list inherit from the same class, you can also use the XmlInclude attribute to specify the expected types :

[XmlInclude(typeof(Foo)), XmlInclude(typeof(Bar))]
public class MyBaseClass
{
}

Combine two OR-queries with AND in Mongoose

It's probably easiest to create your query object directly as:

  Test.find({
      $and: [
          { $or: [{a: 1}, {b: 1}] },
          { $or: [{c: 1}, {d: 1}] }
      ]
  }, function (err, results) {
      ...
  }

But you can also use the Query#and helper that's available in recent 3.x Mongoose releases:

  Test.find()
      .and([
          { $or: [{a: 1}, {b: 1}] },
          { $or: [{c: 1}, {d: 1}] }
      ])
      .exec(function (err, results) {
          ...
      });

Use Font Awesome Icon in Placeholder

Sometimes above all answer not woking, when you can use below trick

_x000D_
_x000D_
.form-group {_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
input {_x000D_
  padding-left: 1rem;_x000D_
}_x000D_
_x000D_
i {_x000D_
  position: absolute;_x000D_
  left: 0;_x000D_
  top: 50%;_x000D_
  transform: translateY(-50%);_x000D_
}
_x000D_
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css">_x000D_
_x000D_
<form role="form">_x000D_
  <div class="form-group">_x000D_
    <input type="text" class="form-control empty" id="iconified" placeholder="search">_x000D_
    <i class="fas fa-search"></i>_x000D_
  </div>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Wait some seconds without blocking UI execution

Omar's solution is decent* if you cannot upgrade your environment to .NET 4.5 in order to gain access to the async and await APIs. That said, there here is one important change that should be made in order to avoid poor performance. A slight delay should be added between calls to Application.DoEvents() in order to prevent excessive CPU usage. By adding

Thread.Sleep(1);

before the call to Application.DoEvents(), you can add such a delay (1 millisecond) and prevent the application from using all of the cpu cycles available to it.

private void WaitNSeconds(int seconds)
{
    if (seconds < 1) return;
    DateTime _desired = DateTime.Now.AddSeconds(seconds);
    while (DateTime.Now < _desired) {
         Thread.Sleep(1);
         System.Windows.Forms.Application.DoEvents();
    }
}

*See https://blog.codinghorror.com/is-doevents-evil/ for a more detailed discussion on the potential pitfalls of using Application.DoEvents().

JPA - Returning an auto generated id after persist()

This is how I did it:

EntityManager entityManager = getEntityManager();
EntityTransaction transaction = entityManager.getTransaction();
transaction.begin();
entityManager.persist(object);
transaction.commit();
long id = object.getId();
entityManager.close();

Passing array in GET for a REST call

As @Ravi_MCA mentioned, /users?ids[]=id1&ids[]=id2 worked for me, too.


When you want to send an array through PATCH or POST method, it's better to use JSON or XML. (I use JSON)
In HTTP Request body you should follow like this:

{"params":["arg1", "arg2", ...]}

You can even use JSON object instead of array.

SQL to LINQ Tool

Edit 7/17/2020: I cannot delete this accepted answer. It used to be good, but now it isn't. Beware really old posts, guys. I'm removing the link.

[Linqer] is a SQL to LINQ converter tool. It helps you to learn LINQ and convert your existing SQL statements.

Not every SQL statement can be converted to LINQ, but Linqer covers many different types of SQL expressions. Linqer supports both .NET languages - C# and Visual Basic.

Get a list of URLs from a site

wget from a linux box might also be a good option as there are switches to spider and change it's output.

EDIT: wget is also available on Windows: http://gnuwin32.sourceforge.net/packages/wget.htm

Convert Java Array to Iterable

Integer foo[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };

List<Integer> list = Arrays.asList(foo);
// or
Iterable<Integer> iterable = Arrays.asList(foo);

Though you need to use an Integer array (not an int array) for this to work.

For primitives, you can use guava:

Iterable<Integer> fooBar = Ints.asList(foo);
<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>15.0</version>
    <type>jar</type>
</dependency>

For Java8: (from Jin Kwon's answer)

final int[] arr = {1, 2, 3};
final PrimitiveIterator.OfInt i1 = Arrays.stream(arr).iterator();
final PrimitiveIterator.OfInt i2 = IntStream.of(arr).iterator();
final Iterator<Integer> i3 = IntStream.of(arr).boxed().iterator();

Escape a string for a sed replace pattern

It turns out you're asking the wrong question. I also asked the wrong question. The reason it's wrong is the beginning of the first sentence: "In my bash script...".

I had the same question & made the same mistake. If you're using bash, you don't need to use sed to do string replacements (and it's much cleaner to use the replace feature built into bash).

Instead of something like, for example:

function escape-all-funny-characters() { UNKNOWN_CODE_THAT_ANSWERS_THE_QUESTION_YOU_ASKED; }
INPUT='some long string with KEYWORD that need replacing KEYWORD.'
A="$(escape-all-funny-characters 'KEYWORD')"
B="$(escape-all-funny-characters '<funny characters here>')"
OUTPUT="$(sed "s/$A/$B/g" <<<"$INPUT")"

you can use bash features exclusively:

INPUT='some long string with KEYWORD that need replacing KEYWORD.'
A='KEYWORD'
B='<funny characters here>'
OUTPUT="${INPUT//"$A"/"$B"}"

space between divs - display table-cell

You can use border-spacing property:

HTML:

<div class="table">
    <div class="row">
        <div class="cell">Cell 1</div>
        <div class="cell">Cell 2</div>
    </div>
</div>

CSS:

.table {
  display: table;
  border-collapse: separate;
  border-spacing: 10px;
}

.row { display:table-row; }

.cell {
  display:table-cell;
  padding:5px;
  background-color: gold;
}

JSBin Demo

Any other option?

Well, not really.

Why?

  • margin property is not applicable to display: table-cell elements.
  • padding property doesn't create space between edges of the cells.
  • float property destroys the expected behavior of table-cell elements which are able to be as tall as their parent element.

Using CSS for a fade-in effect on page load

In response to @A.M.K's question about how to do transitions without jQuery. A very simple example I threw together. If I had time to think this through some more, I might be able to eliminate the JavaScript code altogether:

<style>
    body {
        background-color: red;
        transition: background-color 2s ease-in;
    }
</style>

<script>
    window.onload = function() {
        document.body.style.backgroundColor = '#00f';
    }
</script>

<body>
    <p>test</p>
</body>

Get current folder path

for .NET CORE use System.AppContext.BaseDirectory

(as a replacement for AppDomain.CurrentDomain.BaseDirectory)

How to call Stored Procedure in a View?

If you are using Sql Server 2005 you can use table valued functions. You can call these directly and pass paramters, whilst treating them as if they were tables.

For more info check out Table-Valued User-Defined Functions

Finding element in XDocument?

You should use Root to refer to the root element:

xmlFile.Root.Elements("Band")

If you want to find elements anywhere in the document use Descendants instead:

xmlFile.Descendants("Band")

Apache HttpClient Android (Gradle)

Working gradle dependency

Try this:

compile 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'

How to use goto statement correctly

If you look up continue and break they accept a "Label". Experiment with that. Goto itself won't work.

public class BreakContinueWithLabel {

    public static void main(String args[]) {

        int[] numbers= new int[]{100,18,21,30};

        //Outer loop checks if number is multiple of 2
        OUTER:  //outer label
        for(int i = 0; i<numbers.length; i++){
            if(i % 2 == 0){
                System.out.println("Odd number: " + i +
                                   ", continue from OUTER label");
                continue OUTER;
            }

            INNER:
            for(int j = 0; j<numbers.length; j++){
                System.out.println("Even number: " + i +
                                   ", break  from INNER label");
                break INNER;
            }
        }      
    }
}

Read more

constant pointer vs pointer on a constant value

Trying to answer in simple way:

char * const a;  => a is (const) constant (*) pointer of type char {L <- R}. =>( Constant Pointer )
const char * a;  => a is (*) pointer to char constant             {L <- R}. =>( Pointer to Constant)

Constant Pointer:

pointer is constant !!. i.e, the address it is holding can't be changed. It will be stored in read only memory.

Let's try to change the address of pointer to understand more:

char * const a = &b; 
char c;
a = &c; // illegal , you can't change the address. `a` is const at L-value, so can't change. `a` is read-only variable.

It means once constant pointer points some thing it is forever.

pointer a points only b.

However you can change the value of b eg:

char b='a';
char * const a =&b;

printf("\n print a  : [%c]\n",*a);
*a = 'c';
printf("\n now print a  : [%c]\n",*a);

Pointer to Constant:

Value pointed by the pointer can't be changed.

const char *a;
char b = 'b';
const char * a =&b;
char c;
a=&c; //legal

*a = 'c'; // illegal , *a is pointer to constant can't change!.

How do I add a .click() event to an image?

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.js"></script> 
<script type="text/javascript" src="jquery-2.1.0.js"></script> 
<script type="text/javascript" >
function openOnImageClick()
{
//alert("Jai Sh Raam");
// document.getElementById("images").src = "fruits.jpg";
 var img = document.createElement('img');
 img.setAttribute('src', 'tiger.jpg');
  img.setAttribute('width', '200');
   img.setAttribute('height', '150');
  document.getElementById("images").appendChild(img);


}


</script>
</head>
<body>

<h1>Screen Shot View</h1>
<p>Click the Tiger to display the Image</p>

<div id="images" >
</div>

<img src="tiger.jpg" width="100" height="50" alt="unfinished bingo card" onclick="openOnImageClick()" />
<img src="Logo1.jpg" width="100" height="50" alt="unfinished bingo card" onclick="openOnImageClick()" />

</body>
</html> 

Python executable not finding libpython shared library

I had the same problem and I solved it this way:

If you know where libpython resides at, I supposed it would be /usr/local/lib/libpython2.7.so.1.0 in your case, you can just create a symbolic link to it:

sudo ln -s /usr/local/lib/libpython2.7.so.1.0 /usr/lib/libpython2.7.so.1.0

Then try running ldd again and see if it worked.

What is a "callback" in C and how are they implemented?

Here is an example of callbacks in C.

Let's say you want to write some code that allows registering callbacks to be called when some event occurs.

First define the type of function used for the callback:

typedef void (*event_cb_t)(const struct event *evt, void *userdata);

Now, define a function that is used to register a callback:

int event_cb_register(event_cb_t cb, void *userdata);

This is what code would look like that registers a callback:

static void my_event_cb(const struct event *evt, void *data)
{
    /* do stuff and things with the event */
}

...
   event_cb_register(my_event_cb, &my_custom_data);
...

In the internals of the event dispatcher, the callback may be stored in a struct that looks something like this:

struct event_cb {
    event_cb_t cb;
    void *data;
};

This is what the code looks like that executes a callback.

struct event_cb *callback;

...

/* Get the event_cb that you want to execute */

callback->cb(event, callback->data);

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

A workaround - at least for the minimum size: You can use grid to manage the frames contained in root and make them follow the grid size by setting sticky='nsew'. Then you can use root.grid_rowconfigure and root.grid_columnconfigure to set values for minsize like so:

from tkinter import Frame, Tk

class MyApp():
    def __init__(self):
        self.root = Tk()

        self.my_frame_red = Frame(self.root, bg='red')
        self.my_frame_red.grid(row=0, column=0, sticky='nsew')

        self.my_frame_blue = Frame(self.root, bg='blue')
        self.my_frame_blue.grid(row=0, column=1, sticky='nsew')

        self.root.grid_rowconfigure(0, minsize=200, weight=1)
        self.root.grid_columnconfigure(0, minsize=200, weight=1)
        self.root.grid_columnconfigure(1, weight=1)

        self.root.mainloop()

if __name__ == '__main__':
    app = MyApp()

But as Brian wrote (in 2010 :D) you can still resize the window to be smaller than the frame if you don't limit its minsize.

What function is to replace a substring from a string in C?

You can use strrep()

char* strrep ( const char * cadena, const char * strf, const char * strr )

strrep (String Replace). Replaces 'strf' with 'strr' in 'cadena' and returns the new string. You need to free the returned string in your code after using strrep.

Parameters cadena The string with the text. strf The text to find. strr The replacement text.

Returns The text updated wit the replacement.

Project can be found at https://github.com/ipserc/strrep

Decompile an APK, modify it and then recompile it

Thanks to Chris Jester-Young I managed to make it work!

I think the way I managed to do it will work only on really simple projects:

  • With Dex2jar I obtained the Jar.
  • With jd-gui I convert my Jar back to Java files.
  • With apktool i got the android manifest and the resources files.

  • In Eclipse I create a new project with the same settings as the old one (checking all the information in the manifest file)

  • When the project is created I'm replacing all the resources and the manifest with the ones I obtained with apktool
  • I paste the java files I extracted from the Jar in the src folder (respecting the packages)
  • I modify those files with what I need
  • Everything is compiling!

/!\ be sure you removed the old apk from the device an error will be thrown stating that the apk signature is not the same as the old one!

sed fails with "unknown option to `s'" error

The problem is with slashes: your variable contains them and the final command will be something like sed "s/string/path/to/something/g", containing way too many slashes.

Since sed can take any char as delimiter (without having to declare the new delimiter), you can try using another one that doesn't appear in your replacement string:

replacement="/my/path"
sed --expression "s@pattern@$replacement@"

Note that this is not bullet proof: if the replacement string later contains @ it will break for the same reason, and any backslash sequences like \1 will still be interpreted according to sed rules. Using | as a delimiter is also a nice option as it is similar in readability to /.

Random number from a range in a Bash Script

You can do this

cat /dev/urandom|od -N2 -An -i|awk -v f=2000 -v r=65000 '{printf "%i\n", f + r * $1 / 65536}'

If you need more details see Shell Script Random Number Generator.

How to get selenium to wait for ajax response?

Below is my code for fetch. Took me while researching because jQuery.active doesn't work with fetch. Here is the answer helped me proxy fetch, but its only for ajax not fetch mock for selenium

public static void customPatchXMLHttpRequest(WebDriver driver) {
    try {
        if (driver instanceof JavascriptExecutor) {
            JavascriptExecutor jsDriver = (JavascriptExecutor) driver;
            Object numberOfAjaxConnections = jsDriver.executeScript("return window.openHTTPs");
            if (numberOfAjaxConnections instanceof Long) {
                return;
            }
            String script = "  (function() {" + "var oldFetch = fetch;"
                    + "window.openHTTPs = 0; console.log('starting xhttps');" + "fetch = function(input,init ){ "
                    + "window.openHTTPs++; "

                    + "return oldFetch(input,init).then( function (response) {"
                    + "      if (response.status >= 200 && response.status < 300) {"
                    + "          window.openHTTPs--;  console.log('Call completed. Remaining active calls: '+ window.openHTTPs); return response;"
                    + "      } else {"
                    + "          window.openHTTPs--; console.log('Call fails. Remaining active calls: ' + window.openHTTPs);  return response;"
                    + "      };})" + "};" + "var oldOpen = XMLHttpRequest.prototype.open;"
                    + "XMLHttpRequest.prototype.open = function(method, url, async, user, pass) {"
                    + "window.openHTTPs++; console.log('xml ajax called');"
                    + "this.addEventListener('readystatechange', function() {" + "if(this.readyState == 4) {"
                    + "window.openHTTPs--; console.log('xml ajax complete');" + "}" + "}, false);"
                    + "oldOpen.call(this, method, url, async, user, pass);" + "}" +

                    "})();";
            jsDriver.executeScript(script);
        } else {
            System.out.println("Web driver: " + driver + " cannot execute javascript");
        }
    } catch (Exception e) {
        System.out.println(e);
    }
}

How to change file encoding in NetBeans?

There is an old Bugreport concerning this issue.

html5: display video inside canvas

Using canvas to display Videos

Displaying a video is much the same as displaying an image. The minor differences are to do with onload events and the fact that you need to render the video every frame or you will only see one frame not the animated frames.

The demo below has some minor differences to the example. A mute function (under the video click mute/sound on to toggle sound) and some error checking to catch IE9+ and Edge if they don't have the correct drivers.

Keeping answers current.

The previous answers by user372551 is out of date (December 2010) and has a flaw in the rendering technique used. It uses the setTimeout and a rate of 33.333..ms which setTimeout will round down to 33ms this will cause the frames to be dropped every two seconds and may drop many more if the video frame rate is any higher than 30. Using setTimeout will also introduce video shearing created because setTimeout can not be synced to the display hardware.

There is currently no reliable method that can determine a videos frame rate unless you know the video frame rate in advance you should display it at the maximum display refresh rate possible on browsers. 60fps

The given top answer was for the time (6 years ago) the best solution as requestAnimationFrame was not widely supported (if at all) but requestAnimationFrame is now standard across the Major browsers and should be used instead of setTimeout to reduce or remove dropped frames, and to prevent shearing.

The example demo.

Loads a video and set it to loop. The video will not play until the you click on it. Clicking again will pause. There is a mute/sound on button under the video. The video is muted by default.

Note users of IE9+ and Edge. You may not be able to play the video format WebM as it needs additional drivers to play the videos. They can be found at tools.google.com Download IE9+ WebM support

_x000D_
_x000D_
// This code is from the example document on stackoverflow documentation. See HTML for link to the example._x000D_
// This code is almost identical to the example. Mute has been added and a media source. Also added some error handling in case the media load fails and a link to fix IE9+ and Edge support._x000D_
// Code by Blindman67._x000D_
_x000D_
_x000D_
// Original source has returns 404_x000D_
// var mediaSource = "http://video.webmfiles.org/big-buck-bunny_trailer.webm";_x000D_
// New source from wiki commons. Attribution in the leading credits._x000D_
var mediaSource = "http://upload.wikimedia.org/wikipedia/commons/7/79/Big_Buck_Bunny_small.ogv"_x000D_
_x000D_
var muted = true;_x000D_
var canvas = document.getElementById("myCanvas"); // get the canvas from the page_x000D_
var ctx = canvas.getContext("2d");_x000D_
var videoContainer; // object to hold video and associated info_x000D_
var video = document.createElement("video"); // create a video element_x000D_
video.src = mediaSource;_x000D_
// the video will now begin to load._x000D_
// As some additional info is needed we will place the video in a_x000D_
// containing object for convenience_x000D_
video.autoPlay = false; // ensure that the video does not auto play_x000D_
video.loop = true; // set the video to loop._x000D_
video.muted = muted;_x000D_
videoContainer = {  // we will add properties as needed_x000D_
     video : video,_x000D_
     ready : false,   _x000D_
};_x000D_
// To handle errors. This is not part of the example at the moment. Just fixing for Edge that did not like the ogv format video_x000D_
video.onerror = function(e){_x000D_
    document.body.removeChild(canvas);_x000D_
    document.body.innerHTML += "<h2>There is a problem loading the video</h2><br>";_x000D_
    document.body.innerHTML += "Users of IE9+ , the browser does not support WebM videos used by this demo";_x000D_
    document.body.innerHTML += "<br><a href='https://tools.google.com/dlpage/webmmf/'> Download IE9+ WebM support</a> from tools.google.com<br> this includes Edge and Windows 10";_x000D_
    _x000D_
 }_x000D_
video.oncanplay = readyToPlayVideo; // set the event to the play function that _x000D_
                                  // can be found below_x000D_
function readyToPlayVideo(event){ // this is a referance to the video_x000D_
    // the video may not match the canvas size so find a scale to fit_x000D_
    videoContainer.scale = Math.min(_x000D_
                         canvas.width / this.videoWidth, _x000D_
                         canvas.height / this.videoHeight); _x000D_
    videoContainer.ready = true;_x000D_
    // the video can be played so hand it off to the display function_x000D_
    requestAnimationFrame(updateCanvas);_x000D_
    // add instruction_x000D_
    document.getElementById("playPause").textContent = "Click video to play/pause.";_x000D_
    document.querySelector(".mute").textContent = "Mute";_x000D_
}_x000D_
_x000D_
function updateCanvas(){_x000D_
    ctx.clearRect(0,0,canvas.width,canvas.height); _x000D_
    // only draw if loaded and ready_x000D_
    if(videoContainer !== undefined && videoContainer.ready){ _x000D_
        // find the top left of the video on the canvas_x000D_
        video.muted = muted;_x000D_
        var scale = videoContainer.scale;_x000D_
        var vidH = videoContainer.video.videoHeight;_x000D_
        var vidW = videoContainer.video.videoWidth;_x000D_
        var top = canvas.height / 2 - (vidH /2 ) * scale;_x000D_
        var left = canvas.width / 2 - (vidW /2 ) * scale;_x000D_
        // now just draw the video the correct size_x000D_
        ctx.drawImage(videoContainer.video, left, top, vidW * scale, vidH * scale);_x000D_
        if(videoContainer.video.paused){ // if not playing show the paused screen _x000D_
            drawPayIcon();_x000D_
        }_x000D_
    }_x000D_
    // all done for display _x000D_
    // request the next frame in 1/60th of a second_x000D_
    requestAnimationFrame(updateCanvas);_x000D_
}_x000D_
_x000D_
function drawPayIcon(){_x000D_
     ctx.fillStyle = "black";  // darken display_x000D_
     ctx.globalAlpha = 0.5;_x000D_
     ctx.fillRect(0,0,canvas.width,canvas.height);_x000D_
     ctx.fillStyle = "#DDD"; // colour of play icon_x000D_
     ctx.globalAlpha = 0.75; // partly transparent_x000D_
     ctx.beginPath(); // create the path for the icon_x000D_
     var size = (canvas.height / 2) * 0.5;  // the size of the icon_x000D_
     ctx.moveTo(canvas.width/2 + size/2, canvas.height / 2); // start at the pointy end_x000D_
     ctx.lineTo(canvas.width/2 - size/2, canvas.height / 2 + size);_x000D_
     ctx.lineTo(canvas.width/2 - size/2, canvas.height / 2 - size);_x000D_
     ctx.closePath();_x000D_
     ctx.fill();_x000D_
     ctx.globalAlpha = 1; // restore alpha_x000D_
}    _x000D_
_x000D_
function playPauseClick(){_x000D_
     if(videoContainer !== undefined && videoContainer.ready){_x000D_
          if(videoContainer.video.paused){                                 _x000D_
                videoContainer.video.play();_x000D_
          }else{_x000D_
                videoContainer.video.pause();_x000D_
          }_x000D_
     }_x000D_
}_x000D_
function videoMute(){_x000D_
    muted = !muted;_x000D_
 if(muted){_x000D_
         document.querySelector(".mute").textContent = "Mute";_x000D_
    }else{_x000D_
         document.querySelector(".mute").textContent= "Sound on";_x000D_
    }_x000D_
_x000D_
_x000D_
}_x000D_
// register the event_x000D_
canvas.addEventListener("click",playPauseClick);_x000D_
document.querySelector(".mute").addEventListener("click",videoMute)
_x000D_
body {_x000D_
    font :14px  arial;_x000D_
    text-align : center;_x000D_
    background : #36A;_x000D_
}_x000D_
h2 {_x000D_
    color : white;_x000D_
}_x000D_
canvas {_x000D_
    border : 10px white solid;_x000D_
    cursor : pointer;_x000D_
}_x000D_
a {_x000D_
  color : #F93;_x000D_
}_x000D_
.mute {_x000D_
    cursor : pointer;_x000D_
    display: initial;   _x000D_
}
_x000D_
<h2>Basic Video & canvas example</h2>_x000D_
<p>Code example from Stackoverflow Documentation HTML5-Canvas<br>_x000D_
<a href="https://stackoverflow.com/documentation/html5-canvas/3689/media-types-and-the-canvas/14974/basic-loading-and-playing-a-video-on-the-canvas#t=201607271638099201116">Basic loading and playing a video on the canvas</a></p>_x000D_
<canvas id="myCanvas" width = "532" height ="300" ></canvas><br>_x000D_
<h3><div id = "playPause">Loading content.</div></h3>_x000D_
<div class="mute"></div><br>_x000D_
<div style="font-size:small">Attribution in the leading credits.</div><br>
_x000D_
_x000D_
_x000D_

Canvas extras

Using the canvas to render video gives you additional options in regard to displaying and mixing in fx. The following image shows some of the FX you can get using the canvas. Using the 2D API gives a huge range of creative possibilities.

Image relating to answer Fade canvas video from greyscale to color Video filters "Lighten", "Black & white", "Sepia", "Saturate", and "Negative"

See video title in above demo for attribution of content in above inmage.

Format certain floating dataframe columns into percentage in pandas

style.format is vectorized, so we can simply apply it to the entire df (or just its numerical columns):

df[num_cols].style.format('{:,.3f}')

JSON string to JS object

the string in your question is not a valid json string. From json.org website:

JSON is built on two structures:

* A collection of name/value pairs. In various languages, this is 
  realized as an object, record, struct, dictionary, hash table, keyed list, or
  associative array.
* An ordered list of values. In most languages, this is realized as an
  array, vector, list, or sequence.

Basically a json string will always start with either { or [.

Then as @Andy E and @Cryo said you can parse the string with json2.js or some other libraries.

IMHO you should avoid eval because it will any javascript program, so you might incur in security issues.

Convert string to decimal, keeping fractions

You can try calling this method in you program:

static double string_double(string s)
    {
        double temp = 0;
        double dtemp = 0;
        int b = 0;
        for (int i = 0; i < s.Length; i++)
        {
            if (s[i] == '.')
            {
                i++;
                while (i < s.Length)
                {
                    dtemp = (dtemp * 10) + (int)char.GetNumericValue(s[i]);
                    i++;
                    b++;
                }
                temp = temp + (dtemp * Math.Pow(10, -b));
                return temp;
            }
            else
            {
                temp = (temp * 10) + (int)char.GetNumericValue(s[i]);
            }
        }
        return -1; //if somehow failed
    }

Example:

string s = "12.3";
double d = string_double (s);        //d = 12.3 

How do I find the length/number of items present for an array?

I'm not sure that i know exactly what you mean.

But to get the length of an initialized array,

doesn't strlen(string) work ??

How can I wait for set of asynchronous callback functions?

You can emulate it like this:

  countDownLatch = {
     count: 0,
     check: function() {
         this.count--;
         if (this.count == 0) this.calculate();
     },
     calculate: function() {...}
  };

then each async call does this:

countDownLatch.count++;

while in each asynch call back at the end of the method you add this line:

countDownLatch.check();

In other words, you emulate a count-down-latch functionality.

Variables not showing while debugging in Eclipse

I ended up trying something easy by resetting the Debug perspective, which seemed to work:

Window => Perspective => Reset Perspective...

Thanks for the comments.

How to calculate the time interval between two time strings

import datetime as dt
from dateutil.relativedelta import relativedelta

start = "09:35:23"
end = "10:23:00"
start_dt = dt.datetime.strptime(start, "%H:%M:%S")
end_dt = dt.datetime.strptime(end, "%H:%M:%S")
timedelta_obj = relativedelta(start_dt, end_dt)
print(
    timedelta_obj.years,
    timedelta_obj.months,
    timedelta_obj.days,
    timedelta_obj.hours,
    timedelta_obj.minutes,
    timedelta_obj.seconds,
)

result: 0 0 0 0 -47 -37

How can I find the method that called the current method?

private static MethodBase GetCallingMethod()
{
  return new StackFrame(2, false).GetMethod();
}

private static Type GetCallingType()
{
  return new StackFrame(2, false).GetMethod().DeclaringType;
}

A fantastic class is here: http://www.csharp411.com/c-get-calling-method/

Maximum number of rows in an MS Access database engine table?

Practical = 'useful in practice' - so the best you're going to get is anecdotal. Everything else is just prototyping and testing results.

I agree with others - determining 'a max quantity of records' is completely dependent on schema - # tables, # fields, # indexes.

Another anecdote for you: I recently hit 1.6GB file size with 2 primary data stores (tables), of 36 and 85 fields respectively, with some subset copies in 3 additional tables.

Who cares if data is unique or not - only material if context says it is. Data is data is data, unless duplication affects handling by the indexer.

The total row counts making up that 1.6GB is 1.72M.

Python 2.7.10 error "from urllib.request import urlopen" no module named request

Instead of using urllib.request.urlopen() remove request for python 2.

urllib.urlopen() you do not have to request in python 2.x for what you are trying to do. Hope it works for you. This was tested using python 2.7 I was receiving the same error message and this resolved it.

Converting string to numeric

As csgillespie said. stringsAsFactors is default on TRUE, which converts any text to a factor. So even after deleting the text, you still have a factor in your dataframe.

Now regarding the conversion, there's a more optimal way to do so. So I put it here as a reference :

> x <- factor(sample(4:8,10,replace=T))
> x
 [1] 6 4 8 6 7 6 8 5 8 4
Levels: 4 5 6 7 8
> as.numeric(levels(x))[x]
 [1] 6 4 8 6 7 6 8 5 8 4

To show it works.

The timings :

> x <- factor(sample(4:8,500000,replace=T))
> system.time(as.numeric(as.character(x)))
   user  system elapsed 
   0.11    0.00    0.11 
> system.time(as.numeric(levels(x))[x])
   user  system elapsed 
      0       0       0 

It's a big improvement, but not always a bottleneck. It gets important however if you have a big dataframe and a lot of columns to convert.

creating list of objects in Javascript

dynamically build list of objects

var listOfObjects = [];
var a = ["car", "bike", "scooter"];
a.forEach(function(entry) {
    var singleObj = {};
    singleObj['type'] = 'vehicle';
    singleObj['value'] = entry;
    listOfObjects.push(singleObj);
});

here's a working example http://jsfiddle.net/b9f6Q/2/ see console for output

Python constructors and __init__

coonstructors are called automatically when you create a new object, thereby "constructing" the object. The reason you can have more than one init is because names are just references in python, and you are allowed to change what each variable references whenever you want (hence dynamic typing)

def func(): #now func refers to an empty funcion
    pass
...
func=5      #now func refers to the number 5
def func():
    print "something"    #now func refers to a different function

in your class definition, it just keeps the later one

Forward X11 failed: Network error: Connection refused

fill in the "X display location" did not work for me. but install MobaXterm did the job.

Set View Width Programmatically

This code let you fill the banner to the maximum width and keep the ratio. This will only work in portrait. You must recreate the ad when you rotate the device. In landscape you should just leave the ad as is because it will be quite big an blurred.

Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
double ratio = ((float) (width))/300.0;
int height = (int)(ratio*50);

AdView adView = new AdView(this,"ad_url","my_ad_key",true,true);
LinearLayout layout = (LinearLayout) findViewById(R.id.testing);
mAdView.setLayoutParams(new FrameLayout.LayoutParams(LayoutParams.FILL_PARENT,height));
adView.setAdListener(this);
layout.addView(adView);

Removing input background colour for Chrome autocomplete?

We can use the -webkit-autofill pseudo-selector to target those fields and style them as we see fit. The default styling only affects the background color, but most other properties apply here, such as border and font-size. We can even change the color of the text using -webkit-text-fill-color which is included in the snippet below.

/* Change Autocomplete styles in Chrome*/

input:-webkit-autofill,
input:-webkit-autofill:hover, 
input:-webkit-autofill:focus,
textarea:-webkit-autofill,
textarea:-webkit-autofill:hover,
textarea:-webkit-autofill:focus,
select:-webkit-autofill,
select:-webkit-autofill:hover,
select:-webkit-autofill:focus {
  border: 1px solid green;
  -webkit-text-fill-color: green;
  -webkit-box-shadow: 0 0 0px 1000px #000 inset;
  transition: background-color 5000s ease-in-out 0s;
}

Getting an Embedded YouTube Video to Auto Play and Loop

Playlist hack didn't work for me either. Working workaround for September 2018 (bonus: set width and height by CSS for #yt-wrap instead of hard-coding it in JS):

<div id="yt-wrap">
    <!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
    <div id="ytplayer"></div>
</div>

<script>
  // 2. This code loads the IFrame Player API code asynchronously.
  var tag = document.createElement('script');
  tag.src = "https://www.youtube.com/player_api";
  var firstScriptTag = document.getElementsByTagName('script')[0];
  firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

  // 3. This function creates an <iframe> (and YouTube player)
  //    after the API code downloads.
  var player;
  function onYouTubePlayerAPIReady() {
    player = new YT.Player('ytplayer', {
      width: '100%',
      height: '100%',
      videoId: 'VIDEO_ID',
      events: {
        'onReady': onPlayerReady,
        'onStateChange': onPlayerStateChange
      }
    });
  }

  // 4. The API will call this function when the video player is ready.
  function onPlayerReady(event) {
    event.target.playVideo();
    player.mute(); // comment out if you don't want the auto played video muted
  }

  // 5. The API calls this function when the player's state changes.
  //    The function indicates that when playing a video (state=1),
  //    the player should play for six seconds and then stop.
  function onPlayerStateChange(event) {
    if (event.data == YT.PlayerState.ENDED) {
      player.seekTo(0);
      player.playVideo();
    }
  }
  function stopVideo() {
    player.stopVideo();
  }
</script>

'tsc command not found' in compiling typescript

Easy fix for Mac I found. Just run these commands:

sudo npm install -g concurrently
sudo npm install -g lite-server
sudo npm install -g typescript

Nothing worked except this for me.

Is it possible to cast a Stream in Java 8?

Late to the party, but I think it is a useful answer.

flatMap would be the shortest way to do it.

Stream.of(objects).flatMap(o->(o instanceof Client)?Stream.of((Client)o):Stream.empty())

If o is a Client then create a Stream with a single element, otherwise use the empty stream. These streams will then be flattened into a Stream<Client>.

How to stop INFO messages displaying on spark console?

Adding the following to the PySpark did the job for me:

self.spark.sparkContext.setLogLevel("ERROR")

self.spark is the spark session (self.spark = spark_builder.getOrCreate())

Pie chart with jQuery

Chart.js is quite useful, supporting numerous other types of charts as well.

It can be used both with jQuery and without.

How to $watch multiple variable change in angular

There is many way to watch multiple values :

//angular 1.1.4
$scope.$watchCollection(['foo', 'bar'], function(newValues, oldValues){
    // do what you want here
});

or more recent version

//angular 1.3
$scope.$watchGroup(['foo', 'bar'], function(newValues, oldValues, scope) {
  //do what you want here
});

Read official doc for more informations : https://docs.angularjs.org/api/ng/type/$rootScope.Scope

How to enable MySQL Query Log?

I use this method for logging when I want to quickly optimize different page loads. It's a little tip...

Logging to a TABLE

SET global general_log = 1;
SET global log_output = 'table';

You can then select from my mysql.general_log table to retrieve recent queries.

I can then do something similar to tail -f on the mysql.log, but with more refinements...

select * from mysql.general_log 
where  event_time  > (now() - INTERVAL 8 SECOND) and thread_id not in(9 , 628)
and argument <> "SELECT 1" and argument <> "" 
and argument <> "SET NAMES 'UTF8'"  and argument <> "SHOW STATUS"  
and command_type = "Query"  and argument <> "SET PROFILING=1"

This makes it easy to see my queries that I can try and cut back. I use 8 seconds interval to only fetch queries executed within the last 8 seconds.

Python: Select subset from list based on index set

I see 2 options.

  1. Using numpy:

    property_a = numpy.array([545., 656., 5.4, 33.])
    property_b = numpy.array([ 1.2,  1.3, 2.3, 0.3])
    good_objects = [True, False, False, True]
    good_indices = [0, 3]
    property_asel = property_a[good_objects]
    property_bsel = property_b[good_indices]
    
  2. Using a list comprehension and zip it:

    property_a = [545., 656., 5.4, 33.]
    property_b = [ 1.2,  1.3, 2.3, 0.3]
    good_objects = [True, False, False, True]
    good_indices = [0, 3]
    property_asel = [x for x, y in zip(property_a, good_objects) if y]
    property_bsel = [property_b[i] for i in good_indices]
    

Get item in the list in Scala?

Please use parenthesis () to access the list elements list_name(index)

Change the size of a JTextField inside a JBorderLayout

Try to play with

setMinSize()
setMaxSize()
setPreferredSize()

These method are used by layout when it decide what should be the size of current element. The layout manager calls setSize() and actually overrides your values.

How to find out which processes are using swap space in Linux?

Run top then press OpEnter. Now processes should be sorted by their swap usage.

Here is an update as my original answer does not provide an exact answer to the problem as pointed out in the comments. From the htop FAQ:

It is not possible to get the exact size of used swap space of a process. Top fakes this information by making SWAP = VIRT - RES, but that is not a good metric, because other stuff such as video memory counts on VIRT as well (for example: top says my X process is using 81M of swap, but it also reports my system as a whole is using only 2M of swap. Therefore, I will not add a similar Swap column to htop because I don't know a reliable way to get this information (actually, I don't think it's possible to get an exact number, because of shared pages).

How to get day of the month?

LocalDate date = new Date(); date.lengthOfMonth()

or

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("YYYY-MM-dd");

DateTimeFormatter monthFormatter = DateTimeFormatter.ofPattern("MMM");

String stringDate = formatter.format(date);

String month = monthFormatter.format(date);

How to store a byte array in Javascript

var array = new Uint8Array(100);    
array[10] = 256;
array[10] === 0 // true

I verified in firefox and chrome, its really an array of bytes :

var array = new Uint8Array(1024*1024*50);  // allocates 50MBytes

How to generate random number in Bash?

A bash function that uses perl to generate a random number of n digits. Specify either the number of digits or a template of n 0s.

rand() {
  perl -E '$ARGV[0]||=""; $ARGV[0]=int($ARGV[0])||length($ARGV[0]); say join "", int(rand(9)+1)*($ARGV[0]?1:0), map { int(rand(10)) } (0..($ARGV[0]||0)-2)' $1
}

Usage:

$ rand 3
381
$ rand 000
728

Demonstration of calling rand n, for n between 0 and 15:

$ for n in {0..15}; do printf "%02d: %s\n" $n $(rand $n); done
00: 0
01: 3
02: 98
03: 139
04: 1712
05: 49296
06: 426697
07: 2431421
08: 82727795
09: 445682186
10: 6368501779
11: 51029574113
12: 602518591108
13: 5839716875073
14: 87572173490132
15: 546889624135868

Demonstration of calling rand n, for n a template of 0s between length 0 and 15

$ for n in {0..15}; do printf "%15s :%02d: %s\n" $(printf "%0${n}d" 0) $n $(rand $(printf "%0${n}d" 0)); done
              0 :00: 0
              0 :01: 0
             00 :02: 70
            000 :03: 201
           0000 :04: 9751
          00000 :05: 62237
         000000 :06: 262860
        0000000 :07: 1365194
       00000000 :08: 83953419
      000000000 :09: 838521776
     0000000000 :10: 2355011586
    00000000000 :11: 95040136057
   000000000000 :12: 511889225898
  0000000000000 :13: 7441263049018
 00000000000000 :14: 11895209107156
000000000000000 :15: 863219624761093

Autoresize View When SubViews are Added

Yes, it is because you are using auto layout. Setting the view frame and resizing mask will not work.

You should read Working with Auto Layout Programmatically and Visual Format Language.

You will need to get the current constraints, add the text field, adjust the contraints for the text field, then add the correct constraints on the text field.

python list in sql query as parameter

Just use inline if operation with tuple function:

query = "Select * from hr_employee WHERE id in " % tuple(employee_ids) if len(employee_ids) != 1 else "("+ str(employee_ids[0]) + ")"

Javascript : get <img> src and set as variable?

If you don't have an id on the image but have a parent div this is also a technique you can use.

<div id="myDiv"><img src="http://www.example.com/image.png"></div>

var myVar = document.querySelectorAll('#myDiv img')[0].src

How can I get date in application run by node.js?

You would use the javascript date object:

MDN documentation for the Date object

var d = new Date();

Binary numbers in Python

I think you're confused about what binary is. Binary and decimal are just different representations of a number - e.g. 101 base 2 and 5 base 10 are the same number. The operations add, subtract, and compare operate on numbers - 101 base 2 == 5 base 10 and addition is the same logical operation no matter what base you're working in.

Angular2 equivalent of $document.ready()

In order to use jQuery inside Angular only declare the $ as following: declare var $: any;

In git how is fetch different than pull and how is merge different than rebase?

Merge - HEAD branch will generate a new commit, preserving the ancestry of each commit history. History can become polluted if merge commits are made by multiple people who work on the same branch in parallel.

Rebase - Re-writes the changes of one branch onto another without creating a new commit. The code history is simplified, linear and readable but it doesn't work with pull requests, because you can't see what minor changes someone made.

I would use git merge when dealing with feature-based workflow or if I am not familiar with rebase. But, if I want a more a clean, linear history then git rebase is more appropriate. For more details be sure to check out this merge or rebase article.

Regex: match everything but specific pattern

How about not using regex:

// In PHP
0 !== strpos($string, 'index.php')

Shorten string without cutting words in JavaScript

Didn't find the voted solutions satisfactory. So I wrote something thats is kind of generic and works both first and last part of your text (something like substr but for words). Also you can set if you'd like the spaces to be left out in the char-count.

    function chopTxtMinMax(txt, firstChar, lastChar=0){
        var wordsArr = txt.split(" ");
        var newWordsArr = [];

        var totalIteratedChars = 0;
        var inclSpacesCount = true;

        for(var wordIndx in wordsArr){
            totalIteratedChars += wordsArr[wordIndx].length + (inclSpacesCount ? 1 : 0);
            if(totalIteratedChars >= firstChar && (totalIteratedChars <= lastChar || lastChar==0)){
                newWordsArr.push(wordsArr[wordIndx]);
            }
        }

        txt = newWordsArr.join(" ");
        return txt;
    }

ERROR:'keytool' is not recognized as an internal or external command, operable program or batch file

Easy, just find the location where keytool executable is, normally is in java/jre(Version)/bin forexample in my computer is in C:\Program Files\Java\jre7\bin. all you have to do is go to environment variables, click PATH to make it active, then click edit, then add complete path where your keytool is, for me i will add C:\Program Files\Java\jre7\bin this will allow you to execute keytool commands without going to the directory where keytool is installed.

Make a td fixed size (width,height) while rest of td's can expand

just set the width of the td/column you want to be fixed and the rest will expand.

<td width="200"></td>

How to use bitmask?

Bit masking is "useful" to use when you want to store (and subsequently extract) different data within a single data value.

An example application I've used before is imagine you were storing colour RGB values in a 16 bit value. So something that looks like this:

RRRR RGGG GGGB BBBB

You could then use bit masking to retrieve the colour components as follows:

  const unsigned short redMask   = 0xF800;
  const unsigned short greenMask = 0x07E0;
  const unsigned short blueMask  = 0x001F;

  unsigned short lightGray = 0x7BEF;

  unsigned short redComponent   = (lightGray & redMask) >> 11;
  unsigned short greenComponent = (lightGray & greenMask) >> 5;
  unsigned short blueComponent =  (lightGray & blueMask);

What is the correct "-moz-appearance" value to hide dropdown arrow of a <select> element

Update: this was fixed in Firefox v35. See the full gist for details.


== how to hide the select arrow in Firefox ==

Just figured out how to do it. The trick is to use a mix of -prefix-appearance, text-indent and text-overflow. It is pure CSS and requires no extra markup.

select {
    -moz-appearance: none;
    text-indent: 0.01px;
    text-overflow: '';
}

Long story short, by pushing it a tiny bit to the right, the overflow gets rid of the arrow. Pretty neat, huh?

More details on this gist I just wrote. Tested on Ubuntu, Mac and Windows, all with recent Firefox versions.

Pandas split DataFrame by column value

You can use boolean indexing:

df = pd.DataFrame({'Sales':[10,20,30,40,50], 'A':[3,4,7,6,1]})
print (df)
   A  Sales
0  3     10
1  4     20
2  7     30
3  6     40
4  1     50

s = 30

df1 = df[df['Sales'] >= s]
print (df1)
   A  Sales
2  7     30
3  6     40
4  1     50

df2 = df[df['Sales'] < s]
print (df2)
   A  Sales
0  3     10
1  4     20

It's also possible to invert mask by ~:

mask = df['Sales'] >= s
df1 = df[mask]
df2 = df[~mask]
print (df1)
   A  Sales
2  7     30
3  6     40
4  1     50

print (df2)
   A  Sales
0  3     10
1  4     20

print (mask)
0    False
1    False
2     True
3     True
4     True
Name: Sales, dtype: bool

print (~mask)
0     True
1     True
2    False
3    False
4    False
Name: Sales, dtype: bool

React - How to pass HTML tags in props?

For me It worked by passing html tag in props children

<MyComponent>This is <strong>not</strong> working.</MyComponent>


var MyComponent = React.createClass({

   render: function() {
    return (
      <div>this.props.children</div>
    );
   },

How to tell if a <script> tag failed to load

This trick worked for me, although I admit that this is probably not the best way to solve this problem. Instead of trying this, you should see why the javascripts aren't loading. Try keeping a local copy of the script in your server, etc. or check with the third party vendor from where you are trying to download the script.

Anyways, so here's the workaround: 1) Initialize a variable to false 2) Set it to true when the javascript loads (using the onload attribute) 3) check if the variable is true or false once the HTML body has loaded

<html>
  <head>
    <script>
      var scriptLoaded = false;

      function checkScriptLoaded() {
        if (scriptLoaded) {
          // do something here
        } else {
          // do something else here!
        }
      }
    </script>
    <script src="http://some-external-script.js" onload="scriptLoaded=true;" />
  </head>
  <body onload="checkScriptLoaded()">
    <p>My Test Page!</p>
  </body>
</html>

How to set a cron job to run every 3 hours

Change Minute to be 0. That's it :)

Note: you can check your "crons" in http://cronchecker.net/

Example

Stretch horizontal ul to fit width of div

People hate on tables for non-tabular data, but what you're asking for is exactly what tables are good at. <table width="100%">