Programs & Examples On #Demangler

Shell script current directory?

To print the current working Directory i.e. pwd just type command like:

echo "the PWD is : ${pwd}"

make an html svg object also a clickable link

This is very late, but I was wondering why energee's solution works: specifically, how the <object> element affects its parent elements.

tl;dr You cannot click on an anchor that has an <object> element in it because the click events are being captured by whatever is inside of the <object> element, which then doesn't bubble it back out.


To expand on the symptom described in the original question: not only will an <object> element inside an anchor element cause the anchor to become unclickable, it seems that an <object> element as a child of any element will cause click, mousedown, and mouseup events (possibly touch events too) to not fire on the parent element, (when you are clicking inside the <object>'s bounding rect.)

    <object type="image/svg+xml" data="">
    .addEventListener('click', console.log) // will not fire

Now, <object> elements behave somewhat "like" <iframe>s, in the sense that they will establish new browsing contexts, including when the content is an <svg> document. In JavaScript, this is manifested through the existence of the HTMLObjectElement.contentDocument and HTMLObjectElement.contentWindow properties.

This means that if you add an event listener to the <svg> element inside the <object>:

    .contentDocument  // returns null if cross-origin: the same-origin policy
    .addEventListener('click', console.log)

and then click on the image, you will see the events being fired.

Then it becomes clear why the pointer-events: none; solution works:

  • Without this style, any MouseEvent that is considered "interactive" (such as click and mousedown, but not mouseenter) is sent to the nested browsing context inside the <object>, which will never bubble out of it.

  • With this style, the MouseEvents aren't sent into the <object> in the first place, then the <object>'s parent elements will receive the events as usual.

This should explain the z-index solution as well: as long as you can prevent click events from being sent to the nested document, the clicking should work as expected.

(In my test, the z-index solution will work as long as the parent element is not inline and the <object> is positioned and has a negative z-index)

(Alternatively, you can find a way to bubble the event back up):

let objectElem = document.querySelector('object')
let svgElemt = objectElem.contentDocument.querySelector('svg')

svgElem.addEventListener('click', () => {
    window.postMessage('Take this click event please.')
    // window being the outermost window

window.addEventListener('message', console.log)

Redirect website after certain amount of time

If you want greater control you can use javascript rather than use the meta tag. This would allow you to have a visual of some kind, e.g. a countdown.

Here is a very basic approach using setTimeout()

    <p>You will be redirected in 3 seconds</p>_x000D_
        var timer = setTimeout(function() {_x000D_
        }, 3000);_x000D_

ImportError: No module named 'selenium'

While pip install might work. Please check the project structure and see if there is no virtual environment already (It is a good practice to have one) created in the project. If there is, activate it with source <name_of_virtual_env>/bin/activate (for MacOS) and venv\Scripts\Activate.ps1 (for Windows powershell) or venv\Scripts\activate.bat (for Windows cmd). then pip install selenium into the environment.

If it isn't, check if you have a virtual environment with virtualenv --version If it displays an error, install it with pip install virtualenv then create a virtual environment with virtualenv <name_of_virtual_env> (Both Windows and MacOS)or

python -m venv <name_of_virtual_env> (Windows Only)

then activate the virtual environment with source <name_of_virtual_env>/bin/activate (for MacOS) and venv\Scripts\Activate.ps1 (for Windows powershell) or venv\Scripts\activate.bat (for Windows cmd). then install selenium with pip install -U selenium (it will install the latest version). If it doesn't display an error, just create a virtual environment in the project, activate it and install selenium inside of it.

Installing tkinter on ubuntu 14.04

To get this to work with pyenv on Ubuntu 16.04, I had to:

$ sudo apt-get install python-tk python3-tk tk-dev

Then install the version of Python I wanted via pyenv:

$ pyenv install 3.6.2

Then I could import tkinter just fine:

import tkinter

MySQL combine two columns into one column

convert(varchar, column_name1) + (varchar, column_name)

error: resource android:attr/fontVariationSettings not found

I have soled the problem by changing target android version to 28 in (target=android-28) and installed cordova-plugin-androidx and cordova-plugin-androidx-adapter.

How do I get the number of elements in a list?

Answering your question as the examples also given previously:

items = []

print items.__len__()

.NET Events - What are object sender & EventArgs e?

  1. 'sender' is called object which has some action perform on some control

  2. 'event' its having some information about control which has some behavoiur and identity perform by some user.when action will generate by occuring for event add it keep within array is called event agrs

Get access to parent control from user control - C#

You can use Control.Parent to get the parent of the control or Control.FindForm to get the first parent Form the control is on. There is a difference between the two in terms of finding forms, so one may be more suitable to use than the other.:

The control's Parent property value might not be the same as the Form returned by FindForm method. For example, if a RadioButton control is contained within a GroupBox control, and the GroupBox is on a Form, the RadioButton control's Parent is the GroupBox and the GroupBox control's Parent is the Form.

Are table names in MySQL case sensitive?

Table names in MySQL are file system entries, so they are case insensitive if the underlying file system is.

Calculate a Running Total in SQL Server

I believe a running total can be achieved using the simple INNER JOIN operation below.

        SELECT 45 AS ID, CAST('01-01-2009' AS DATETIME) AS SomeDate, 3 AS SomeValue
        UNION ALL
        SELECT 23, CAST('01-08-2009' AS DATETIME), 5
        UNION ALL
        SELECT 12, CAST('02-02-2009' AS DATETIME), 0
        UNION ALL
        SELECT 77, CAST('02-14-2009' AS DATETIME), 7
        UNION ALL
        SELECT 39, CAST('02-20-2009' AS DATETIME), 34
        UNION ALL
        SELECT 33, CAST('03-02-2009' AS DATETIME), 6
    ) rt

    ,SUM(t2.SomeValue) AS RunningTotal
    #tmp t1
    JOIN #tmp t2
        ON t2.OrderID <= t1.OrderID


JSON - Iterate through JSONArray


JSONObject objects = getArray.getJSONArray(i);


JSONObject objects = getArray.getJSONObject(i);

or to

JSONObject objects = getArray.optJSONObject(i);

depending on which JSON-to/from-Java library you're using. (It looks like getJSONObject will work for you.)

Then, to access the string elements in the "objects" JSONObject, get them out by element name.

String a = objects.get("A");

If you need the names of the elements in the JSONObject, you can use the static utility method JSONObject.getNames(JSONObject) to do so.

String[] elementNames = JSONObject.getNames(objects);

"Get the value for the first element and the value for the last element."

If "element" is referring to the component in the array, note that the first component is at index 0, and the last component is at index getArray.length() - 1.

I want to iterate though the objects in the array and get thier component and thier value. In my example the first object has 3 components, the scond has 5 and the third has 4 components. I want iterate though each of them and get thier component name and value.

The following code does exactly that.

import org.json.JSONArray;
import org.json.JSONObject;

public class Foo
  public static void main(String[] args) throws Exception
    String jsonInput = "{\"JObjects\":{\"JArray1\":[{\"A\":\"a\",\"B\":\"b\",\"C\":\"c\"},{\"A\":\"a1\",\"B\":\"b2\",\"C\":\"c3\",\"D\":\"d4\",\"E\":\"e5\"},{\"A\":\"aa\",\"B\":\"bb\",\"C\":\"cc\",\"D\":\"dd\"}]}}";

    // "I want to iterate though the objects in the array..."
    JSONObject outerObject = new JSONObject(jsonInput);
    JSONObject innerObject = outerObject.getJSONObject("JObjects");
    JSONArray jsonArray = innerObject.getJSONArray("JArray1");
    for (int i = 0, size = jsonArray.length(); i < size; i++)
      JSONObject objectInArray = jsonArray.getJSONObject(i);

      // "...and get thier component and thier value."
      String[] elementNames = JSONObject.getNames(objectInArray);
      System.out.printf("%d ELEMENTS IN CURRENT OBJECT:\n", elementNames.length);
      for (String elementName : elementNames)
        String value = objectInArray.getString(elementName);
        System.out.printf("name=%s, value=%s\n", elementName, value);
name=A, value=a
name=B, value=b
name=C, value=c

name=D, value=d4
name=E, value=e5
name=A, value=a1
name=B, value=b2
name=C, value=c3

name=D, value=dd
name=A, value=aa
name=B, value=bb
name=C, value=cc

Return values from the row above to the current row

This formula does not require a column letter reference ("A", "B", etc.). It returns the value of the cell one row above in the same column.


Convert a dataframe to a vector (by rows)

You can try this to get your combination:

as.numeric(rbind(test$x, test$y))

which will return:

26, 34, 21, 29, 20, 28

Get height and width of a layout programmatically

The first snippet is correct, but you need to call it after onMeasure() gets executed. Otherwise the size is not yet measured for the view.

PHP function ssh2_connect is not working

Honestly, I'd recommend using phpseclib, a pure PHP SSH2 implementation. Example:


$ssh = new Net_SSH2('www.domain.tld');
if (!$ssh->login('username', 'password')) {
    exit('Login Failed');

echo $ssh->exec('pwd');
echo $ssh->exec('ls -la');

It's a ton more portable, easier to use and more feature packed too.

How do I test for an empty JavaScript object?

Meanwhile we can have one function that checks for all 'empties' like null, undefined, '', ' ', {}, [].

var isEmpty = function(data) {
  if (typeof(data) === 'object') {
    if (JSON.stringify(data) === '{}' || JSON.stringify(data) === '[]') {
      return true;
    } else if (!data) {
      return true;
    return false;
  } else if (typeof(data) === 'string') {
    if (!data.trim()) {
      return true;
    return false;
  } else if (typeof(data) === 'undefined') {
    return true;
  } else {
    return false;

//Use cases and results.

console.log(isEmpty()); // true
console.log(isEmpty(null)); // true
console.log(isEmpty('')); // true
console.log(isEmpty('  ')); // true
console.log(isEmpty(undefined)); // true
console.log(isEmpty({})); // true
console.log(isEmpty([])); // true
console.log(isEmpty(0)); // false
console.log(isEmpty('Hey')); // false

"int cannot be dereferenced" in Java

id is of primitive type int and not an Object. You cannot call methods on a primitive as you are doing here :


Try replacing this:

        if (id.equals(list[pos].getItemNumber())){ //Getting error on "equals"


        if (id == list[pos].getItemNumber()){ //Getting error on "equals"

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

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

For instance:

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

Or if you like to be fancy,

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

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

Invoke or BeginInvoke cannot be called on a control until the window handle has been created

The method in the post you link to calls Invoke/BeginInvoke before checking if the control's handle has been created in the case where it's being called from a thread that didn't create the control.

So you'll get the exception when your method is called from a thread other than the one that created the control. This can happen from remoting events or queued work user items...


If you check InvokeRequired and HandleCreated before calling invoke you shouldn't get that exception.

Two dimensional array list

You would use

List<List<String>> listOfLists = new ArrayList<List<String>>();

And then when you needed to add a new "row", you'd add the list:

listOfLists.add(new ArrayList<String>());

I've used this mostly when I wanted to hold references to several lists of Point in a GUI so I could draw multiple curves. It works well.

For example:

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.Stroke;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;

public class DrawStuff extends JPanel {
   private static final int PREF_W = 400;
   private static final int PREF_H = PREF_W;
   private static final Color POINTS_COLOR =;
   private static final Color CURRENT_POINTS_COLOR =;
   private static final Stroke STROKE = new BasicStroke(4f);
   private List<List<Point>> pointsList = new ArrayList<List<Point>>();
   private List<Point> currentPointList = null;

   public DrawStuff() {
      MyMouseAdapter myMouseAdapter = new MyMouseAdapter();

   public Dimension getPreferredSize() {
      return new Dimension(PREF_W, PREF_H);

   protected void paintComponent(Graphics g) {
      Graphics2D g2 = (Graphics2D) g;
      for (List<Point> pointList : pointsList) {
         if (pointList.size() > 1) {
            Point p1 = pointList.get(0);
            for (int i = 1; i < pointList.size(); i++) {
               Point p2 = pointList.get(i);
               int x1 = p1.x;
               int y1 = p1.y;
               int x2 = p2.x;
               int y2 = p2.y;
               g.drawLine(x1, y1, x2, y2);
               p1 = p2;
      if (currentPointList != null && currentPointList.size() > 1) {
         Point p1 = currentPointList.get(0);
         for (int i = 1; i < currentPointList.size(); i++) {
            Point p2 = currentPointList.get(i);
            int x1 = p1.x;
            int y1 = p1.y;
            int x2 = p2.x;
            int y2 = p2.y;
            g.drawLine(x1, y1, x2, y2);
            p1 = p2;

   private class MyMouseAdapter extends MouseAdapter {
      public void mousePressed(MouseEvent mEvt) {
         currentPointList = new ArrayList<Point>();

      public void mouseDragged(MouseEvent mEvt) {

      public void mouseReleased(MouseEvent mEvt) {
         currentPointList = null;

   private static void createAndShowGui() {
      JFrame frame = new JFrame("DrawStuff");
      frame.getContentPane().add(new DrawStuff());

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {

Android Fragment handle back button press

Create interfaces:


public interface BackButtonHandlerInterface {
    void addBackClickListener (OnBackClickListener onBackClickListener);
    void removeBackClickListener (OnBackClickListener onBackClickListener);


public interface OnBackClickListener {
     boolean onBackClick();

In Activity:

public class MainActivity extends AppCompatActivity implements BackButtonHandlerInterface {

    private ArrayList<WeakReference<OnBackClickListener>> backClickListenersList = new ArrayList<>();

    public void addBackClickListener(OnBackClickListener onBackClickListener) {
        backClickListenersList.add(new WeakReference<>(onBackClickListener));

    public void removeBackClickListener(OnBackClickListener onBackClickListener) {
        for (Iterator<WeakReference<OnBackClickListener>> iterator = backClickListenersList.iterator();
            WeakReference<OnBackClickListener> weakRef =;
            if (weakRef.get() == onBackClickListener){

    public void onBackPressed() {

    private boolean fragmentsBackKeyIntercept() {
        boolean isIntercept = false;
        for (WeakReference<OnBackClickListener> weakRef : backClickListenersList) {
            OnBackClickListener onBackClickListener = weakRef.get();
            if (onBackClickListener != null) {
                boolean isFragmIntercept = onBackClickListener.onBackClick();
                if (!isIntercept) isIntercept = isFragmIntercept;
        return isIntercept;

In Fragment:

public class MyFragment extends Fragment implements OnBackClickListener{

    private BackButtonHandlerInterface backButtonHandler;

    public void onAttach(Activity activity) {
        backButtonHandler = (BackButtonHandlerInterface) activity;

    public void onDetach() {
        backButtonHandler = null;

    public boolean onBackClick() {
        //This method handle onBackPressed()! return true or false
        return false;



Provide custom back navigation

class MyFragment : Fragment() {

    override fun onCreate(savedInstanceState: Bundle?) {

        // This callback will only be called when MyFragment is at least Started.
        val callback = requireActivity().onBackPressedDispatcher.addCallback(this) {
            // Handle the back button event

        // The callback can be enabled or disabled here or in the lambda


How do I assert equality on two classes without an equals method?

Mockito offers a reflection-matcher:

For latest version of Mockito use:

Assert.assertTrue(new ReflectionEquals(expected, excludeFields).matches(actual));

For older versions use:

Assert.assertThat(actual, new ReflectionEquals(expected, excludeFields));

How can I open a .db file generated by eclipse(android) form DDMS-->File explorer-->data--->data-->packagename-->database?

Depending on your platform you can use: sqlite3 file_name.db from the terminal. .tables will list the tables, .schema is full layout. SQLite commands like: select * from table_name; and such will print out the full contents. Type: ".exit" to exit. No need to download a GUI application.Use a semi-colon if you want it to execute a single command. Decent SQLite usage tutorial

Marker in leaflet, click event

Here's a jsfiddle with a function call:

var marker = new L.Marker([46.947, 7.4448]).on('click', markerOnClick).addTo(map);

function markerOnClick(e)
  alert("hi. you clicked the marker at " + e.latlng);

How to check if array element exists or not in javascript?

you can simply use this:

var tmp = ['a', 'b'];
index = 3 ;
if( tmp[index]){
    console.log(tmp[index] + '\n');
    console.log(' does not exist');

How to send 500 Internal Server Error error from a PHP script

PHP 5.4 has a function called http_response_code, so if you're using PHP 5.4 you can just do:


I've written a polyfill for this function (Gist) if you're running a version of PHP under 5.4.

To answer your follow-up question, the HTTP 1.1 RFC says:

The reason phrases listed here are only recommendations -- they MAY be replaced by local equivalents without affecting the protocol.

That means you can use whatever text you want (excluding carriage returns or line feeds) after the code itself, and it'll work. Generally, though, there's usually a better response code to use. For example, instead of using a 500 for no record found, you could send a 404 (not found), and for something like "conditions failed" (I'm guessing a validation error), you could send something like a 422 (unprocessable entity).

Checkout Jenkins Pipeline Git SCM with credentials?

It solved for me using

checkout scm: ([
                    $class: 'GitSCM',
                    userRemoteConfigs: [[credentialsId: '******',url: ${project_url}]],
                    branches: [[name: 'refs/tags/${project_tag}']]

check if variable is dataframe

Use isinstance, nothing else:

if isinstance(x, pd.DataFrame):
    ... # do something

PEP8 says explicitly that isinstance is the preferred way to check types

No:  type(x) is pd.DataFrame
No:  type(x) == pd.DataFrame
Yes: isinstance(x, pd.DataFrame)

And don't even think about

if obj.__class__.__name__ = 'DataFrame':

isinstance handles inheritance (see What are the differences between type() and isinstance()?). For example, it will tell you if a variable is a string (either str or unicode), because they derive from basestring)

if isinstance(obj, basestring):

Specifically for pandas DataFrame objects:

import pandas as pd
isinstance(var, pd.DataFrame)

How can I show line numbers in Eclipse?

Open Eclipse

goto -> Windows -> Preferences -> Editor -> Text Editors -> Show Line No

Tick the Show Line No checkbox

Create mysql table directly from CSV file using the CSV Storage engine?

If someone is looking for a PHP solution see "PHP_MySQL_wrapper":

$db = new MySQL_wrapper(MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DB);

// this sample gets column names from first row of file
//$db->createTableFromCSV('test_files/countrylist.csv', 'csv_to_table_test');

// this sample generates column names 
$db->createTableFromCSV('test_files/countrylist1.csv', 'csv_to_table_test_no_column_names', ',', '"', '\\', 0, array(), 'generate', '\r\n');

/** Create table from CSV file and imports CSV data to Table with possibility to update rows while import.
 * @param   string      $file           - CSV File path
 * @param   string      $table          - Table name
 * @param   string      $delimiter      - COLUMNS TERMINATED BY (Default: ',')
 * @param   string      $enclosure      - OPTIONALLY ENCLOSED BY (Default: '"')
 * @param   string      $escape         - ESCAPED BY (Default: '\')
 * @param   integer     $ignore         - Number of ignored rows (Default: 1)
 * @param   array       $update         - If row fields needed to be updated eg date format or increment (SQL format only @FIELD is variable with content of that field in CSV row) $update = array('SOME_DATE' => 'STR_TO_DATE(@SOME_DATE, "%d/%m/%Y")', 'SOME_INCREMENT' => '@SOME_INCREMENT + 1')
 * @param   string      $getColumnsFrom - Get Columns Names from (file or generate) - this is important if there is update while inserting (Default: file)
 * @param   string      $newLine        - New line delimiter (Default: \n)
 * @return  number of inserted rows or false
// function createTableFromCSV($file, $table, $delimiter = ',', $enclosure = '"', $escape = '\\', $ignore = 1, $update = array(), $getColumnsFrom = 'file', $newLine = '\r\n')


What does "\r" do in the following script?

Actually, this has nothing to do with the usual Windows / Unix \r\n vs \n issue. The TELNET procotol itself defines \r\n as the end-of-line sequence, independently of the operating system. See RFC854.

How can I increase the JVM memory?

Right click on project -> Run As -> Run Configurations..-> Select Arguments tab -> In VM Arguments you can increase your JVM memory allocation. Java HotSpot document will help you to setup your VM Argument HERE

I will not prefer to make any changes into eclipse.ini as minor mistake cause lot of issues. It's easier to play with VM Args

How do you tell if a string contains another string in POSIX sh?

Here is a link to various solutions of your issue.

This is my favorite as it makes the most human readable sense:

The Star Wildcard Method

if [[ "$string" == *"$substring"* ]]; then
    return 1
return 0

Increment variable value by 1 ( shell programming)

These are the methods I know:

ichramm@NOTPARALLEL ~$ i=10; echo $i;
ichramm@NOTPARALLEL ~$ ((i+=1)); echo $i;
ichramm@NOTPARALLEL ~$ ((i=i+1)); echo $i;
ichramm@NOTPARALLEL ~$ i=`expr $i + 1`; echo $i;

Note the spaces in the last example, also note that's the only one that uses $i.

PuTTY scripting to log onto host

entering a command after you logged in can be done by going through SSH section at the bottom of putty and you should have an option Remote command (data to send to the server) separate the two commands with ;

How do I capture all of my compiler's output to a file?

Assume you want to hilight warning and error from build ouput:

make |& grep -E "warning|error"

Import pandas dataframe column as string not int

Just want to reiterate this will work in pandas >= 0.9.1:

In [2]: read_csv('sample.csv', dtype={'ID': object})
0  00013007854817840016671868
1  00013007854817840016749251
2  00013007854817840016754630
3  00013007854817840016781876
4  00013007854817840017028824
5  00013007854817840017963235
6  00013007854817840018860166

I'm creating an issue about detecting integer overflows also.

EDIT: See resolution here:

Update as it helps others:

To have all columns as str, one can do this (from the comment):

pd.read_csv('sample.csv', dtype = str)

To have most or selective columns as str, one can do this:

# lst of column names which needs to be string
lst_str_cols = ['prefix', 'serial']
# use dictionary comprehension to make dict of dtypes
dict_dtypes = {x : 'str'  for x in lst_str_cols}
# use dict on dtypes
pd.read_csv('sample.csv', dtype=dict_dtypes)

SQL Server 2008 Connection Error "No process is on the other end of the pipe"

Adding "user instance=False" to connection string solved the problem for me.

  <add name="NorthwindEntities" connectionString="metadata=res://*/Models.Northwind.csdl|res://*/Models.Northwind.ssdl|res://*/Models.Northwind.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=.\SQLEXPRESS2008R2;attachdbfilename=|DataDirectory|\Northwind.mdf;integrated security=True;user instance=False;multipleactiveresultsets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />

HTML/CSS: Making two floating divs the same height

Several years ago, the float property used to solve that problem with the table approach using display: table; and display: table-row; and display: table-cell;.

But now with the flex property, you can solve it with 3 lines of code: display: flex; and flex-wrap: wrap; and flex: 1 0 50%;

.parent {
    display: flex;
    flex-wrap: wrap;

.child {
 // flex: flex-grow flex-shrink flex-basis;
    flex: 1 0 50%;

1 0 50% are the flex values we gave to: flex-grow flex-shrink flex-basis respectively. It's a relatively new shortcut in flexbox to avoid typing them individually. I hope this helps someone out there

how to include glyphicons in bootstrap 3

I think your particular problem isn't how to use Glyphicons but understanding how Bootstrap files work together.

Bootstrap requires a specific file structure to work. I see from your code you have this:

<link href="bootstrap.css" rel="stylesheet" media="screen">

Your Bootstrap.css is being loaded from the same location as your page, this would create a problem if you didn't adjust your file structure.

But first, let me recommend you setup your folder structure like so:

/css      <-- Bootstrap.css here
/fonts    <-- Bootstrap fonts here
/js       <-- Bootstrap JavaScript here

If you notice, this is also how Bootstrap structures its files in its download ZIP.

You then include your Bootstrap file like so:

<link href="css/bootstrap.css" rel="stylesheet" media="screen">
<link href="./css/bootstrap.css" rel="stylesheet" media="screen">
<link href="/css/bootstrap.css" rel="stylesheet" media="screen">

Depending on your server structure or what you're going for.

The first and second are relative to your file's current directory. The second one is just more explicit by saying "here" (./) first then css folder (/css).

The third is good if you're running a web server, and you can just use relative to root notation as the leading "/" will be always start at the root folder.

So, why do this?

Bootstrap.css has this specific line for Glyphfonts:

@font-face {
    font-family: 'Glyphicons Halflings';
    src: url('../fonts/glyphicons-halflings-regular.eot');
    src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg');

What you can see is that that Glyphfonts are loaded by going up one directory ../ and then looking for a folder called /fonts and THEN loading the font file.

The URL address is relative to the location of the CSS file. So, if your CSS file is at the same location like this:


The CSS file is going one level deeper than looking for a /fonts folder.

So, let's say the actual location of these files are:


The CSS file would technically be looking for a folder at:


but your folder is actually in:


So see if that helps. You don't have to do anything 'special' to load Bootstrap Glyphicons, except make sure your folder structure is set up appropriately.

When you get that fixed, your HTML should simply be:

<span class="glyphicon glyphicon-comment"></span>

Note, you need both classes. The first class glyphicon sets up the basic styles while glyphicon-comment sets the specific image.

How to list AD group membership for AD users using input list?

Get-ADPrincipalGroupMembership username | select name

Got it from another answer but the script works magic. :)

'negative' pattern matching in python

You can also do it without negative look ahead. You just need to add parentheses to that part of expression which you want to extract. This construction with parentheses is named group.

Let's write python code:

string = """OK SYS 10 LEN 20 12 43
1233a.fdads.txt,23 /data/a11134/a.txt
3232b.ddsss.txt,32 /data/d13f11/b.txt
3452d.dsasa.txt,1234 /data/c13af4/f.txt

search_result ="^OK.*\n((.|\s)*).", string)

if search_result:

Output is:

1233a.fdads.txt,23 /data/a11134/a.txt
3232b.ddsss.txt,32 /data/d13f11/b.txt
3452d.dsasa.txt,1234 /data/c13af4/f.txt

^OK.*\n will find first line with OK statement, but we don't want to extract it so leave it without parentheses. Next is part which we want to capture: ((.|\s)*), so put it inside parentheses. And in the end of regexp we look for a dot ., but we also don't want to capture it.

P.S: I find this answer is super helpful to understand power of groups.

Joining three tables using MySQL

Simply use:

select "Student", "Course"
from student s, bridge b, course c
where b.sid = s.sid and b.cid = c.cid 

Is it possible to remove inline styles with jQuery?

.removeAttr("style") to just get rid of the whole style tag...

.attr("style") to test the value and see if an inline style exists...

.attr("style",newValue) to set it to something else

How to check Network port access and display useful message?

Actually Shay levy's answer is almost correct but i got an weird issue as i mentioned in his comment column. So i split the command into two lines and it works fine.

$Ipaddress= Read-Host "Enter the IP address:"
$Port= Read-host "Enter the port number to access:"

$t = New-Object Net.Sockets.TcpClient
        "Port $Port is operational"
        "Port $Port is closed, You may need to contact your IT team to open it. "

Center a column using Twitter Bootstrap 3

If you put this on your row, all of the columns inside will be centered:

.row-centered {
    display: flex;
    justify-content: space-between;

MIME types missing in IIS 7 for ASP.NET - 404.17


I chose the "ISAPI & CGI Restrictions" after clicking the server name (not the site name) in IIS Manager, and right clicked the "ASP.NET v4.0.30319" lines and chose "Allow".

After turning on ASP.NET from "Programs and Features > Turn Windows features on or off", you must install ASP.NET from the Windows command prompt. The MIME types don't ever show up, but after doing this command, I noticed these extensions showed up under the IIS web site "Handler Mappings" section of IIS Manager.

C:\>cd C:\Windows\Microsoft.NET\Framework64\v4.0.30319

C:\Windows\Microsoft.NET\Framework64\v4.0.30319>dir aspnet_reg*
 Volume in drive C is Windows
 Volume Serial Number is 8EE6-5DD0

 Directory of C:\Windows\Microsoft.NET\Framework64\v4.0.30319

03/18/2010  08:23 PM            19,296 aspnet_regbrowsers.exe
03/18/2010  08:23 PM            36,696 aspnet_regiis.exe
03/18/2010  08:23 PM           102,232 aspnet_regsql.exe
               3 File(s)        158,224 bytes
               0 Dir(s)  34,836,508,672 bytes free

C:\Windows\Microsoft.NET\Framework64\v4.0.30319>aspnet_regiis.exe -i
Start installing ASP.NET (4.0.30319).
Finished installing ASP.NET (4.0.30319).


However, I still got this error. But if you do what I mentioned for the "Fix", this will go away.

HTTP Error 404.2 - Not Found
The page you are requesting cannot be served because of the ISAPI and CGI Restriction list settings on the Web server.

Should 'using' directives be inside or outside the namespace?

According to Hanselman - Using Directive and Assembly Loading... and other such articles there is technically no difference.

My preference is to put them outside of namespaces.

Call one constructor from another

If what you want can't be achieved satisfactorily without having the initialization in its own method (e.g. because you want to do too much before the initialization code, or wrap it in a try-finally, or whatever) you can have any or all constructors pass the readonly variables by reference to an initialization routine, which will then be able to manipulate them at will.

public class Sample
    private readonly int _intField;
    public int IntProperty => _intField; 

    private void setupStuff(ref int intField, int newValue) => intField = newValue;

    public Sample(string theIntAsString)
        int i = int.Parse(theIntAsString);
        setupStuff(ref _intField,i);

    public Sample(int theInt) => setupStuff(ref _intField, theInt);

Manually raising (throwing) an exception in Python

How do I manually throw/raise an exception in Python?

Use the most specific Exception constructor that semantically fits your issue.

Be specific in your message, e.g.:

raise ValueError('A very specific bad thing happened.')

Don't raise generic exceptions

Avoid raising a generic Exception. To catch it, you'll have to catch all other more specific exceptions that subclass it.

Problem 1: Hiding bugs

raise Exception('I know Python!') # Don't! If you catch, likely to hide bugs.

For example:

def demo_bad_catch():
        raise ValueError('Represents a hidden bug, do not catch this')
        raise Exception('This is the exception you expect to handle')
    except Exception as error:
        print('Caught this error: ' + repr(error))

>>> demo_bad_catch()
Caught this error: ValueError('Represents a hidden bug, do not catch this',)

Problem 2: Won't catch

And more specific catches won't catch the general exception:

def demo_no_catch():
        raise Exception('general exceptions not caught by specific handling')
    except ValueError as e:
        print('we will not catch exception: Exception')

>>> demo_no_catch()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in demo_no_catch
Exception: general exceptions not caught by specific handling

Best Practices: raise statement

Instead, use the most specific Exception constructor that semantically fits your issue.

raise ValueError('A very specific bad thing happened')

which also handily allows an arbitrary number of arguments to be passed to the constructor:

raise ValueError('A very specific bad thing happened', 'foo', 'bar', 'baz') 

These arguments are accessed by the args attribute on the Exception object. For example:

except ValueError as err:


('message', 'foo', 'bar', 'baz')    

In Python 2.5, an actual message attribute was added to BaseException in favor of encouraging users to subclass Exceptions and stop using args, but the introduction of message and the original deprecation of args has been retracted.

Best Practices: except clause

When inside an except clause, you might want to, for example, log that a specific type of error happened, and then re-raise. The best way to do this while preserving the stack trace is to use a bare raise statement. For example:

logger = logging.getLogger(__name__)

except AppError as error:
    raise                 # just this!
    # raise AppError      # Don't do this, you'll lose the stack trace!

Don't modify your errors... but if you insist.

You can preserve the stacktrace (and error value) with sys.exc_info(), but this is way more error prone and has compatibility problems between Python 2 and 3, prefer to use a bare raise to re-raise.

To explain - the sys.exc_info() returns the type, value, and traceback.

type, value, traceback = sys.exc_info()

This is the syntax in Python 2 - note this is not compatible with Python 3:

raise AppError, error, sys.exc_info()[2] # avoid this.
# Equivalently, as error *is* the second object:
raise sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]

If you want to, you can modify what happens with your new raise - e.g. setting new args for the instance:

def error():
    raise ValueError('oops!')

def catch_error_modify_message():
    except ValueError:
        error_type, error_instance, traceback = sys.exc_info()
        error_instance.args = (error_instance.args[0] + ' <modification>',)
        raise error_type, error_instance, traceback

And we have preserved the whole traceback while modifying the args. Note that this is not a best practice and it is invalid syntax in Python 3 (making keeping compatibility much harder to work around).

>>> catch_error_modify_message()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in catch_error_modify_message
  File "<stdin>", line 2, in error
ValueError: oops! <modification>

In Python 3:

raise error.with_traceback(sys.exc_info()[2])

Again: avoid manually manipulating tracebacks. It's less efficient and more error prone. And if you're using threading and sys.exc_info you may even get the wrong traceback (especially if you're using exception handling for control flow - which I'd personally tend to avoid.)

Python 3, Exception chaining

In Python 3, you can chain Exceptions, which preserve tracebacks:

raise RuntimeError('specific message') from error

Be aware:

  • this does allow changing the error type raised, and
  • this is not compatible with Python 2.

Deprecated Methods:

These can easily hide and even get into production code. You want to raise an exception, and doing them will raise an exception, but not the one intended!

Valid in Python 2, but not in Python 3 is the following:

raise ValueError, 'message' # Don't do this, it's deprecated!

Only valid in much older versions of Python (2.4 and lower), you may still see people raising strings:

raise 'message' # really really wrong. don't do this.

In all modern versions, this will actually raise a TypeError, because you're not raising a BaseException type. If you're not checking for the right exception and don't have a reviewer that's aware of the issue, it could get into production.

Example Usage

I raise Exceptions to warn consumers of my API if they're using it incorrectly:

def api_func(foo):
    '''foo should be either 'baz' or 'bar'. returns something very useful.'''
    if foo not in _ALLOWED_ARGS:
        raise ValueError('{foo} wrong, use "baz" or "bar"'.format(foo=repr(foo)))

Create your own error types when apropos

"I want to make an error on purpose, so that it would go into the except"

You can create your own error types, if you want to indicate something specific is wrong with your application, just subclass the appropriate point in the exception hierarchy:

class MyAppLookupError(LookupError):
    '''raise this when there's a lookup error for my app'''

and usage:

if important_key not in resource_dict and not ok_to_be_missing:
    raise MyAppLookupError('resource is missing, and that is not ok.')

How to launch a Google Chrome Tab with specific URL using C#

As a simplification to chrfin's response, since Chrome should be on the run path if installed, you could just call:

Process.Start("chrome.exe", "");

This seem to work as expected for me, opening a new tab if Chrome is already open.

How do I run a PowerShell script when the computer starts?

You could set it up as a Scheduled Task, and set the Task Trigger for "At Startup"

What is "pom" packaging in maven?

The packaging type required to be pom for parent and aggregation (multi-module) projects. These types define the goals bound to a set of lifecycle stages. For example, if packaging is jar, then the package phase will execute the jar:jar goal. If the packaging is pom, the goal executed will be site:attach-descriptor

Remove spaces from std::string in C++

std::string::iterator end_pos = std::remove(str.begin(), str.end(), ' ');
str.erase(end_pos, str.end());

Using dig to search for SPF records

I believe that I found the correct answer through this dig How To. I was able to look up the SPF records on a specific DNS, by using the following query:

dig txt

Directing print output to a .txt file

Give print a file keyword argument, where the value of the argument is a file stream. We can create a file stream using the open function:

print("Hello stackoverflow!", file=open("output.txt", "a"))
print("I have a question.", file=open("output.txt", "a"))

From the Python documentation about print:

The file argument must be an object with a write(string) method; if it is not present or None, sys.stdout will be used.

And the documentation for open:

Open file and return a corresponding file object. If the file cannot be opened, an OSError is raised.

The "a" as the second argument of open means "append" - in other words, the existing contents of the file won't be overwritten. If you want the file to be overwritten instead, use "w".

Opening a file with open many times isn't ideal for performance, however. You should ideally open it once and name it, then pass that variable to print's file option. You must remember to close the file afterwards!

f = open("output.txt", "a")
print("Hello stackoverflow!", file=f)
print("I have a question.", file=f)

There's also a syntactic shortcut for this, which is the with block. This will close your file at the end of the block for you:

with open("output.txt", "a") as f:
    print("Hello stackoverflow!", file=f)
    print("I have a question.", file=f)

Unable to add window -- token null is not valid; is your activity running?

In my case, I was inflating a PopupMenu at the very beginning of the activity i.e on onCreate()... I fixed it by putting it in a Handler

  new Handler().postDelayed(new Runnable() {
            public void run() {
                PopupMenu popuMenu=new PopupMenu(SplashScreen.this,binding.progressBar);

Class is inaccessible due to its protection level

First thing, try a full rebuild. Clean and build (or just use rebuild). Every once in a long while that resolves bizarre build issues for me.

Next, comment out the rest of the code that is not in your example you have posted. Compile. Does that work?

If so, start adding segments back until one breaks it.

If not, make all the classes public and try again.

If that still fails, maybe try putting the trimmed down classes in the same file and rebuilding. At that point, there would be absolutely no reason for access issues. If that still fails, take up carpentry.

How to compare two object variables in EL expression language?

In Expression Language you can just use the == or eq operator to compare object values. Behind the scenes they will actually use the Object#equals(). This way is done so, because until with the current EL 2.1 version you cannot invoke methods with other signatures than standard getter (and setter) methods (in the upcoming EL 2.2 it would be possible).

So the particular line

<c:when test="${lang}.equals(${pageLang})">

should be written as (note that the whole expression is inside the { and })

<c:when test="${lang == pageLang}">

or, equivalently

<c:when test="${lang eq pageLang}">

Both are behind the scenes roughly interpreted as


If you want to compare constant String values, then you need to quote it

<c:when test="${lang == 'en'}">

or, equivalently

<c:when test="${lang eq 'en'}">

which is behind the scenes roughly interpreted as


Finding what methods a Python object has

There is no reliable way to list all object's methods. dir(object) is usually useful, but in some cases it may not list all methods. According to dir() documentation: "With an argument, attempt to return a list of valid attributes for that object."

Checking that method exists can be done by callable(getattr(object, method)) as already mentioned there.

Video streaming over websockets using JavaScript

Is WebSockets over TCP a fast enough protocol to stream a video of, say, 30fps?

Yes.. it is, take a look at this project. Websockets can easily handle HD videostreaming.. However, you should go for Adaptive Streaming. I explain here how you could implement it.

Currently we're working on a webbased instant messaging application with chat, filesharing and video/webcam support. With some bits and tricks we got streaming media through websockets (used HTML5 Media Capture to get the stream from our webcams).

You need to build a stream API and a Media Stream Transceiver to control the related media processing and transport.

Iterate through every file in one directory

The find library is designed for this task specifically:

require 'find'
Find.find(path) do |file|
  # process

This is a standard ruby library, so it should be available

What is the easiest way to ignore a JPA field during persistence?

Apparently, using Hibernate5Module, the @Transient will not be serialize if using ObjectMapper. Removing will make it work.

import javax.persistence.Transient;

import org.junit.Test;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

public class TransientFieldTest {

    public void Print_Json() throws JsonProcessingException {

        ObjectMapper objectEntityMapper = new ObjectMapper();
        //objectEntityMapper.registerModule(new Hibernate5Module());
        objectEntityMapper.setSerializationInclusion(Include.NON_NULL);"object: {}", objectEntityMapper.writeValueAsString( //


    private static class SampleTransient {

        private String id;

        private String transientField;

        private String nullField;


Tensorflow r1.0 : could not a find a version that satisfies the requirement tensorflow

Tensorflow on windows needs python 3.5. You can follow following steps to activate python 3.5 in anaconda:

  1. See which version of python you have: conda search python
  2. If you already have python 3.5 then go to step 3 otherwise use conda create -n py35 python=3.5 anaconda to create python 3.5
  3. Activate python 3.5 using activate py35
  4. Now install tensorflow using conda install tensorflow

If step4 is not working i.e, something like "tensorflow: no package found " then follow this tutorial to forge conda-forge channel and then try installing tensorflow using step4. It worked for me.

How do you run a SQL Server query from PowerShell?

If you want to do it on your local machine instead of in the context of SQL server then I would use the following. It is what we use at my company.

$ServerName = "_ServerName_"
$DatabaseName = "_DatabaseName_"
$Query = "SELECT * FROM Table WHERE Column = ''"

#Timeout parameters
$QueryTimeout = 120
$ConnectionTimeout = 30

#Action of connecting to the Database and executing the query and returning results if there were any.
$conn=New-Object System.Data.SqlClient.SQLConnection
$ConnectionString = "Server={0};Database={1};Integrated Security=True;Connect Timeout={2}" -f $ServerName,$DatabaseName,$ConnectionTimeout
$cmd=New-Object system.Data.SqlClient.SqlCommand($Query,$conn)
$ds=New-Object system.Data.DataSet
$da=New-Object system.Data.SqlClient.SqlDataAdapter($cmd)

Just fill in the $ServerName, $DatabaseName and the $Query variables and you should be good to go.

I am not sure how we originally found this out, but there is something very similar here.

using lodash .groupBy. how to add your own keys for grouped output?

You can do it like this in Lodash 4.x

var data = [{_x000D_
  "name": "jim",_x000D_
  "color": "blue",_x000D_
  "age": "22"_x000D_
}, {_x000D_
  "name": "Sam",_x000D_
  "color": "blue",_x000D_
  "age": "33"_x000D_
}, {_x000D_
  "name": "eddie",_x000D_
  "color": "green",_x000D_
  "age": "77"_x000D_
    // Group the elements of Array based on `color` property_x000D_
    // `key` is group's name (color), `value` is the array of objects_x000D_
    .map((value, key) => ({ color: key, users: value }))_x000D_
<script src=""></script>

Original Answer

var result = _.chain(data)
    .map(function(currentItem) {
        return _.object(["color", "users"], currentItem));

Online Demo

Note: Lodash 4.0 onwards, the .pairs function has been renamed to _.toPairs()

How to make Visual Studio copy a DLL file to the output directory?

Use a post-build action in your project, and add the commands to copy the offending DLL. The post-build action are written as a batch script.

The output directory can be referenced as $(OutDir). The project directory is available as $(ProjDir). Try to use relative pathes where applicable, so that you can copy or move your project folder without breaking the post-build action.

Unzip All Files In A Directory

The following bash script extracts all zip files in the current directory into new dirs with the filename of the zip file, i.e.:

The following files: 

Will be extracted to:


Shell script:

for zip in *.zip
  dirname=`echo $zip | sed 's/\.zip$//'`
  if mkdir "$dirname"
    if cd "$dirname"
      unzip ../"$zip"
      cd ..
      # rm -f $zip # Uncomment to delete the original zip file
      echo "Could not unpack $zip - cd failed"
    echo "Could not unpack $zip - mkdir failed"

Pycharm/Python OpenCV and CV2 install error

I had the same problem. Here are the steps for Windows 10 users.

Open CMD: win+r then type cmd. Now,

  1. Type pip install virtualenv
  2. Create a Virtual Environment, Type virtualenv testopencv
  3. Get Inside testopencv, Type cd testopencv
  4. Activate the Virtual Environment, Type .\Scripts\activate
  5. Now Install Opencv, Type pip install opencv-contrib-python --upgrade
  6. Let's test Opencv, Type Python then import cv2 hit enter then type print(cv2.__version__) to check if its installed

Now, open a new cmd, win + r then type cmd, repeat step 6. If it gives you an error.

Go inside the testopencv folder, inside lib. Copy everything, go to your python directory, inside lib folder paste it and skip that are already present.

Again open a new cmd, repeat Step 6.

Hope it helps.

How to convert IPython notebooks to PDF and HTML?

For those who can't install wkhtmltopdf in their systems, one more method other than many already mentioned in the answers to this question is to simply download the file as an html file from the jupyter notebook, upload that to HTML to PDF, and download the converted pdf files from there.

Here you have your IPython notebook(.ipynb) converted to both PDF(.pdf) & HTML(.html) formats.

How to print a percentage value in python?

There is a way more convenient 'percent'-formatting option for the .format() format method:

>>> '{:.1%}'.format(1/3.0)

Change image size with JavaScript

you can see the result here In these simple block of code you can change the size of your image ,and make it bigger when the mouse enter over the image , and it will return to its original size when mouve leave.


<img  onmouseover="fifo()" onmouseleave="fifo()" src="your_image"   
       width="10%"  id="f" >

js file:

var b=0;
function fifo() {
            document.getElementById("f").width = "300";
         document.getElementById("f").width = "100";

How to use @Nullable and @Nonnull annotations more effectively?

Short answer: I guess these annotations are only useful for your IDE to warn you of potentially null pointer errors.

As said in the "Clean Code" book, you should check your public method's parameters and also avoid checking invariants.

Another good tip is never returning null values, but using Null Object Pattern instead.

How do you enable mod_rewrite on any OS?

Nope, mod_rewrite is an Apache module and has nothing to do with PHP.

To activate the module, the following line in httpd.conf needs to be active:

LoadModule rewrite_module modules/

to see whether it is already active, try putting a .htaccess file into a web directory containing the line

RewriteEngine on

if this works without throwing a 500 internal server error, and the .htaccess file gets parsed, URL rewriting works.

Executing command line programs from within python

I am not familiar with sox, but instead of making repeated calls to the program as a command line, is it possible to set it up as a service and connect to it for requests? You can take a look at the connection interface such as sqlite for inspiration.

Using TortoiseSVN via the command line

You can have both TortoiseSVN and the Apache Subversion command line tools installed. I usually install the Apache SVN tools from the VisualSVN download site:

Once installed, place the Subversion\bin in your set PATH. Then you will be able to use TortoiseSVN when you want to use the GUI, and you have the proper SVN command line tools to use from the command line.

groovy: safely find a key in a map and return its value

Groovy maps can be used with the property property, so you can just do:

def x = mymap.likes

If the key you are looking for (for example 'likes.key') contains a dot itself, then you can use the syntax:

def x = mymap.'likes.key'

"Input string was not in a correct format."

it was my problem too .. in my case i changed the PERSIAN number to LATIN number and it worked. AND also trime your string before converting.

PersianCalendar pc = new PersianCalendar();
char[] seperator ={'/'};
string[] date = txtSaleDate.Text.Split(seperator);
int a = Convert.ToInt32(Persia.Number.ConvertToLatin(date[0]).Trim());

"An access token is required to request this resource" while accessing an album / photo with Facebook php sdk

To get the actual access_token, you can also do pro grammatically via the following PHP code:

 require 'facebook.php';

 $facebook = new Facebook(array(
   'appId'  => 'YOUR_APP_ID',
   'secret' => 'YOUR_APP_SECRET',

 // Get User ID
 $user = $facebook->getUser();

 if ($user) {
   try {
     $user_profile = $facebook->api('/me');
     $access_token = $facebook->getAccessToken();
   } catch (FacebookApiException $e) {
     $user = null;

How to get child process from parent process

#include <sys/types.h>
#include <unistd.h>

int main()
    // Create a child process     
    int pid = fork();

    if (pid > 0)

            int j=getpid();

            printf("in parent process %d\n",j);
    // Note that pid is 0 in child process
    // and negative if fork() fails
    else if (pid == 0)

            int i=getppid();
            printf("Before sleep %d\n",i);

            int k=getppid();

            printf("in child process %d\n",k);

    return 0;


Format datetime in mvc 4

Ahhhh, now it is clear. You seem to have problems binding back the value. Not with displaying it on the view. Indeed, that's the fault of the default model binder. You could write and use a custom one that will take into consideration the [DisplayFormat] attribute on your model. I have illustrated such a custom model binder here:

Apparently some problems still persist. Here's my full setup working perfectly fine on both ASP.NET MVC 3 & 4 RC.


public class MyViewModel
    [DisplayName("date of birth")]
    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
    public DateTime? Birth { get; set; }


public class HomeController : Controller
    public ActionResult Index()
        return View(new MyViewModel
            Birth = DateTime.Now

    public ActionResult Index(MyViewModel model)
        return View(model);


@model MyViewModel

@using (Html.BeginForm())
    @Html.LabelFor(x => x.Birth)
    @Html.EditorFor(x => x.Birth)
    @Html.ValidationMessageFor(x => x.Birth)
    <button type="submit">OK</button>

Registration of the custom model binder in Application_Start:

ModelBinders.Binders.Add(typeof(DateTime?), new MyDateTimeModelBinder());

And the custom model binder itself:

public class MyDateTimeModelBinder : DefaultModelBinder
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        var displayFormat = bindingContext.ModelMetadata.DisplayFormatString;
        var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

        if (!string.IsNullOrEmpty(displayFormat) && value != null)
            DateTime date;
            displayFormat = displayFormat.Replace("{0:", string.Empty).Replace("}", string.Empty);
            // use the format specified in the DisplayFormat attribute to parse the date
            if (DateTime.TryParseExact(value.AttemptedValue, displayFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
                return date;
                    string.Format("{0} is an invalid date format", value.AttemptedValue)

        return base.BindModel(controllerContext, bindingContext);

Now, no matter what culture you have setup in your web.config (<globalization> element) or the current thread culture, the custom model binder will use the DisplayFormat attribute's date format when parsing nullable dates.

What does body-parser do with express?

Let’s try to keep this least technical.

Let’s say you are sending a html form data to node-js server i.e. you made a request to the server. The server file would receive your request under a request object. Now by logic, if you console log this request object in your server file you should see your form data some where in it, which could be extracted then, but whoa ! you actually don’t !

So, where is our data ? How will we extract it if its not only present in my request.

Simple explanation to this is http sends your form data in bits and pieces which are intended to get assembled as they reach their destination. So how would you extract your data.

But, why take this pain of every-time manually parsing your data for chunks and assembling it. Use something called “body-parser” which would do this for you.

body-parser parses your request and converts it into a format from which you can easily extract relevant information that you may need.

For example, let’s say you have a sign-up form at your frontend. You are filling it, and requesting server to save the details somewhere.

Extracting username and password from your request goes as simple as below if you use body-parser.

var loginDetails = {    
    username : request.body.username,    
    password : request.body.password    

So basically, body-parser parsed your incoming request, assembled the chunks containing your form data, then created this body object for you and filled it with your form data.

Add new element to an existing object

You can use Extend to add new objects to an existing one.

syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING

Might be a pasting problem, but as far as I can see from your code, you're missing the single quotes around the HTML part you're echo-ing.

If not, could you post the code correctly and tell us what line is causing the error?

How to retrieve element value of XML using Java?

There are two general ways of doing that. You will either create a Domain Object Model of that XML file, take a look at this

and the second choice is using event driven parsing, which is an alternative to DOM xml representation. Imho you can find the best overall comparison of these two basic techniques here. Of course there are much more to know about processing xml, for instance if you are given XML schema definition (XSD), you could use JAXB.

How to check if directory exist using C++ and winAPI

Here is a simple function which does exactly this :

#include <windows.h>
#include <string>

bool dirExists(const std::string& dirName_in)
  DWORD ftyp = GetFileAttributesA(dirName_in.c_str());
    return false;  //something is wrong with your path!

    return true;   // this is a directory!

  return false;    // this is not a directory!

Text File Parsing with Python

There are a few ways to go about this. One option would be to use instead of inputfile.readlines() - you'd need to write separate code to strip the first four lines, but if you want the final output as a single string anyway, this might make the most sense.

A second, simpler option would be to rejoin the strings after striping the first four lines with my_text = ''.join(my_text). This is a little inefficient, but if speed isn't a major concern, the code will be simplest.

Finally, if you actually want the output as a list of strings instead of a single string, you can just modify your data parser to iterate over the list. That might looks something like this:

def data_parser(lines, dic):
    for i, j in dic.iteritems():
        for (k, line) in enumerate(lines):
            lines[k] = line.replace(i, j)
    return lines

socket.error: [Errno 10013] An attempt was made to access a socket in a way forbidden by its access permissions

I had to allow ..\python27\python.exe in windows firewall. I don't need to do this on WinXP or Win8.

How to update single value inside specific array item in redux

I believe when you need this kinds of operations on your Redux state the spread operator is your friend and this principal applies for all children.

Let's pretend this is your state:

const state = {
    houses: {
        gryffindor: {
          points: 15
        ravenclaw: {
          points: 18
        hufflepuff: {
          points: 7
        slytherin: {
          points: 5

And you want to add 3 points to Ravenclaw

const key = "ravenclaw";
  return {
    ...state, // copy state
    houses: {
      ...state.houses, // copy houses
      [key]: {  // update one specific house (using Computed Property syntax)
        ...state.houses[key],  // copy that specific house's properties
        points: state.houses[key].points + 3   // update its `points` property

By using the spread operator you can update only the new state leaving everything else intact.

Example taken from this amazing article, you can find almost every possible option with great examples.

Get fragment (value after hash '#') from a URL in php

You need to parse the url first, so it goes like this:

$url = "";
$fragment = parse_url($url,PHP_URL_FRAGMENT); //this variable holds the value - 'picture'

If you need to parse the actual url of the current browser, you need to request to call the server.

$fragment = parse_url($url,PHP_URL_FRAGMENT); //this variable holds the value - 'picture'

Javascript for "Add to Home Screen" on iPhone?

The only way to add any book marks in MobileSafari (including ones on the home screen) is with the builtin UI, and that Apples does not provide anyway to do this from scripts within a page. In fact, I am pretty sure there is no mechanism for doing this on the desktop version of Safari either.

How can I list all of the files in a directory with Perl?

If you want to get content of given directory, and only it (i.e. no subdirectories), the best way is to use opendir/readdir/closedir:

opendir my $dir, "/some/path" or die "Cannot open directory: $!";
my @files = readdir $dir;
closedir $dir;

You can also use:

my @files = glob( $dir . '/*' );

But in my opinion it is not as good - mostly because glob is quite complex thing (can filter results automatically) and using it to get all elements of directory seems as a too simple task.

On the other hand, if you need to get content from all of the directories and subdirectories, there is basically one standard solution:

use File::Find;

my @content;
find( \&wanted, '/some/path');
do_something_with( @content );


sub wanted {
  push @content, $File::Find::name;

CSS Printing: Avoiding cut-in-half DIVs between pages?

In my case I managed to fix the page break difficulties in webkit by setting my selected divs to page-break-inside:avoid, and also setting all elements to display:inline. So like this:

@media print{
* {
script, style { 
div {


It seems like page-break-properties can only be applied to inline elements (in webkit). I tried to only apply display:inline to the particular elements I needed, but this didn't work. The only thing that worked was applying inline to all elements. I guess it's one of the large container div' that's messing things up.

Maybe someone could expand on this.

Query an XDocument for elements by name at any depth

We know the above is true. Jon is never wrong; real life wishes can go a little further.

    xmlns:ota="" EchoToken="740" Target=" Test" TimeStamp="2012-07-19T14:42:55.198Z" Version="1.1">

For example, usually the problem is, how can we get EchoToken in the above XML document? Or how to blur the element with the name attribute.

  1. You can find them by accessing with the namespace and the name like below

     doc.Descendants().Where(p => p.Name.LocalName == "OTA_AirAvailRQ").Attributes("EchoToken").FirstOrDefault().Value
  2. You can find it by the attribute content value, like this one.

MySql export schema without data

You can do with the --no-data option with mysqldump command

mysqldump -h yourhostnameorIP -u root -p --no-data dbname > schema.sql

Adjust width and height of iframe to fit with content in it

If the content is just a very simple html, the simplest way is to remove the iframe with javascript

HTML code:

<div class="iframe">
    <iframe src="./mypage.html" frameborder="0" onload="removeIframe(this);"></iframe>

Javascript code:

function removeIframe(obj) {
    var iframeDocument = obj.contentDocument || obj.contentWindow.document;
    var mycontent = iframeDocument.getElementsByTagName("body")[0].innerHTML;
    document.getElementsByClassName("iframe")[0].innerHTML = mycontent;

How to read files and stdout from a running Docker container

A bit late but this is what I'm doing with journald. It's pretty powerful.

You need to be running your docker containers on an OS with systemd-journald.

docker run -d --log-driver=journald myapp

This pipes the whole lot into host's journald which takes care of stuff like log pruning, storage format etc and gives you some cool options for viewing them:

journalctl CONTAINER_NAME=myapp -f

which will feed it to your console as it is logged,

journalctl CONTAINER_NAME=myapp > output.log

which gives you the whole lot in a file to take away, or

journalctl CONTAINER_NAME=myapp --since=17:45

Plus you can still see the logs via docker logs .... if that's your preference.

No more > my.log or -v "/apps/myapp/logs:/logs" etc

How to do an array of hashmaps?

Java doesn't want you to make an array of HashMaps, but it will let you make an array of Objects. So, just write up a class declaration as a shell around your HashMap, and make an array of that class. This lets you store some extra data about the HashMaps if you so choose--which can be a benefit, given that you already have a somewhat complex data structure.

What this looks like:

private static someClass[] arr = new someClass[someNum];


public class someClass {

private static int dataFoo;
private static int dataBar;
private static HashMap<String, String> yourArray;



Download and install an ipa from self hosted url on iOS

Answer for Enterprise account with Xcode8

  1. Export the .ipa by checking the "with manifest plist checkbox" and provide the links requested.

  2. Upload the .ipa file and .plist file to the same location of the server (which you provided when exporting .ipa/ which mentioned in the .plist file).

  3. Create the Download Link as given below. url should link to your .plist file location.


  4. Copy this link and paste it in safari browser in your iphone. It will ask to install :D

Create a html button using this full url

Android M Permissions: onRequestPermissionsResult() not being called

Before you check everything according to above answers, make sure your request code is not 0!!!

check the code of onRequestPermissionsResult() in

public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
        @NonNull int[] grantResults) {
    int index = (requestCode>>16)&0xffff;
    if (index != 0) {

        String who = mPendingFragmentActivityResults.get(index);
        if (who == null) {
            Log.w(TAG, "Activity result delivered for unknown Fragment.");
        Fragment frag = mFragments.findFragmentByWho(who);
        if (frag == null) {
            Log.w(TAG, "Activity result no fragment exists for who: " + who);
        } else {
            frag.onRequestPermissionsResult(requestCode&0xffff, permissions, grantResults);

What is the difference between % and %% in a cmd file?

In DOS you couldn't use environment variables on the command line, only in batch files, where they used the % sign as a delimiter. If you wanted a literal % sign in a batch file, e.g. in an echo statement, you needed to double it.

This carried over to Windows NT which allowed environment variables on the command line, however for backwards compatibility you still need to double your % signs in a .cmd file.

How can I concatenate two arrays in Java?

String [] both = new ArrayList<String>(){{addAll(Arrays.asList(first)); addAll(Arrays.asList(second));}}.toArray(new String[0]);

Defining an abstract class without any abstract methods

Of course.

Declaring a class abstract only means that you don't allow it to be instantiated on its own.

Declaring a method abstract means that subclasses have to provide an implementation for that method.

The two are separate concepts, though obviously you can't have an abstract method in a non-abstract class. You can even have abstract classes with final methods but never the other way around.

What is the best/simplest way to read in an XML file in Java application?

What is the best/simplest library to use in order to read in values from this file?

As you're asking for the simplest library, I feel obliged to add an approach quite different to that in Guillaume's top-voted answer. (Of the other answers, sjbotha's JDOM mention is closest to what I suggest).

I've come to think that for XML handling in Java, using the standard JDK tools is certainly not the simplest way, and that only in some circumstances (such as not being able to use 3rd party libraries, for some reason) it is the best way.

Instead, consider using a good XML library, such as XOM. Here's how to read an XML file into a nu.xom.Document object:

import nu.xom.Builder;
import nu.xom.Document;


File file = new File("some/path");
Document document = new Builder().build(file);

So, this was just a little bit simpler, as reading the file into org.w3c.dom.Document wasn't very complicated either, in the "pure JDK" approach. But the advantages of using a good library only start here! Whatever you're doing with your XML, you'll often get away with much simpler solutions, and less of your own code to maintain, when using a library like XOM. As examples, consider this vs. this, or this vs. this, or this post containing both XOM and W3C DOM examples.

Others will provide counter-arguments (like these) for why sticking to Java's standard XML APIs may be worth it - these probably have merit, at least in some cases, although personally I don't subscribe to all of them. In any case, when choosing one way or the other, it's good to be aware of both sides of the story.

(This answer is part of my evaluation of XOM, which is a strong contender in my quest for finding the best Java XML library to replace dom4j.)

Read file from aws s3 bucket using node fs

var fileStream = fs.createWriteStream('/path/to/file.jpg');
var s3Stream = s3.getObject({Bucket: 'myBucket', Key: 'myImageFile.jpg'}).createReadStream();

// Listen for errors returned by the service
s3Stream.on('error', function(err) {
    // NoSuchKey: The specified key does not exist

s3Stream.pipe(fileStream).on('error', function(err) {
    // capture any errors that occur when writing data to the file
    console.error('File Stream:', err);
}).on('close', function() {


How to view files in binary from bash?

hexdump -C yourfile.bin

unless you want to edit it of course. Most linux distros have hexdump by default (but obviously not all).

How do I call a SQL Server stored procedure from PowerShell?

This answer was pulled from

This same example can be used for any adhoc queries. Let us execute the stored procedure “sp_helpdb” as shown below.

$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server=HOME\SQLEXPRESS;Database=master;Integrated Security=True"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = "sp_helpdb"
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet

Sql select rows containing part of string

FROM myTable


Java check to see if a variable has been initialized

Instance variables or fields, along with static variables, are assigned default values based on the variable type:

  • int: 0
  • char: \u0000 or 0
  • double: 0.0
  • boolean: false
  • reference: null

Just want to clarify that local variables (ie. declared in block, eg. method, for loop, while loop, try-catch, etc.) are not initialized to default values and must be explicitly initialized.

jQuery window scroll event does not fire up

Your CSS is actually setting the rest of the document to not show overflow therefore the document itself isn't scrolling. The easiest fix for this is bind the event to the thing that is scrolling, which in your case is div#page.

So its easy as changing:

$(document).scroll(function() {  // OR  $(window).scroll(function() {
    didScroll = true;


$('div#page').scroll(function() {
    didScroll = true;

How do I grep for all non-ASCII characters?

Here is another variant I found that produced completely different results from the grep search for [\x80-\xFF] in the accepted answer. Perhaps it will be useful to someone to find additional non-ascii characters:

grep --color='auto' -P -n "[^[:ascii:]]" myfile.txt

Note: my computer's grep (a Mac) did not have -P option, so I did brew install grep and started the call above with ggrep instead of grep.

angularjs - using {{}} binding inside ng-src but ng-src doesn't load

Changing the ng-src value is actually very simple. Like this:

<html ng-app>
<script src=""></script>
<img ng-src="{{img_url}}">
<button ng-click="img_url = ''">Click</button>

Here is a jsFiddle of a working example:

Import error No module named skimage

Hey this is pretty simple to solve this error.Just follow this steps:

First uninstall any existing installation:

pip uninstall scikit-image

or, on conda-based systems:

conda uninstall scikit-image

Now, clone scikit-image on your local computer, and install:

git clone
cd scikit-image
pip install -e .

To update the installation:

git pull  # Grab latest source
pip install -e .  # Reinstall

For other os and manual process please check this Link.

How to move from one fragment to another fragment on click of an ImageView in Android?

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_profile, container, false);
    notification = (ImageView)v.findViewById(;

    notification.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            FragmentTransaction fr = getFragmentManager().beginTransaction();
            fr.replace(,new NotificationFragment());

    return v;

Where to find the complete definition of off_t type?

If you are having trouble tracing the definitions, you can use the preprocessed output of the compiler which will tell you all you need to know. E.g.

$ cat test.c
#include <stdio.h>
$ cc -E test.c | grep off_t
typedef long int __off_t;
typedef __off64_t __loff_t;
  __off_t __pos;
  __off_t _old_offset;
typedef __off_t off_t;
extern int fseeko (FILE *__stream, __off_t __off, int __whence);
extern __off_t ftello (FILE *__stream) ;

If you look at the complete output you can even see the exact header file location and line number where it was defined:

# 132 "/usr/include/bits/types.h" 2 3 4

typedef unsigned long int __dev_t;
typedef unsigned int __uid_t;
typedef unsigned int __gid_t;
typedef unsigned long int __ino_t;
typedef unsigned long int __ino64_t;
typedef unsigned int __mode_t;
typedef unsigned long int __nlink_t;
typedef long int __off_t;
typedef long int __off64_t;


# 91 "/usr/include/stdio.h" 3 4
typedef __off_t off_t;

Java HashMap: How to get a key and value by index?

Here is the general solution if you really only want the first key's value

Object firstKey = myHashMap.keySet().toArray()[0];
Object valueForFirstKey = myHashMap.get(firstKey);

Reloading a ViewController

You really don't need to do:

[self.view setNeedsDisplay];

Honestly, I think it's "let's hope for the best" type of solution, in this case. There are several approaches to update your UIViews:

  1. KVO
  2. Notifications
  3. Delegation

Each one has is pros and cons. Depending of what you are updating and what kind of "connection" you have between your business layer (the server connectivity) and the UIViewController, I can recommend one that would suit your needs.

Groovy - Convert object to JSON string

You can use JsonBuilder for that.

Example Code:

import groovy.json.JsonBuilder

class Person {
    String name
    String address

def o = new Person( name: 'John Doe', address: 'Texas' )

println new JsonBuilder( o ).toPrettyString()

Input jQuery get old value before onchange and get value after on change

I found this question today, but I'm not sure why was this made so complicated rather than implementing it simply like:

var input = $('#target');
var inputVal = input.val();
input.on('change', function() {
  console.log('Current Value: ', $(this).val());
  console.log('Old Value: ', inputVal);
  inputVal = $(this).val();

If you want to target multiple inputs then, use each function:

$('input').each(function() {
  var inputVal = $(this).val();
  $(this).on('change', function() {
    console.log('Current Value: ',$(this).val());
    console.log('Old Value: ', inputVal);
    inputVal = $(this).val();

Ignoring SSL certificate in Apache HttpClient 4.3

If you are using HttpClient 4.5.x, your code can be similar to the following:

SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null,
SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(
        sslContext, NoopHostnameVerifier.INSTANCE);

HttpClient httpClient = HttpClients.custom()
                                   .setDefaultCookieStore(new BasicCookieStore())

ASP.NET MVC: Html.EditorFor and multi-line text boxes

in your view, instead of:

@Html.EditorFor(model => model.Comments[0].Comment)

just use:

@Html.TextAreaFor(model => model.Comments[0].Comment, 5, 1, null)

The AWS Access Key Id does not exist in our records

None of the up-voted answers work for me. Finally I pass the credentials inside the python script, using the client API.

import boto3
client = boto3.client(

Please notice that the aws_session_token argument is optional. Not recommended for public work, but make life easier for simple trial.

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

You can check detail of error by running this command

sudo service mongod status

if error is something like this

  • Failed to unlink socket file /tmp/mongodb-27017.sock Unknown error
  • Fatal Assertion 40486 at src/mongo/transport/transport_layer_asio.cpp 670

simply running this will resolve your issue

rm /tmp/mongodb-27017.sock

How to add ASP.NET 4.0 as Application Pool on IIS 7, Windows 7

Chances are you need to install .NET 4 (Which will also create a new AppPool for you)

First make sure you have IIS installed then perform the following steps:

  1. Open your command prompt (Windows + R) and type cmd and press ENTER
    You may need to start this as an administrator if you have UAC enabled.
    To do so, locate the exe (usually you can start typing with Start Menu open), right click and select "Run as Administrator"
  2. Type cd C:\Windows\Microsoft.NET\Framework\v4.0.30319\ and press ENTER.
  3. Type aspnet_regiis.exe -ir and press ENTER again.
    • If this is a fresh version of IIS (no other sites running on it) or you're not worried about the hosted sites breaking with a framework change you can use -i instead of -ir. This will change their AppPools for you and steps 5-on shouldn't be necessary.
    • at this point you will see it begin working on installing .NET's framework in to IIS for you
  4. Close the DOS prompt, re-open your start menu and right click Computer and select Manage
  5. Expand the left-hand side (Services and Applications) and select Internet Information Services
    • You'll now have a new applet within the content window exclusively for IIS.
  6. Expand out your computer and locate the Application Pools node, and select it. (You should now see ASP.NET v4.0 listed)
  7. Expand out your Sites node and locate the site you want to modify (select it)
  8. To the right you'll notice Basic Settings... just below the Edit Site text. Click this, and a new window should appear
  9. Select the .NET 4 AppPool using the Select... button and click ok.
  10. Restart the site, and you should be good-to-go.

(You can repeat steps 7-on for every site you want to apply .NET 4 on as well).

Additional References:

  1. .NET 4 Framework
    The framework for those that don't already have it.
  2. How do I run a command with elevated privileges?
    Directions on how to run the command prompt with Administrator rights.
  3. aspnet_regiis.exe options
    For those that might want to know what -ir or -i does (or the difference between them) or what other options are available. (I typically use -ir to prevent any older sites currently running from breaking on a framework change but that's up to you.)

java doesn't run if structure inside of onclick listener

both your conditions are the same:

if(s < f) {     calc = f - s;     n = s; }else if(f > s){     calc =  s - f;     n = f;  } 


if(s < f)   


}else if(f > s){ 

are the same

change to

}else if(f < s){ 

Postgresql: error "must be owner of relation" when changing a owner object

Thanks to Mike's comment, I've re-read the doc and I've realised that my current user (i.e. userA that already has the create privilege) wasn't a direct/indirect member of the new owning role...

So the solution was quite simple - I've just done this grant:

grant userB to userA;

That's all folks ;-)


Another requirement is that the object has to be owned by user userA before altering it...

How do I ZIP a file in C#, using no 3rd-party APIs?

Looks like Windows might just let you do this...

Unfortunately I don't think you're going to get around starting a separate process unless you go to a third party component.

Add item to array in VBScript

There are a few ways, not including a custom COM or ActiveX object

  1. ReDim Preserve
  2. Dictionary object, which can have string keys and search for them
  3. ArrayList .Net Framework Class, which has many methods including: sort (forward, reverse, custom), insert, remove, binarysearch, equals, toArray, and toString

With the code below, I found Redim Preserve is fastest below 54000, Dictionary is fastest from 54000 to 690000, and Array List is fastest above 690000. I tend to use ArrayList for pushing because of the sorting and array conversion.

user326639 provided FastArray, which is pretty much the fastest.

Dictionaries are useful for searching for the value and returning the index (i.e. field names), or for grouping and aggregation (histograms, group and add, group and concatenate strings, group and push sub-arrays). When grouping on keys, set CompareMode for case in/sensitivity, and check the "exists" property before "add"-ing.

Redim wouldn't save much time for one array, but it's useful for a dictionary of arrays.

imax = 10000
value = "Testvalue"
s = imax & " of """ & value & """" 

t0 = timer 'ArrayList Method
Set o = CreateObject("System.Collections.ArrayList")
For i = 0 To imax
  o.Add value
s = s & "[AList " & FormatNumber(timer - t0, 3, -1) & "]"
Set o = Nothing

t0 = timer 'ReDim Preserve Method
a = array()
For i = 0 To imax
  ReDim Preserve a(UBound(a) + 1)
  a(UBound(a)) = value
s = s & "[ReDim " & FormatNumber(timer - t0, 3, -1) & "]"
Set a = Nothing

t0 = timer 'Dictionary Method
Set o = CreateObject("Scripting.Dictionary")
For i = 0 To imax
  o.Add i, value
s = s & "[Dictionary " & FormatNumber(timer - t0, 3, -1) & "]"
Set o = Nothing

t0 = timer 'Standard array
Redim a(imax)
For i = 0 To imax
  a(i) = value
s = s & "[Array " & FormatNumber(timer - t0, 3, -1) & "]" & vbCRLF
Set a = Nothing

t0 = timer 'Fast array
a = array()
For i = 0 To imax
 ub = UBound(a)
 If i>ub Then ReDim Preserve a(Int((ub+10)*1.1))
 a(i) = value
ReDim Preserve a(i-1)
s = s & "[FastArr " & FormatNumber(timer - t0, 3, -1) & "]"
Set a = Nothing

MsgBox s

'  10000 of "Testvalue" [ArrayList 0.156][Redim 0.016][Dictionary 0.031][Array 0.016][FastArr 0.016]
'  54000 of "Testvalue" [ArrayList 0.734][Redim 0.672][Dictionary 0.203][Array 0.063][FastArr 0.109]
' 240000 of "Testvalue" [ArrayList 3.172][Redim 5.891][Dictionary 1.453][Array 0.203][FastArr 0.484]
' 690000 of "Testvalue" [ArrayList 9.078][Redim 44.785][Dictionary 8.750][Array 0.609][FastArr 1.406]
'1000000 of "Testvalue" [ArrayList 13.191][Redim 92.863][Dictionary 18.047][Array 0.859][FastArr 2.031]

Call to undefined function App\Http\Controllers\ [ function name ]

If they are in the same controller class, it would be:

foreach ( $characters as $character) {
    $num += $this->getFactorial($index) * $index;
    $index ++;

Otherwise you need to create a new instance of the class, and call the method, ie:

$controller = new MyController();
foreach ( $characters as $character) {
    $num += $controller->getFactorial($index) * $index;
    $index ++;

Find index of a value in an array

int keyIndex = words.TakeWhile(w => !w.IsKey).Count();

Where to put the file

Gradle looks for files in these places:

  • in project build dir (that is where your build script is)
  • in sub-project dir
  • in gradle user home (defined by the GRADLE_USER_HOME environment variable, which if not set defaults to USER_HOME/.gradle)

Properties from one file will override the properties from the previous ones (so file in gradle user home has precedence over the others, and file in sub-project has precedence over the one in project root).


Creating a new dictionary in Python

>>> dict.fromkeys(['a','b','c'],[1,2,3])

{'a': [1, 2, 3], 'b': [1, 2, 3], 'c': [1, 2, 3]}

How to remove gem from Ruby on Rails application?

How about something like:

gem dependency devise --pipe | cut -d \  -f 1 | xargs gem uninstall -a

(this assumes that you're not using bundler - but I guess you're not since removing from your bundle gemspec would solve the problem)

Subtract days, months, years from a date in JavaScript

I'd recommend using the MomentJS libraries. They make all interactions with Dates a lot simpler.

If you use Moment, your code would be as simple as this:

var today = moment();
var nextMonth = today.add('month', 1);
// note that both variables `today` and `nextMonth` refer to 
// the next month at this point, because `add` mutates in-place

You can find MomentJS here:


In JavaScript, the Date.getDate() function returns the current day of the month from 1-31. You are subtracting 6 from this number, and it is currently the 3rd of the month. This brings the value to -3.

How do I get a specific range of numbers from rand()?

As others have noted, simply using a modulus will skew the probabilities for individual numbers so that smaller numbers are preferred.

A very ingenious and good solution to that problem is used in Java's java.util.Random class:

public int nextInt(int n) {
    if (n <= 0)
        throw new IllegalArgumentException("n must be positive");

    if ((n & -n) == n)  // i.e., n is a power of 2
        return (int)((n * (long)next(31)) >> 31);

    int bits, val;
    do {
        bits = next(31);
        val = bits % n;
    } while (bits - val + (n-1) < 0);
    return val;

It took me a while to understand why it works and I leave that as an exercise for the reader but it's a pretty concise solution which will ensure that numbers have equal probabilities.

The important part in that piece of code is the condition for the while loop, which rejects numbers that fall in the range of numbers which otherwise would result in an uneven distribution.

Controlling a USB power supply (on/off) with Linux

The reason why folks post questions such as this is due to the dreaded- indeed "EVIL"- USB Auto-Suspend "feature".

Auto suspend winds-down the power to an "idle" USB device and unless the device's driver supports this feature correctly, the device can become uncontactable. So powering a USB port on/off is a symptom of the problem, not the problem in itself.

I'll show you how to GLOBALLY disable auto-suspend, negating the need to manually toggle the USB ports on & off:

Short Answer:

You do NOT need to edit "autosuspend_delay_ms" individually: USB autosuspend can be disabled globally and PERSISTENTLY using the following commands:

sed -i 's/GRUB_CMDLINE_LINUX_DEFAULT="/&usbcore.autosuspend=-1 /' /etc/default/grub


systemctl reboot

An Ubuntu 18.04 screen-grab follows at the end of the "Long Answer" illustrating how my results were achieved.

Long Answer:

It's true that the USB Power Management Kernel Documentation states autosuspend is to be deprecated and in in its' place "autosuspend_delay_ms" used to disable USB autosuspend:

"In 2.6.38 the "autosuspend" file will be deprecated
and replaced by the "autosuspend_delay_ms" file."

HOWEVER my testing reveals that setting usbcore.autosuspend=-1 in /etc/default/grub as below can be used as a GLOBAL toggle for USB autosuspend functionality- you do NOT need to edit individual "autosuspend_delay_ms" files.

The same document linked above states a value of "0" is ENABLED and a negative value is DISABLED:


    <snip> 0 means to autosuspend
    as soon as the device becomes idle, and negative
    values mean never to autosuspend.  You can write a
    number to the file to change the autosuspend
    idle-delay time.

In the annotated Ubuntu 18.04 screen-grab below illustrating how my results were achieved (and reproducible), please remark the default is "0" (enabled) in autosuspend_delay_ms.

Then note that after ONLY setting usbcore.autosuspend=-1 in Grub, these values are now negative (disabled) after reboot. This will save me the bother of editing individual values and can now script disabling USB autosuspend.

screengrab: autosuspend values Before and after globally editing

Hope this makes disabling USB autosuspend a little easier and more scriptable-

Fetching data from MySQL database to html dropdown list

What you are asking is pretty straight forward

  1. execute query against your db to get resultset or use API to get the resultset

  2. loop through the resultset or simply the result using php

  3. In each iteration simply format the output as an element

the following refernce should help

HTML option tag

Getting Datafrom MySQL database

hope this helps :)

Find a value anywhere in a database

Here, very sweet and small solution:

1) create a store procedure:

create procedure get_table
@find_str varchar(50)
  declare @col_name varchar(500), @tab_name varchar(500);
  declare @find_tab TABLE(table_name varchar(100), column_name varchar(100));

  DECLARE tab_col cursor for 
  select as 'col_name', as tab_name
  from sys.tables as T
  left outer join sys.columns as C on  C.object_id=T.object_id
  left outer join sys.types as TP on  C.system_type_id=TP.system_type_id
  where type='U' 
  and in('text','ntext','varchar','char','nvarchar','nchar');

  open tab_col
  fetch next from tab_col into @col_name, @tab_name

  while @@FETCH_STATUS = 0
    insert into @find_tab 
    exec('select ''' +  @tab_name + ''',''' + @col_name + ''' from ' + @tab_name + 
    ' where ' + @col_name + '=''' + @find_str + ''' group by ' + 
    @col_name + ' having count(*)>0');

    fetch next from tab_col into @col_name, @tab_name;
  CLOSE tab_col;  
  DEALLOCATE tab_col; 
  select table_name, column_name from @find_tab;



2) call procedure by calling store procedure:
exec get_table 'serach_string';

Calling stored procedure with return value

The version of EnterpriseLibrary on my machine had other parameters. This was working:

        SqlParameter retval = new SqlParameter("@ReturnValue", System.Data.SqlDbType.Int);
        retval.Direction = System.Data.ParameterDirection.ReturnValue;
        object o = cmd.Parameters["@ReturnValue"].Value;

Why is January month 0 in Java Calendar?

I'd say laziness. Arrays start at 0 (everyone knows that); the months of the year are an array, which leads me to believe that some engineer at Sun just didn't bother to put this one little nicety into the Java code.

Maven and adding JARs to system scope


Try this.

mysqldump data only

mysqldump --no-create-info ...

Also you may use:

  • --skip-triggers: if you are using triggers
  • --no-create-db: if you are using --databases ... option
  • --compact: if you want to get rid of extra comments

How to display pdf in php

  $content = $_GET['content'];
  $dir = $_GET['dir'];

$directory = (file_exists("mydir/"))?"mydir/":die("file/directory doesn't exists");// checks directory if existing.
 //the line above is just a one-line if statement (syntax: (conditon)?code here if true : code if false; )
 if($handle = opendir($directory)){ //opens directory if existing.
   while ($file = readdir($handle)) { //assign each file with link <a> tag with GET params
     echo '<a target="_blank" href="?content=application/pdf&dir='.$directory.'">'.$file.'</a>';


if you click the link a new window will appear with the pdf file

JavaScript: client-side vs. server-side validation

You can do Server side validation and send back a JSON object with the validation results for each field, keeping client Javascript to a minimum (just displaying results) and still having a user friendly experience without having to repeat yourself on both client and server.

how to set windows service username and password through commandline

This works:

sc.exe config "[servicename]" obj= "[.\username]" password= "[password]"

Where each of the [bracketed] items are replaced with the true arguments. (Keep the quotes, but don't keep the brackets.)

Just keep in mind that:

  • The spacing in the above example matters. obj= "foo" is correct; obj="foo" is not.
  • '.' is an alias to the local machine, you can specify a domain there (or your local computer name) if you wish.
  • Passwords aren't validated until the service is started
  • Quote your parameters, as above. You can sometimes get by without quotes, but good luck.

How to delete all instances of a character in a string in python?

>>> x = 'it is icy'.replace('i', '', 1)
>>> x
't is icy'

Since your code would only replace the first instance, I assumed that's what you wanted. If you want to replace them all, leave off the 1 argument.

Since you cannot replace the character in the string itself, you have to reassign it back to the variable. (Essentially, you have to update the reference instead of modifying the string.)

Angular error: "Can't bind to 'ngModel' since it isn't a known property of 'input'"

In order to use two-way data binding for form inputs you need to import the FormsModule package in your Angular module.

import { FormsModule } from '@angular/forms';

    imports: [


Since there are lot of duplicate questions with the same problem, I am enhancing this answer.

There are two possible reasons

  • Missing FormsModule, hence Add this to your Module,

    import { FormsModule } from '@angular/forms';
        imports: [
  • Check the syntax/spelling of [(ngModel)] in the input tag

Get size of an Iterable in Java

Strictly speaking, Iterable does not have size. Think data structure like a cycle.

And think about following Iterable instance, No size:

    new Iterable(){

        @Override public Iterator iterator() {
            return new Iterator(){

                public boolean hasNext() {
                    return isExternalSystemAvailble();

                public Object next() {
                    return fetchDataFromExternalSystem();

Why would a JavaScript variable start with a dollar sign?

The $ character has no special meaning to the JavaScript engine. It's just another valid character in a variable name like a-z, A-Z, _, 0-9, etc...

Is there a MySQL option/feature to track history of changes to records?

MariaDB supports System Versioning since 10.3 which is the standard SQL feature that does exactly what you want: it stores history of table records and provides access to it via SELECT queries. MariaDB is an open-development fork of MySQL. You can find more on its System Versioning via this link:

How to find index of an object by key and value in an javascript array

Not a direct answer to your question, though I thing it's worth mentioning it, because your question seems like fitting in the general case of "getting things by name in a key-value storage".

If you are not tight to the way "peoples" is implemented, a more JavaScript-ish way of getting the right guy might be :

var peoples = {
  "bob":  { "dinner": "pizza" },
  "john": { "dinner": "sushi" },
  "larry" { "dinner": "hummus" }

// If people is implemented this way, then
// you can get values from their name, like :
var theGuy = peoples["john"];

// You can event get directly to the values
var thatGuysPrefferedDinner = peoples["john"].dinner;

Hope if this is not the answer you wanted, it might help people interested in that "key/value" question.

Copy or rsync command

It's not really a question of what's more efficient.

The commands 'rsync', and 'cp' are not equivalent and achieve different goals.

1- rsync can preserve the time of creation of existing files. (using -a option)
2- rsync will run multiprocess and transfer using either local sockets or network sockets. (i.e. fork itself into multiple processes)
3- The multiprocessing, and threading will increase your throughput when copying large number of small files, and even with multiple larger files.

So bottom line is rsync is for large data, and cp is for smaller local copying. (MB to small GB range). When you start getting into multiple GB or in the TB range, go with rsync. And of course network copies, rsync all the way.

Getting HTTP headers with Node.js

Using the excellent request module:

var request = require('request');
  request("", {method: 'HEAD'}, function (err, res, body){

You can change the method to GET if you wish, but using HEAD will save you from getting the entire response body if you only wish to look at the headers.

Converting a PDF to PNG

I'll add my solution, even thought his thread is old. Maybe this will help someone anyway.

First, I need to generate the PDF. I use XeLaTeX for that:

xelatex test.tex

Now, ImageMagick and GraphicMagic both parse parameters from left to right, so the leftmost parameter, will be executed first. I ended up using this sequence for optimal processing:

gm convert -trim -transparent white -background transparent -density 1200x1200 -resize 25% test.pdf test.png

It gives nice graphics on transparent background, trimmed to what is actually on the page. The -density and -resize parameters, give a better granularity, and increase overall resolution.

I suggest checking if the density can be decreased for you. It'll cut down converting time.

SQL Server : check if variable is Empty or NULL for WHERE clause

Just use

If @searchType is null means 'return the whole table' then use

WHERE p.[Type] = @SearchType OR @SearchType is NULL

If @searchType is an empty string means 'return the whole table' then use

WHERE p.[Type] = @SearchType OR @SearchType = ''

If @searchType is null or an empty string means 'return the whole table' then use

WHERE p.[Type] = @SearchType OR Coalesce(@SearchType,'') = ''

Python, HTTPS GET with basic authentication

using only standard modules and no manual header encoding

...which seems to be the intended and most portable way

the concept of python urllib is to group the numerous attributes of the request into various managers/directors/contexts... which then process their parts:

import urllib.request, ssl

# to avoid verifying ssl certificates
httpsHa = urllib.request.HTTPSHandler(context= ssl._create_unverified_context())

# setting up realm+urls+user-password auth
# (top_level_url may be sequence, also the complete url, realm None is default)
top_level_url = 'https://ip:port_or_domain'
# of the std managers, this can send user+passwd in one go,
# not after HTTP req->401 sequence
password_mgr = urllib.request.HTTPPasswordMgrWithPriorAuth()
password_mgr.add_password(None, top_level_url, "user", "password", is_authenticated=True)

handler = urllib.request.HTTPBasicAuthHandler(password_mgr)
# create OpenerDirector
opener = urllib.request.build_opener(handler, httpsHa)

url = top_level_url + '/some_url?some_query...'
response =


Concatenating string and integer in python

Python is an interesting language in that while there is usually one (or two) "obvious" ways to accomplish any given task, flexibility still exists.

s = "string"
i = 0

print (s + repr(i))

The above code snippet is written in Python3 syntax but the parentheses after print were always allowed (optional) until version 3 made them mandatory.

Hope this helps.


how to File.listFiles in alphabetical order?

I think the previous answer is the best way to do it here is another simple way. just to print the sorted results.

 String path="/tmp";
 String[] dirListing = null;
 File dir = new File(path);
 dirListing = dir.list();

Error inflating class fragment

None of the solutions mentioned above helped me. In the log I could find the detail of the exception as mentioned below:

06-19 16:20:37.885: E/AndroidRuntime(23973): Caused by: java.lang.RuntimeException: API key not found.  Check that /meta-data/ android:name="" android:value="your API key"/ is in the application element of AndroidManifest.xml.

I did this and my code was working!

<meta-data  android:name="" android:value="AIzaSyCl1yGPZ3mpxxxxxxxAz2R-t7zcWVzrHUL9k"/>

What is the recommended project structure for spring boot rest projects?

config - class which will read from property files

cache - caching mechanism class files

constants - constant defined class

controller - controller class

exception - exception class

model - pojos classes will be present

security - security classes

service - Impl classes

util - utility classes

validation - validators classes

bootloader - main class

Python: For each list element apply a function across the list

Some readable python:

def JoeCalimar(l):
    masterList = []
    for i in l:
        for j in l:
    pos = masterList.index(min(masterList))
    a = pos/len(masterList)
    b = pos%len(masterList)
    return (l[a],l[b])

Let me know if something is not clear.

How to check if a String contains any letter from a to z?

You could use RegEx:

Regex.IsMatch(hello, @"^[a-zA-Z]+$");

If you don't like that, you can use LINQ:


Or, you can loop through the characters, and use isAlpha:


Returning a file to View/Download in ASP.NET MVC

If, like me, you've come to this topic via Razor components as you're learning Blazor, then you'll find you need to think a little more outside of the box to solve this problem. It's a bit of a minefield if (also like me) Blazor is your first forray into the MVC-type world, as the documentation isn't as helpful for such 'menial' tasks.

So, at the time of writing, you cannot achieve this using vanilla Blazor/Razor without embedding an MVC controller to handle the file download part an example of which is as below:

using Microsoft.AspNetCore.Mvc;
using Microsoft.Net.Http.Headers;

public class FileHandlingController : ControllerBase
    public FileContentResult Download(int attachmentId)
        TaskAttachment taskFile = null;

        if (attachmentId > 0)
            // taskFile = <your code to get the file>
            // which assumes it's an object with relevant properties as required below

            if (taskFile != null)
                var cd = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
                    FileNameStar = taskFile.Filename

                Response.Headers.Add(HeaderNames.ContentDisposition, cd.ToString());

        return new FileContentResult(taskFile?.FileData, taskFile?.FileContentType);

Next, make sure your application startup (Startup.cs) is configured to correctly use MVC and has the following line present (add it if not):


.. and then finally modify your component to link to the controller, for example (iterative based example using a custom class):

        @foreach (var attachment in yourAttachments)
            <td><a href="api/[email protected]" target="_blank">@attachment.Filename</a> </td>
            <td>@attachment.Created?.ToString("dd MMM yyyy")</td>
            <td><ul><li class="oi oi-circle-x delete-attachment"></li></ul></td>

Hopefully this helps anyone who struggled (like me!) to get an appropriate answer to this seemingly simple question in the realms of Blazor…!

Hide Signs that Meteor.js was Used

The amount of hacks you would need to go through to completely hide the fact your site is built by Meteor.js is absolutely ridiculous. You would have to strip essentially all core functionality and just serve straight up html, completely defeating the purpose of using the framework anyway.

That being said, I suggest looking at

You enter a url, and it reveals a ton of information about a site. If you only need to "fool" engines like this, there may be simple solutions.

How to fix height of TR?

Setting the td height to less than the natural height of its content

Since table cells want to be at least big enough to encase their content, if the content has no apparent height, the cells can be arbitrarily resized.

By resizing the cells, we can control the row height.

One way to do this, is to set the content with an absolute position within the relative cell, and set the height of the cell, and the left and top of the content.

table {_x000D_
  width: 100%;_x000D_
td {_x000D_
  border: 1px solid #999;_x000D_
.set-height td {_x000D_
  position: relative;_x000D_
  overflow: hidden;_x000D_
  height: 3em;_x000D_
.set-height p {_x000D_
  position: absolute;_x000D_
  margin: 0;_x000D_
  top: 0;_x000D_
/* table layout fixed */_x000D_
.layout-fixed {_x000D_
  table-layout: fixed;_x000D_
/* td width */_x000D_
.td-width td:first-child {_x000D_
  width: 33%;_x000D_
  <tr class="set-height">_x000D_
    <td><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p></td>_x000D_
    <td>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</td>_x000D_
<h3>With <code>table-layout: fixed</code> applied:</h3>_x000D_
<table class="layout-fixed"><tbody>_x000D_
  <tr class="set-height">_x000D_
    <td><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p></td>_x000D_
    <td>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</td>_x000D_
<h3>With <code>&lt;td&gt; width</code> applied:</h3>_x000D_
<table class="td-width"><tbody>_x000D_
  <tr class="set-height">_x000D_
    <td><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p></td>_x000D_
    <td>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</td>_x000D_

The table-layout property

The second table in the snippet above has table-layout: fixed applied, which causes cells to be given equal width, regardless of their content, within the parent.

According to, there are no significant compatibility issues regarding the use of table-layout as of Sept 12, 2019.

Or simply apply width to specific cells as in the third table.

These methods allow the cell containing the effectively sizeless content created by applying position: absolute to be given some arbitrary girth.

Much more simply...

I really should have thought of this from the start; we can manipulate block level table cell content in all the usual ways, and without completely destroying the content's natural size with position: absolute, we can leave the table to figure out what the width should be.

table {_x000D_
  width: 100%;_x000D_
td {_x000D_
  border: 1px solid #999;_x000D_
table p {_x000D_
  margin: 0;_x000D_
.cap-height p {_x000D_
  max-height: 3em;_x000D_
  overflow: hidden;_x000D_
  <tr class="cap-height">_x000D_
    <td><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p></td>_x000D_
  <tr class="cap-height">_x000D_
    <td><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p></td>_x000D_

How do I rename a repository on GitHub?

  1. open this url ( from your browser

  2. Go to repositories at the Right end of the page

  3. Open the link of repository that you want to rename

  4. click Settings (you will find in the Navigation bar)

  5. At the top you will find a box Called (Repository name) where you write the new name

  6. Press Rename

What is DOM Event delegation?

DOM event delegation is a mechanism of responding to ui-events via a single common parent rather than each child, through the magic of event "bubbling" (aka event propagation).

When an event is triggered on an element, the following occurs:

The event is dispatched to its target EventTarget and any event listeners found there are triggered. Bubbling events will then trigger any additional event listeners found by following the EventTarget's parent chain upward, checking for any event listeners registered on each successive EventTarget. This upward propagation will continue up to and including the Document.

Event bubbling provides the foundation for event delegation in browsers. Now you can bind an event handler to a single parent element, and that handler will get executed whenever the event occurs on any of its child nodes (and any of their children in turn). This is event delegation. Here's an example of it in practice:

<ul onclick="alert(event.type + '!')">

With that example if you were to click on any of the child <li> nodes, you would see an alert of "click!", even though there is no click handler bound to the <li> you clicked on. If we bound onclick="..." to each <li> you would get the same effect.

So what's the benefit?

Imagine you now have a need to dynamically add new <li> items to the above list via DOM manipulation:

var newLi = document.createElement('li');
newLi.innerHTML = 'Four';

Without using event delegation you would have to "rebind" the "onclick" event handler to the new <li> element, in order for it to act the same way as its siblings. With event delegation you don't need to do anything. Just add the new <li> to the list and you're done.

This is absolutely fantastic for web apps with event handlers bound to many elements, where new elements are dynamically created and/or removed in the DOM. With event delegation the number of event bindings can be drastically decreased by moving them to a common parent element, and code that dynamically creates new elements on the fly can be decoupled from the logic of binding their event handlers.

Another benefit to event delegation is that the total memory footprint used by event listeners goes down (since the number of event bindings go down). It may not make much of a difference to small pages that unload often (i.e. user's navigate to different pages often). But for long-lived applications it can be significant. There are some really difficult-to-track-down situations when elements removed from the DOM still claim memory (i.e. they leak), and often this leaked memory is tied to an event binding. With event delegation you're free to destroy child elements without risk of forgetting to "unbind" their event listeners (since the listener is on the ancestor). These types of memory leaks can then be contained (if not eliminated, which is freaking hard to do sometimes. IE I'm looking at you).

Here are some better concrete code examples of event delegation:

Java Serializable Object to Byte Array

I would like to transmit it as byte[] over sockets to another machine

// When you connect
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
// When you want to send it

where it is rebuilt from the bytes received.

// When you connect
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
// When you want to receive it
AppMessage appMessage = (AppMessage)ois.readObject();

How do I print colored output with Python 3?

I would like to show you about how to color code. There is also a game to it if you would like to play it down below. Copy and paste if you would like and make sure to have a good day everyone! Also, this is for Python 3, not 2. ( Game )

   # The Color Game!
# Thank you for playing this game.
# Hope you enjoy and please do not copy it. Thank you!


import colorama
from colorama import Fore
score = 0

def Check_Answer(answer):
    if (answer == "no"):
        return True

answer = input((Fore.RED + "This is green."))
if Check_Answer(answer) == True:
    score = score + 1

answer = input((Fore.BLACK + "This is red."))
if Check_Answer(answer) == True:
    score = score + 1

answer = input((Fore.BLUE + "This is black."))

if Check_Answer(answer) == True:
    score = score + 1

print('Your Score is ', score)

Now for the color coding. It also comes with a list of colors YOU can try.

# Here is how to color code in Python 3!
# Some featured color codes are : RED, BLUE, GREEN, YELLOW, OR WHITE. I don't think purple or pink are not out yet.
# Here is how to do it. (Example is down below!)

import colorama
from colorama import Fore
print(Fore.RED + "This is red..")

Python equivalent of a given wget command

There is also a nice Python module named wget that is pretty easy to use. Found here.

This demonstrates the simplicity of the design:

>>> import wget
>>> url = ''
>>> filename =
100% [................................................] 3841532 / 3841532>
>> filename


However, if wget doesn't work (I've had trouble with certain PDF files), try this solution.

Edit: You can also use the out parameter to use a custom output directory instead of current working directory.

>>> output_directory = <directory_name>
>>> filename =, out=output_directory)
>>> filename

In Firebase, is there a way to get the number of children of a node without loading all the node data?

This is a little late in the game as several others have already answered nicely, but I'll share how I might implement it.

This hinges on the fact that the Firebase REST API offers a shallow=true parameter.

Assume you have a post object and each one can have a number of comments:

 "posts": {
  "$postKey": {
   "comments": {

You obviously don't want to fetch all of the comments, just the number of comments.

Assuming you have the key for a post, you can send a GET request to[the post key]/comments?shallow=true.

This will return an object of key-value pairs, where each key is the key of a comment and its value is true:

 "comment1key": true,
 "comment2key": true,
 "comment9999key": true

The size of this response is much smaller than requesting the equivalent data, and now you can calculate the number of keys in the response to find your value (e.g. commentCount = Object.keys(result).length).

This may not completely solve your problem, as you are still calculating the number of keys returned, and you can't necessarily subscribe to the value as it changes, but it does greatly reduce the size of the returned data without requiring any changes to your schema.

Random number generator only generating one random number

There are a lot of solutions, here one: if you want only number erase the letters and the method receives a random and the result length.

public String GenerateRandom(Random oRandom, int iLongitudPin)
    String sCharacters = "123456789ABCDEFGHIJKLMNPQRSTUVWXYZ123456789";
    int iLength = sCharacters.Length;
    char cCharacter;
    int iLongitudNuevaCadena = iLongitudPin; 
    String sRandomResult = "";
    for (int i = 0; i < iLongitudNuevaCadena; i++)
        cCharacter = sCharacters[oRandom.Next(iLength)];
        sRandomResult += cCharacter.ToString();
    return (sRandomResult);

Why am I getting "Thread was being aborted" in ASP.NET?

This problem occurs in the Response.Redirect and Server.Transfer methods, because both methods call Response.End internally.

The solution for this problem is as follows.

For Server.Transfer, use the Server.Execute method instead.

Visit this link for download an example.

What is is the default namespace URI used by Microsoft development products, like Visual Studio.

Makefile If-Then Else and Loops

Here's an example if:

ifeq ($(strip $(OS)),Linux)
        PYTHON = /usr/bin/python
        FIND = /usr/bin/find

Note that this comes with a word of warning that different versions of Make have slightly different syntax, none of which seems to be documented very well.

Detect if an element is visible with jQuery

You're looking for:


Although you should probably change your selector to use jQuery considering you're using it in other places anyway:

if($('#testElement').is(':visible')) {
    // Code

It is important to note that if any one of a target element's parent elements are hidden, then .is(':visible') on the child will return false (which makes sense).

jQuery 3

:visible has had a reputation for being quite a slow selector as it has to traverse up the DOM tree inspecting a bunch of elements. There's good news for jQuery 3, however, as this post explains (Ctrl + F for :visible):

Thanks to some detective work by Paul Irish at Google, we identified some cases where we could skip a bunch of extra work when custom selectors like :visible are used many times in the same document. That particular case is up to 17 times faster now!

Keep in mind that even with this improvement, selectors like :visible and :hidden can be expensive because they depend on the browser to determine whether elements are actually displaying on the page. That may require, in the worst case, a complete recalculation of CSS styles and page layout! While we don’t discourage their use in most cases, we recommend testing your pages to determine if these selectors are causing performance issues.

Expanding even further to your specific use case, there is a built in jQuery function called $.fadeToggle():

function toggleTestElement() {

How to add data into ManyToMany field?

There's a whole page of the Django documentation devoted to this, well indexed from the contents page.

As that page states, you need to do:




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

Put this in ~/.zshrc:

autoload -U colors && colors
PS1="%{$fg[red]%}%n%{$reset_color%}@%{$fg[blue]%}%m %{$fg[yellow]%}%~ %{$reset_color%}%% "

Supported Colors:
red, blue, green, cyan, yellow, magenta, black, & white (from this answer) although different computers may have different valid options.

Surround color codes (and any other non-printable chars) with %{....%}. This is for the text wrapping to work correctly.

Additionally, here is how you can get this to work with the directory-trimming from here.

PS1="%{$fg[red]%}%n%{$reset_color%}@%{$fg[blue]%}%m %{$fg[yellow]%}%(5~|%-1~/.../%3~|%4~) %{$reset_color%}%% "

Java :Add scroll into text area

My naive assumption was that the size of scroll pane will be determined automatically...

The only solution that actually worked for me was explicitly seeting bounds of JScrollPane:

import javax.swing.*;

public class MyFrame extends JFrame {

    public MyFrame()
        setBounds(100, 100, 491, 310);

        JTextArea textField = new JTextArea();

        String str = "";
        for (int i = 0; i < 50; ++i)
            str += "Some text\n";

        JScrollPane scroll = new JScrollPane(textField);
        scroll.setBounds(10, 11, 455, 249);                     // <-- THIS

        setLocationRelativeTo ( null );

Maybe it will help some future visitors :)

OnClick vs OnClientClick for an asp:CheckBox?

You are right this is inconsistent. What is happening is that CheckBox doesn't HAVE an server-side OnClick event, so your markup gets rendered to the browser.

Whereas Button does have a OnClick - so ASP.NET expects a reference to an event in your OnClick markup.

How to Make Laravel Eloquent "IN" Query?

Here is how you do in Eloquent

$users = User::whereIn('id', array(1, 2, 3))->get();

And if you are using Query builder then :

$users = DB::table('users')->whereIn('id', array(1, 2, 3))->get();

Running PHP script from the command line


After misunderstanding, I finally got what you are trying to do. You should check your server configuration files; are you using apache2 or some other server software?

Look for lines that start with LoadModule php... There probably are configuration files/directories named mods or something like that, start from there.

You could also check output from php -r 'phpinfo();' | grep php and compare lines to phpinfo(); from web server.

To run php interactively:

(so you can paste/write code in the console)

php -a

To make it parse file and output to console:

php -f file.php

Parse file and output to another file:

php -f file.php > results.html

Do you need something else?

To run only small part, one line or like, you can use:

php -r '$x = "Hello World"; echo "$x\n";'

If you are running linux then do man php at console.

if you need/want to run php through fpm, use cli fcgi

SCRIPT_NAME="file.php" SCRIP_FILENAME="file.php" REQUEST_METHOD="GET" cgi-fcgi -bind -connect "/var/run/php-fpm/php-fpm.sock"

where /var/run/php-fpm/php-fpm.sock is your php-fpm socket file.

How can I remove the "No file chosen" tooltip from a file input in Chrome?

Very easy, forget CSS targeting the input["type"] thing, it doesn't work for me. I don't know why. I got my solution in my HTML tag

<input type="file" style="color:transparent; width:70px;"/>

End of the problem

Remove the last line from a file in Bash

OK processing a good amount of data and the output was OK, but had one junk line.

If I piped the output of the script to:

| sed -i '$ d' I would get the following error and finally no output at all sed: no input files

But | head -n -1 worked!

Make a link open a new window (not tab)

With pure HTML you can't influence this - every modern browser (= the user) has complete control over this behavior because it has been misused a lot in the past...

HTML option

You can open a new window (HTML4) or a new browsing context (HTML5). Browsing context in modern browsers is mostly "new tab" instead of "new window". You have no influence on that, and you can't "force" modern browsers to open a new window.

In order to do this, use the anchor element's attribute target[1]. The value you are looking for is _blank[2].

<a href="" target="_blank">link text</a>

JavaScript option

Forcing a new window is possible via javascript - see Ievgen's excellent answer below for a javascript solution.

(!) However, be aware, that opening windows via javascript (if not done in the onclick event from an anchor element) are subject to getting blocked by popup blockers!

[1] This attribute dates back to the times when browsers did not have tabs and using framesets was state of the art. In the meantime, the functionality of this attribute has slightly changed (see MDN Docu)

[2] There are some other values which do not make much sense anymore (because they were designed with framesets in mind) like _parent, _self or _top.

python pandas: Remove duplicates by columns A, keeping the row with the highest value in column B

this also works:

a=pd.DataFrame({'A':a.groupby('A')['B'].max().index,'B':a.groupby('A')       ['B'].max().values})

Construct pandas DataFrame from list of tuples of (row,col,values)

This is what I expected to see when I came to this question:

#!/usr/bin/env python

import pandas as pd

df = pd.DataFrame([(1, 2, 3, 4),
                   (5, 6, 7, 8),
                   (9, 0, 1, 2),
                   (3, 4, 5, 6)],
                  index=['India', 'France', 'England', 'Germany'])


         a  b  c  d
India    1  2  3  4
France   5  6  7  8
England  9  0  1  2
Germany  3  4  5  6

How to restrict SSH users to a predefined set of commands after login?

What you are looking for is called Restricted Shell. Bash provides such a mode in which users can only execute commands present in their home directories (and they cannot move to other directories), which might be good enough for you.

I've found this thread to be very illustrative, if a bit dated.

Ansible: Store command's stdout in new variable?

There's no need to set a fact.

    - shell: cat "hello"
      register: cat_contents

    - shell: echo "I cat hello"
      when: cat_contents.stdout == "hello"

How to make <input type="file"/> accept only these types?

Use accept attribute with the MIME_type as values

<input type="file" accept="image/gif, image/jpeg" />

importing a CSV into phpmyadmin

This is happen due to the id(auto increment filed missing). If you edit it in a text editor by adding a comma for the ID field this will be solved.

Python: How to check if keys exists and retrieve value from Dictionary in descending priority

One option if the number of keys is small is to use chained gets:

value = myDict.get('lastName', myDict.get('firstName', myDict.get('userName')))

But if you have keySet defined, this might be clearer:

value = None
for key in keySet:
    if key in myDict:
        value = myDict[key]

The chained gets do not short-circuit, so all keys will be checked but only one used. If you have enough possible keys that that matters, use the for loop.

Best Way to read rss feed in .net Using C#

Use this :

private string GetAlbumRSS(SyndicationItem album)

        string url = "";
        foreach (SyndicationElementExtension ext in album.ElementExtensions)
            if (ext.OuterName == "itemRSS") url = ext.GetObject<string>();
        return (url);

    protected void Page_Load(object sender, EventArgs e)
        string albumRSS;
        string url = "";
        XmlReader r = XmlReader.Create(url);
        SyndicationFeed albums = SyndicationFeed.Load(r);
        foreach (SyndicationItem album in albums.Items)

            cell.InnerHtml = cell.InnerHtml +string.Format("<br \'><a href='{0}'>{1}</a>", album.Links[0].Uri, album.Title.Text);
            albumRSS = GetAlbumRSS(album);



Getting DOM element value using pure JavaScript

The second function should have:

var value = document.getElementById(id).value;

Then they are basically the same function.