Programs & Examples On #Textnode

textNodes in DOM, HTML, XML are nodes which contain only text, rather than the other node types of element, comment, and processing instruction.

adding text to an existing text element in javascript via DOM

_x000D_
_x000D_
var t = document.getElementById("p").textContent;
var y = document.createTextNode("This just got added");

t.appendChild(y);
_x000D_
<p id="p">This is some text</p>
_x000D_
_x000D_
_x000D_

Uncaught TypeError: Cannot read property 'appendChild' of null

add your script tag on the bottom of the body tag. so that script loads after html content then you won't get such error and add=

Javascript loading CSV file into an array

This is what I used to use a csv file into an array. Couldn't get the above answers to work, but this worked for me.

$(document).ready(function() {
   "use strict";
    $.ajax({
        type: "GET",
        url: "../files/icd10List.csv",
        dataType: "text",
        success: function(data) {processData(data);}
     });
});

function processData(icd10Codes) {
    "use strict";
    var input = $.csv.toArrays(icd10Codes);
    $("#test").append(input);
}

Used the jQuery-CSV Plug-in linked above.

Javascript Uncaught Reference error Function is not defined

In JSFiddle, when you set the wrapping to "onLoad" or "onDomready", the functions you define are only defined inside that block, and cannot be accessed by outside event handlers.

Easiest fix is to change:

function something(...)

To:

window.something = function(...)

how to add new <li> to <ul> onclick with javascript

You were almost there:

You just need to append the li to ul and voila!

So just add

ul.appendChild(li);

to the end of your function so the end function will be like this:

function function1() {
  var ul = document.getElementById("list");
  var li = document.createElement("li");
  li.appendChild(document.createTextNode("Element 4"));
  ul.appendChild(li);
}

Creating SVG elements dynamically with javascript inside HTML

To facilitate svg editing you can use an intermediate function:

function getNode(n, v) {
  n = document.createElementNS("http://www.w3.org/2000/svg", n);
  for (var p in v)
    n.setAttributeNS(null, p, v[p]);
  return n
}

Now you can write:

svg.appendChild( getNode('rect', { width:200, height:20, fill:'#ff0000' }) );

Example (with an improved getNode function allowing camelcase for property with dash, eg strokeWidth > stroke-width):

_x000D_
_x000D_
function getNode(n, v) {_x000D_
  n = document.createElementNS("http://www.w3.org/2000/svg", n);_x000D_
  for (var p in v)_x000D_
    n.setAttributeNS(null, p.replace(/[A-Z]/g, function(m, p, o, s) { return "-" + m.toLowerCase(); }), v[p]);_x000D_
  return n_x000D_
}_x000D_
_x000D_
var svg = getNode("svg");_x000D_
document.body.appendChild(svg);_x000D_
_x000D_
var r = getNode('rect', { x: 10, y: 10, width: 100, height: 20, fill:'#ff00ff' });_x000D_
svg.appendChild(r);_x000D_
_x000D_
var r = getNode('rect', { x: 20, y: 40, width: 100, height: 40, rx: 8, ry: 8, fill: 'pink', stroke:'purple', strokeWidth:7 });_x000D_
svg.appendChild(r);
_x000D_
_x000D_
_x000D_

JavaScript Adding an ID attribute to another created Element

You set an element's id by setting its corresponding property:

myPara.id = ID;

jQuery append() vs appendChild()

No longer

now append is a method in JavaScript

MDN documentation on append method

Quoting MDN

The ParentNode.append method inserts a set of Node objects or DOMString objects after the last child of the ParentNode. DOMString objects are inserted as equivalent Text nodes.

This is not supported by IE and Edge but supported by Chrome(54+), Firefox(49+) and Opera(39+).

The JavaScript's append is similar to jQuery's append.

You can pass multiple arguments.

_x000D_
_x000D_
var elm = document.getElementById('div1');
elm.append(document.createElement('p'),document.createElement('span'),document.createElement('div'));
console.log(elm.innerHTML);
_x000D_
<div id="div1"></div>
_x000D_
_x000D_
_x000D_

Create table using Javascript

<!DOCTYPE html>
<html>
    <body>
        <p id="p1">
            <b>Enter the no of row and column to create table:</b>
            <br/><br/>
            <table>
                <tr>
                    <th>No. of Row(s) </th>
                    <th>No. of Column(s)</th>
                </tr>
                <tr>
                    <td><input type="text" id="row" value="4" /> X</td>
                    <td><input type="text" id="col" value="7" />Y</td>
                </tr>
            </table>
            <br/>
            <button id="create" onclick="create()">create table</button>
        </p>
        <br/><br/>
        <input type="button" value="Reload page" onclick="reloadPage()">
        <script>
            function create() {
                var row = parseInt(document.getElementById("row").value);
                var col = parseInt(document.getElementById("col").value);

                var tablestart="<table id=myTable border=1>";
                var tableend = "</table>";
                var trstart = "<tr bgcolor=#ff9966>";
                var trend = "</tr>";
                var tdstart = "<td>";
                var tdend = "</td>";
                var data="data in cell";
                var str1=tablestart + trstart + tdstart + data + tdend + trend + tableend;
                document.write(tablestart);

                for (var r=0;r<row;r++) {
                    document.write(trstart);
                    for(var c=0; c<col; c++) {
                        document.write(tdstart+"Row."+r+" Col."+c+tdend);
                    }
                }

                document.write(tableend);
                document.write("<br/>");
                var s="<button id="+"delete"+" onclick="+"deleteTable()"+">Delete top Row </button>";
                document.write(s);
                var relod="<button id="+"relod"+" onclick="+"reloadPage()"+">Reload Page </button>";
                document.write(relod);
            }
            function deleteTable() {
                var dr=0;
                if(confirm("It will be deleted..!!")) {
                    document.getElementById("myTable").deleteRow(dr);
                }
            }
            function reloadPage(){
                location.reload();
            }
        </script>
    </body>
</html>

Creating a div element inside a div element in javascript

Your code works well you just mistyped this line of code:

document.getElementbyId('lc').appendChild(element);

change it with this: (The "B" should be capitalized.)

document.getElementById('lc').appendChild(element);  

HERE IS MY EXAMPLE:

_x000D_
_x000D_
<html>_x000D_
<head>_x000D_
_x000D_
<script>_x000D_
_x000D_
function test() {_x000D_
_x000D_
    var element = document.createElement("div");_x000D_
    element.appendChild(document.createTextNode('The man who mistook his wife for a hat'));_x000D_
    document.getElementById('lc').appendChild(element);_x000D_
_x000D_
}_x000D_
_x000D_
</script>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
<input id="filter" type="text" placeholder="Enter your filter text here.." onkeyup = "test()" />_x000D_
_x000D_
<div id="lc" style="background: blue; height: 150px; width: 150px;_x000D_
}" onclick="test();">  _x000D_
</div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Best way to get child nodes

firstElementChild might not be available in IE<9 (only firstChild)

on IE<9 firstChild is the firstElementChild because MS DOM (IE<9) is not storing empty text nodes. But if you do so on other browsers they will return empty text nodes...

my solution

child=(elem.firstElementChild||elem.firstChild)

this will give the firstchild even on IE<9

PHP XML how to output nice format

This is a slight variation of the above theme but I'm putting here in case others hit this and cannot make sense of it ...as I did.

When using saveXML(), preserveWhiteSpace in the target DOMdocument does not apply to imported nodes (as at PHP 5.6).

Consider the following code:

$dom = new DOMDocument();                               //create a document
$dom->preserveWhiteSpace = false;                       //disable whitespace preservation
$dom->formatOutput = true;                              //pretty print output
$documentElement = $dom->createElement("Entry");        //create a node
$dom->appendChild ($documentElement);                   //append it 
$message = new DOMDocument();                           //create another document
$message->loadXML($messageXMLtext);                     //populate the new document from XML text
$node=$dom->importNode($message->documentElement,true); //import the new document content to a new node in the original document
$documentElement->appendChild($node);                   //append the new node to the document Element
$dom->saveXML($dom->documentElement);                   //print the original document

In this context, the $dom->saveXML(); statement will NOT pretty print the content imported from $message, but content originally in $dom will be pretty printed.

In order to achieve pretty printing for the entire $dom document, the line:

$message->preserveWhiteSpace = false; 

must be included after the $message = new DOMDocument(); line - ie. the document/s from which the nodes are imported must also have preserveWhiteSpace = false.

Dynamic creation of table with DOM

You must create td and text nodes within loop. Your code creates only 2 td, so only 2 are visible. Example:

var table = document.createElement('table');
for (var i = 1; i < 4; i++){
    var tr = document.createElement('tr');   

    var td1 = document.createElement('td');
    var td2 = document.createElement('td');

    var text1 = document.createTextNode('Text1');
    var text2 = document.createTextNode('Text2');

    td1.appendChild(text1);
    td2.appendChild(text2);
    tr.appendChild(td1);
    tr.appendChild(td2);

    table.appendChild(tr);
}
document.body.appendChild(table);

How do I append a node to an existing XML file in java

The following complete example will read an existing server.xml file from the current directory, append a new Server and re-write the file to server.xml. It does not work without an existing .xml file, so you will need to modify the code to handle that case.

import java.util.*;
import javax.xml.transform.*;
import javax.xml.transform.stream.*;
import javax.xml.transform.dom.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;

public class AddXmlNode {
    public static void main(String[] args) throws Exception {

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.parse("server.xml");
        Element root = document.getDocumentElement();

        Collection<Server> servers = new ArrayList<Server>();
        servers.add(new Server());

        for (Server server : servers) {
            // server elements
            Element newServer = document.createElement("server");

            Element name = document.createElement("name");
            name.appendChild(document.createTextNode(server.getName()));
            newServer.appendChild(name);

            Element port = document.createElement("port");
            port.appendChild(document.createTextNode(Integer.toString(server.getPort())));
            newServer.appendChild(port);

            root.appendChild(newServer);
        }

        DOMSource source = new DOMSource(document);

        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        StreamResult result = new StreamResult("server.xml");
        transformer.transform(source, result);
    }

    public static class Server {
        public String getName() { return "foo"; }
        public Integer getPort() { return 12345; }
    }
}

Example server.xml file:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Servers>
  <server>
    <name>something</name>
    <port>port</port>
  </server>
</Servers>

The main change to your code is not creating a new "root" element. The above example just uses the current root node from the existing server.xml and then just appends a new Server element and re-writes the file.

Error on line 2 at column 1: Extra content at the end of the document

I think you are creating a document that looks like this:

<mycatch>
    ....
</mycatch>
<mycatch>
    ....
</mycatch>

This is not a valid XML document as it has more than one root element. You must have a single top-level element, as in

<mydocument>      
  <mycatch>
      ....
  </mycatch>
  <mycatch>
      ....
  </mycatch>
  ....
</mydocument>

Add CSS to <head> with JavaScript?

Here's a function that will dynamically create a CSS rule in all major browsers. createCssRule takes a selector (e.g. "p.purpleText"), a rule (e.g. "color: purple;") and optionally a Document (the current document is used by default):

var addRule;

if (typeof document.styleSheets != "undefined" && document.styleSheets) {
    addRule = function(selector, rule) {
        var styleSheets = document.styleSheets, styleSheet;
        if (styleSheets && styleSheets.length) {
            styleSheet = styleSheets[styleSheets.length - 1];
            if (styleSheet.addRule) {
                styleSheet.addRule(selector, rule)
            } else if (typeof styleSheet.cssText == "string") {
                styleSheet.cssText = selector + " {" + rule + "}";
            } else if (styleSheet.insertRule && styleSheet.cssRules) {
                styleSheet.insertRule(selector + " {" + rule + "}", styleSheet.cssRules.length);
            }
        }
    }
} else {
    addRule = function(selector, rule, el, doc) {
        el.appendChild(doc.createTextNode(selector + " {" + rule + "}"));
    };
}

function createCssRule(selector, rule, doc) {
    doc = doc || document;
    var head = doc.getElementsByTagName("head")[0];
    if (head && addRule) {
        var styleEl = doc.createElement("style");
        styleEl.type = "text/css";
        styleEl.media = "screen";
        head.appendChild(styleEl);
        addRule(selector, rule, styleEl, doc);
        styleEl = null;
    }
};

createCssRule("body", "background-color: purple;");

Get the last item in an array

Normally you are not supposed to mess with the prototype of built-in types but here is a hack/shortcut:

Object.defineProperty(Array.prototype, 'last', {
  get() {
    return this[this.length - 1]; 
  }
});

This will allow all array objects to have a last property, which you can use like so:

const letters = ['a', 'b', 'c', 'd', 'e'];
console.log(letters.last); // 'e'

You are not supposed to mess with a built-in type's prototype because you never when a new ES version will be released and in the event that a new version uses the same property name as your custom property, all sorts of breaks can happen. You COULD make the property to something that you know an ES version would, like lastItem but that is at the discretion of the developer.

Executing <script> elements inserted with .innerHTML

It's easier to use jquery $(parent).html(code) instead of parent.innerHTML = code:

var oldDocumentWrite = document.write;
var oldDocumentWriteln = document.writeln;
try {
    document.write = function(code) {
        $(parent).append(code);
    }
    document.writeln = function(code) {
        document.write(code + "<br/>");
    }
    $(parent).html(html); 
} finally {
    $(window).load(function() {
        document.write = oldDocumentWrite
        document.writeln = oldDocumentWriteln
    })
}

This also works with scripts that use document.write and scripts loaded via src attribute. Unfortunately even this doesn't work with Google AdSense scripts.

Get the string representation of a DOM node

I dont think you need any complicated script for this. Just use

get_string=(el)=>el.outerHTML;

Creating the checkbox dynamically using JavaScript?

You can create a function:

function changeInputType(oldObj, oTyp, nValue) {
  var newObject = document.createElement('input');
  newObject.type = oTyp;
  if(oldObj.size) newObject.size = oldObj.size;
  if(oldObj.value) newObject.value = nValue;
  if(oldObj.name) newObject.name = oldObj.name;
  if(oldObj.id) newObject.id = oldObj.id;
  if(oldObj.className) newObject.className = oldObj.className;
  oldObj.parentNode.replaceChild(newObject,oldObj);
  return newObject;
}

And you do a call like:

changeInputType(document.getElementById('DATE_RANGE_VALUE'), 'checkbox', 7);

Sending commands and strings to Terminal.app with Applescript

As neat solution, try-

$ open -a /Applications/Utilities/Terminal.app  *.py

or

$ open -b com.apple.terminal *.py

For the shell launched, you can go to Preferences > Shell > set it to exit if no error.

That's it.

How to pass data from 2nd activity to 1st activity when pressed back? - android

TL;DR Use Activity.startActivityForResult

Long answer:

You should start by reading the Android developer documentation. Specifically the topic of your question is covered in the Starting Activities and Getting Results section of the Activity documentation.

As for example code, the Android SDK provides good examples. Also, other answers here give you short snippets of sample code to use.

However, if you are looking for alternatives, read this SO question. This is a good discussion on how to use startActivityForResults with fragments, as well as couple othe approaches for passing data between activities.

Access-control-allow-origin with multiple domains

Try this:

<add name="Access-Control-Allow-Origin" value="['URL1','URL2',...]" />

How to fully delete a git repository created with init?

Where $GIT_DIR is the path to the folder to be searched (the git repo path), execute the following in terminal.

find $GIT_DIR -name *.git* -ok rm -Rf {} \;

This will recursively search for any directories or files containing ".git" in the file/directory name within the specified Git directory. This will include .git/ and .gitignore files and any other .git-like assets. The command is interactive and will ask before removing. To proceed with the deletion, simply enter y, then Enter.

Updating .class file in jar

Do you want to do it automatically or manually? If manually, a JAR file is really just a ZIP file, so you should be able to open it with any ZIP reader. (You may need to change the extension first.) If you want to update the JAR file automatically via Eclipse, you may want to look into Ant support in Eclipse and look at the zip task.

Split string on whitespace in Python

import re
s = "many   fancy word \nhello    \thi"
re.split('\s+', s)

Changing ImageView source

You're supposed to use setImageResource instead of setBackgroundResource.

Handling the null value from a resultset in JAVA

The String being null is a very good chance, but when you see values in your table, yet a null is printed by the ResultSet, it might mean that the connection was closed before the value of ResultSet was used.

Class.forName("org.sqlite.JDBC");
con = DriverManager.getConnection("jdbc:sqlite:My_db.db");
String sql = ("select * from cust where cust_id='" + cus + "'");
pst = con.prepareStatement(sql);
rs = pst.executeQuery();
con.close();
System.out.println(rs.getString(1));

Would print null even if there are values.

Class.forName("org.sqlite.JDBC");
con = DriverManager.getConnection("jdbc:sqlite:My_db.db");
String sql = ("select * from cust where cust_id='" + cus + "'");
pst = con.prepareStatement(sql);
rs = pst.executeQuery();
System.out.println(rs.getString(1));
con.close();

Wouldn't print null if there are values in the table.

Is a URL allowed to contain a space?

Shorter answer: no, you must encode a space; it is correct to encode a space as +, but only in the query string; in the path you must use %20.

How to stop asynctask thread in android?

declare your asyncTask in your activity:

private YourAsyncTask mTask;

instantiate it like this:

mTask = new YourAsyncTask().execute();

kill/cancel it like this:

mTask.cancel(true);

Algorithm to generate all possible permutations of a list?

in PHP

$set=array('A','B','C','D');

function permutate($set) {
    $b=array();
    foreach($set as $key=>$value) {
        if(count($set)==1) {
            $b[]=$set[$key];
        }
        else {
            $subset=$set;
            unset($subset[$key]);
            $x=permutate($subset);
            foreach($x as $key1=>$value1) {
                $b[]=$value.' '.$value1;
            }
        }
    }
    return $b;
}

$x=permutate($set);
var_export($x);

Get a file name from a path

std::string getfilename(std::string path)
{
    path = path.substr(path.find_last_of("/\\") + 1);
    size_t dot_i = path.find_last_of('.');
    return path.substr(0, dot_i);
}

Make XmlHttpRequest POST using JSON

If you use JSON properly, you can have nested object without any issue :

var xmlhttp = new XMLHttpRequest();   // new HttpRequest instance 
var theUrl = "/json-handler";
xmlhttp.open("POST", theUrl);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send(JSON.stringify({ "email": "[email protected]", "response": { "name": "Tester" } }));

How do you get the length of a string?

same way you do it in javascript:

"something".length

Calling a javascript function in another js file

This is actually coming very late, but I thought I should share,

in index.html

<script type="text/javascript" src="1.js"></script>
<script type="text/javascript" src="2.js"></script>

in 1.js

fn1 = function() {
    alert("external fn clicked");
}

in 2.js

fn1()

Check/Uncheck a checkbox on datagridview

Looking at this MSDN Forum Posting it suggests comparing the Cell's value with Cell.TrueValue.

So going by its example your code should looks something like this:(this is completely untested)

Edit: it seems that the Default for Cell.TrueValue for an Unbound DataGridViewCheckBox is null you will need to set it in the Column definition.

private void chkItems_CheckedChanged(object sender, EventArgs e)
{
    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[1];
        if (chk.Value  == chk.TrueValue)
        {
            chk.Value = chk.FalseValue;
        }
        else
        {
            chk.Value = chk.TrueValue;
        }
    }
}

This code is working note setting the TrueValue and FalseValue in the Constructor plus also checking for null:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        DataGridViewCheckBoxColumn CheckboxColumn = new DataGridViewCheckBoxColumn();
        CheckboxColumn.TrueValue = true;
        CheckboxColumn.FalseValue = false;
        CheckboxColumn.Width = 100;
        dataGridView1.Columns.Add(CheckboxColumn);
        dataGridView1.Rows.Add(4);
    }

    private void chkItems_CheckedChanged(object sender, EventArgs e)
    {
        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[0];
            if (chk.Value == chk.FalseValue || chk.Value == null)
            {
                chk.Value = chk.TrueValue;
            }
            else
            {
                chk.Value = chk.FalseValue;
            }

        }
        dataGridView1.EndEdit();
    }
}

Running powershell script within python script, how to make python print the powershell output while it is running

  1. Make sure you can run powershell scripts (it is disabled by default). Likely you have already done this. http://technet.microsoft.com/en-us/library/ee176949.aspx

    Set-ExecutionPolicy RemoteSigned
    
  2. Run this python script on your powershell script helloworld.py:

    # -*- coding: iso-8859-1 -*-
    import subprocess, sys
    
    p = subprocess.Popen(["powershell.exe", 
                  "C:\\Users\\USER\\Desktop\\helloworld.ps1"], 
                  stdout=sys.stdout)
    p.communicate()
    

This code is based on python3.4 (or any 3.x series interpreter), though it should work on python2.x series as well.

C:\Users\MacEwin\Desktop>python helloworld.py
Hello World

Get names of all files from a folder with Ruby

In Ruby 2.5 you can now use Dir.children. It gets filenames as an array except for "." and ".."

Example:

Dir.children("testdir")   #=> ["config.h", "main.rb"]

http://ruby-doc.org/core-2.5.0/Dir.html#method-c-children

How to use View.OnTouchListener instead of onClick

The event when user releases his finger is MotionEvent.ACTION_UP. I'm not aware if there are any guidelines which prohibit using View.OnTouchListener instead of onClick(), most probably it depends of situation.

Here's a sample code:

imageButton.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if(event.getAction() == MotionEvent.ACTION_UP){

            // Do what you want
            return true;
        }
        return false;
    }
});

How do I escape a percentage sign in T-SQL?

WHERE column_name LIKE '%save 50[%] off!%'

Get IPv4 addresses from Dns.GetHostEntry()

IPHostEntry ipHostInfo = Dns.GetHostEntry(serverName);
IPAddress ipAddress = ipHostInfo.AddressList
    .FirstOrDefault(a => a.AddressFamily == AddressFamily.InterNetwork);

Error #2032: Stream Error

Just to clarify my comment (it's illegible in a single line)

I think the best answer is the comment by Mike Chambers in this link (http://www.judahfrangipane.com/blog/2007/02/15/error-2032-stream-error/) by Hunter McMillen.

A note from Mike Chambers:

If you run into this using URLLoader, listen for the:

flash.events.HTTPStatusEvent.HTTP_STATUS

and in AIR :

flash.events.HTTPStatusEvent.HTTP_RESPONSE_STATUS

It should give you some more information (such as the status code being returned from the server).

Bind class toggle to window scroll event

What about performance?

  1. Always debounce events to reduce calculations
  2. Use scope.applyAsync to reduce overall digest cycles count
function debounce(func, wait) {
    var timeout;
    return function () {
        var context = this, args = arguments;
        var later = function () {
            timeout = null;
            func.apply(context, args);
        };

        if (!timeout) func.apply(context, args);
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

angular.module('app.layout')
  .directive('classScroll', function ($window) {    
    return {
        restrict: 'A',
        link: function (scope, element) {    
            function toggle() {
                angular.element(element)
                  .toggleClass('class-scroll--scrolled', 
                    window.pageYOffset > 0);
                scope.$applyAsync();
            }    
            angular.element($window)
              .on('scroll', debounce(toggle, 50));

            toggle();
        }
    };
});

3. If you don't need to trigger watchers/digests at all then use compile

.directive('classScroll', function ($window, utils) {
    return {
        restrict: 'A',
        compile: function (element, attributes) {
            function toggle() {
                angular.element(element)
                  .toggleClass(attributes.classScroll,
                    window.pageYOffset > 0);
            }

            angular.element($window)
              .on('scroll', utils.debounce(toggle, 50));
            toggle();
        }
    };
  });

And you can use it like <header class-scroll="header--scrolled">

jQuery select change show/hide div event

Try the below JS

$(function() {
    $('#type').change(function(){
        $('#row_dim').hide(); 
        if ($(this).val() == 'parcel')
        {
             $('#row_dim').show();
        }
    });
});

Error:(23, 17) Failed to resolve: junit:junit:4.12

The error is caused by missing jar files. My simple solution is just by copying all the files that does not resolve to the C:\Program Files\Android\Android Studio\gradle\m2repository... (your file path may be different). I got around 6 dependencies that cannot be resolved, junit is one of them and the others are com and org and javax. Since I am behind a firewall, even if I added the code for the repository, the Android Studio doesn't seem to access it. I went to the maven repository and downloaded all the files that will not resolve. Problem solved and the Gradle sync without error. But I am a certified newbie with only 1 day experience so I do not not if this is the proper way to do it.

Example error: Cannot resolve com:squareup:javawriter:2.1.1

Step 1: I created a path C:\Program Files\Android\Android Studio\gradle\m2repository\com\squareup\javawriter\2.1.1\

Step 2: I downloaded all the jar files from the maven repository: http://repo1.maven.org/maven2/com/squareup/javawriter/2.1.1/

Step 3: I manually downloaded all the .jar files from this directory

Step 4: I copied them to C:\Program Files\Android\Android Studio\gradle\m2repository\com\squareup\javawriter\2.1.1\

I repeated this to all the files that did not resolve including the junit.

For junit, here is the directory I created: C:\Program Files\Android\Android Studio\gradle\m2repository\junit\junit\4.12 and then I copied the junit-4.12.jar inside this directory and the junit error disappeared.

Stopping a windows service when the stop option is grayed out

Use the Task manager to find the Service and kill it from there using End Task. Always does the trick for me.

If you have made the service yourself, consider removing Long running operations from the OnStart event, usually that is what causes the Service to be non responsive.

Establish a VPN connection in cmd

Is Powershell an option?

Start Powershell:

powershell

Create the VPN Connection: Add-VpnConnection

Add-VpnConnection [-Name] <string> [-ServerAddress] <string> [-TunnelType <string> {Pptp | L2tp | Sstp | Ikev2 | Automatic}] [-EncryptionLevel <string> {NoEncryption | Optional | Required | Maximum}] [-AuthenticationMethod <string[]> {Pap | Chap | MSChapv2 | Eap}] [-SplitTunneling] [-AllUserConnection] [-L2tpPsk <string>] [-RememberCredential] [-UseWinlogonCredential] [-EapConfigXmlStream <xml>] [-Force] [-PassThru] [-WhatIf] [-Confirm] 

Edit VPN connections: Set-VpnConnection

Set-VpnConnection [-Name] <string> [[-ServerAddress] <string>] [-TunnelType <string> {Pptp | L2tp | Sstp | Ikev2 | Automatic}] [-EncryptionLevel <string> {NoEncryption | Optional | Required | Maximum}] [-AuthenticationMethod <string[]> {Pap | Chap | MSChapv2 | Eap}] [-SplitTunneling <bool>] [-AllUserConnection] [-L2tpPsk <string>] [-RememberCredential <bool>] [-UseWinlogonCredential <bool>] [-EapConfigXmlStream <xml>] [-PassThru] [-Force] [-WhatIf] [-Confirm]

Lookup VPN Connections: Get-VpnConnection

Get-VpnConnection [[-Name] <string[]>] [-AllUserConnection]

Connect: rasdial [connectionName]

rasdial connectionname [username [password | \]] [/domain:domain*] [/phone:phonenumber] [/callback:callbacknumber] [/phonebook:phonebookpath] [/prefixsuffix**]

You can manage your VPN connections with the powershell commands above, and simply use the connection name to connect via rasdial.

The results of Get-VpnConnection can be a little verbose. This can be simplified with a simple Select-Object filter:

Get-VpnConnection | Select-Object -Property Name

More information can be found here:

ESLint - "window" is not defined. How to allow global variables in package.json

I'm aware he's not asking for the inline version. But since this question has almost 100k visits and I fell here looking for that, I'll leave it here for the next fellow coder:

Make sure ESLint is not run with the --no-inline-config flag (if this doesn't sound familiar, you're likely good to go). Then, write this in your code file (for clarity and convention, it's written on top of the file but it'll work anywhere):

/* eslint-env browser */

This tells ESLint that your working environment is a browser, so now it knows what things are available in a browser and adapts accordingly.

There are plenty of environments, and you can declare more than one at the same time, for example, in-line:

/* eslint-env browser, node */

If you are almost always using particular environments, it's best to set it in your ESLint's config file and forget about it.

From their docs:

An environment defines global variables that are predefined. The available environments are:

  • browser - browser global variables.
  • node - Node.js global variables and Node.js scoping.
  • commonjs - CommonJS global variables and CommonJS scoping (use this for browser-only code that uses Browserify/WebPack).
  • shared-node-browser - Globals common to both Node and Browser.

[...]

Besides environments, you can make it ignore anything you want. If it warns you about using console.log() but you don't want to be warned about it, just inline:

/* eslint-disable no-console */

You can see the list of all rules, including recommended rules to have for best coding practices.

Uint8Array to string in Javascript

The solution given by Albert works well as long as the provided function is invoked infrequently and is only used for arrays of modest size, otherwise it is egregiously inefficient. Here is an enhanced vanilla JavaScript solution that works for both Node and browsers and has the following advantages:

• Works efficiently for all octet array sizes

• Generates no intermediate throw-away strings

• Supports 4-byte characters on modern JS engines (otherwise "?" is substituted)

var utf8ArrayToStr = (function () {
    var charCache = new Array(128);  // Preallocate the cache for the common single byte chars
    var charFromCodePt = String.fromCodePoint || String.fromCharCode;
    var result = [];

    return function (array) {
        var codePt, byte1;
        var buffLen = array.length;

        result.length = 0;

        for (var i = 0; i < buffLen;) {
            byte1 = array[i++];

            if (byte1 <= 0x7F) {
                codePt = byte1;
            } else if (byte1 <= 0xDF) {
                codePt = ((byte1 & 0x1F) << 6) | (array[i++] & 0x3F);
            } else if (byte1 <= 0xEF) {
                codePt = ((byte1 & 0x0F) << 12) | ((array[i++] & 0x3F) << 6) | (array[i++] & 0x3F);
            } else if (String.fromCodePoint) {
                codePt = ((byte1 & 0x07) << 18) | ((array[i++] & 0x3F) << 12) | ((array[i++] & 0x3F) << 6) | (array[i++] & 0x3F);
            } else {
                codePt = 63;    // Cannot convert four byte code points, so use "?" instead
                i += 3;
            }

            result.push(charCache[codePt] || (charCache[codePt] = charFromCodePt(codePt)));
        }

        return result.join('');
    };
})();

how to generate a unique token which expires after 24 hours?

Use Dictionary<string, DateTime> to store token with timestamp:

static Dictionary<string, DateTime> dic = new Dictionary<string, DateTime>();

Add token with timestamp whenever you create new token:

dic.Add("yourToken", DateTime.Now);

There is a timer running to remove any expired tokens out of dic:

 timer = new Timer(1000*60); //assume run in 1 minute
 timer.Elapsed += timer_Elapsed;

 static void timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        var expiredTokens = dic.Where(p => p.Value.AddDays(1) <= DateTime.Now)
                              .Select(p => p.Key);

        foreach (var key in expiredTokens)
            dic.Remove(key);
    }

So, when you authenticate token, just check whether token exists in dic or not.

Android dependency has different version for the compile and runtime

The answer for me was to also add this to my build.gradle file:

configurations.all {
  resolutionStrategy.eachDependency { details ->
      if (details.requested.group == 'com.android.support'
              && !details.requested.name.contains('multidex') ) {
          details.useVersion "26.1.0"
      }
  }
}

In my case, it was nessisary to enclose the resolution strategy in a configurations.all { .. } block. I placed the configurations.all block directly into my app/build.gradle file (ie configurations.all was not nested in anything else)

How do I find which application is using up my port?

It may be possible that there is no other application running. It is possible that the socket wasn't cleanly shutdown from a previous session in which case you may have to wait for a while before the TIME_WAIT expires on that socket. Unfortunately, you won't be able to use the port till that socket expires. If you can start your server after waiting for a while (a few minutes) then the problem is not due to some other application running on port 8080.

What tools do you use to test your public REST API?

http://www.quadrillian.com/ this enables you to create an entire test suite for your API and run it from your browser and share it with others.

How can I output the value of an enum class in C++11

(I'm not allowed to comment yet.) I would suggest the following improvements to the already great answer of James McNellis:

template <typename Enumeration>
constexpr auto as_integer(Enumeration const value)
    -> typename std::underlying_type<Enumeration>::type
{
    static_assert(std::is_enum<Enumeration>::value, "parameter is not of type enum or enum class");
    return static_cast<typename std::underlying_type<Enumeration>::type>(value);
}

with

  • constexpr: allowing me to use an enum member value as compile-time array size
  • static_assert+is_enum: to 'ensure' compile-time that the function does sth. with enumerations only, as suggested

By the way I'm asking myself: Why should I ever use enum class when I would like to assign number values to my enum members?! Considering the conversion effort.

Perhaps I would then go back to ordinary enum as I suggested here: How to use enums as flags in C++?


Yet another (better) flavor of it without static_assert, based on a suggestion of @TobySpeight:

template <typename Enumeration>
constexpr std::enable_if_t<std::is_enum<Enumeration>::value,
std::underlying_type_t<Enumeration>> as_number(const Enumeration value)
{
    return static_cast<std::underlying_type_t<Enumeration>>(value);
}

What is the best way to tell if a character is a letter or number in Java without using regexes?

Character.isDigit(string.charAt(index)) (JavaDoc) will return true if it's a digit
Character.isLetter(string.charAt(index)) (JavaDoc) will return true if it's a letter

What is the difference between WCF and WPF?

  • WPF is your FrontEnd (presentation: .htm, .xaml & .css, ..)
  • WCF is your BackEnd app (services that involve server connections to acquire data for you to deliver to the FrontEnd to present). You can write WCF for RESTful model.
  • WebAPI is for building services of RESTful model for 4.+ frameworks.

How can I get a process handle by its name in C++?

#include <cstdio>
#include <windows.h>
#include <tlhelp32.h>

int main( int, char *[] )
{
    PROCESSENTRY32 entry;
    entry.dwSize = sizeof(PROCESSENTRY32);

    HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);

    if (Process32First(snapshot, &entry) == TRUE)
    {
        while (Process32Next(snapshot, &entry) == TRUE)
        {
            if (stricmp(entry.szExeFile, "target.exe") == 0)
            {  
                HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, entry.th32ProcessID);

                // Do stuff..

                CloseHandle(hProcess);
            }
        }
    }

    CloseHandle(snapshot);

    return 0;
}

Also, if you'd like to use PROCESS_ALL_ACCESS in OpenProcess, you could try this:

#include <cstdio>
#include <windows.h>
#include <tlhelp32.h>

void EnableDebugPriv()
{
    HANDLE hToken;
    LUID luid;
    TOKEN_PRIVILEGES tkp;

    OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken);

    LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &luid);

    tkp.PrivilegeCount = 1;
    tkp.Privileges[0].Luid = luid;
    tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;

    AdjustTokenPrivileges(hToken, false, &tkp, sizeof(tkp), NULL, NULL);

    CloseHandle(hToken); 
}

int main( int, char *[] )
{
    EnableDebugPriv();

    PROCESSENTRY32 entry;
    entry.dwSize = sizeof(PROCESSENTRY32);

    HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);

    if (Process32First(snapshot, &entry) == TRUE)
    {
        while (Process32Next(snapshot, &entry) == TRUE)
        {
            if (stricmp(entry.szExeFile, "target.exe") == 0)
            {  
                HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, entry.th32ProcessID);

                // Do stuff..

                CloseHandle(hProcess);
            }
        }
    }

    CloseHandle(snapshot);

    return 0;
}

Getting all types in a namespace via reflection

You won't be able to get all types in a namespace, because a namespace can bridge multiple assemblies, but you can get all classes in an assembly and check to see if they belong to that namespace.

Assembly.GetTypes() works on the local assembly, or you can load an assembly first then call GetTypes() on it.

What is the difference between varchar and nvarchar?

varchar: Variable-length, non-Unicode character data. The database collation determines which code page the data is stored using.

nvarchar: Variable-length Unicode character data. Dependent on the database collation for comparisons.

Armed with this knowledge, use whichever one matches your input data (ASCII v. Unicode).

How to resolve Nodejs: Error: ENOENT: no such file or directory

Guys i have was facing this issue for an entire day at my work, just now solved by just copy pasting the MSBuild.exe file in C:\Program Files (x86)\Microsoft Visual Studio\2019\Preview\MSBuild\Current\Bin to C:\Program Files (x86)\Microsoft Visual Studio\2019\Preview\MSBuild\15.0\Bin.

I tried all the suggested methods in this thread none worked. If anyone happened to face this issue straight away use npm install --global --production windows-build-tools --vs2019 or --vs2017 . and copy paste the exe file.

How to convert map to url query string?

I think this is better for memory usage and performance, and I want to send just the property name when the value is null.

public static String toUrlEncode(Map<String, Object> map) {
    StringBuilder sb = new StringBuilder();
    map.entrySet().stream()
            .forEach(entry
                    -> (entry.getValue() == null
                    ? sb.append(entry.getKey())
                    : sb.append(entry.getKey())
                            .append('=')
                            .append(URLEncoder.encode(entry.getValue().toString(), StandardCharsets.UTF_8)))
                    .append('&')
            );
    sb.delete(sb.length() - 1, sb.length());
    return sb.toString();
}

How can I suppress all output from a command using Bash?

Try

: $(yourcommand)

: is short for "do nothing".

$() is just your command.

Rename a column in MySQL

https://dev.mysql.com/doc/refman/8.0/en/alter-table.html

For MySQL 8

alter table creditReportXml_temp change column applicationID applicantID int(11);

Find out time it took for a python script to complete execution

import time
start = time.time()

fun()

# python 2
print 'It took', time.time()-start, 'seconds.'

# python 3
print('It took', time.time()-start, 'seconds.')

What is the difference between match_parent and fill_parent?

Both, FILL_PARENT and MATCH_PARENT are the same properties. FILL_PARENT was deprecated in API level 8.

What methods of ‘clearfix’ can I use?

I recommend using the following, which is taken from http://html5boilerplate.com/

/* >> The Magnificent CLEARFIX << */
.clearfix:after { 
  content: "."; 
  display: block; 
  height: 0; 
  clear: both; 
  visibility: hidden; 
}
.clearfix { 
  display: inline-block;  
}
* html .clearfix {  
  height: 1%;  
} /* Hides from IE-mac \*/
.clearfix {  
  display: block;  
}

How does one set up the Visual Studio Code compiler/debugger to GCC?

EDIT: As of ~March 2016, Microsoft offers a C/C++ extension for Visual Studio Code and therefor the answer I originally gave is no longer valid.

Visual Studio Code doesn't support C/C++ very well. As such it doesn't >naturally support gcc or gdb within the Visual Studio Code application. The most it will do is syntax highlighting, the advanced features like >intellisense aren't supported with C. You can still compile and debug code >that you wrote in VSC, but you'll need to do that outside the program itself.

What is a Windows Handle?

A handle is a unique identifier for an object managed by Windows. It's like a pointer, but not a pointer in the sence that it's not an address that could be dereferenced by user code to gain access to some data. Instead a handle is to be passed to a set of functions that can perform actions on the object the handle identifies.

docker error - 'name is already in use by container'

I was running into this issue that when I run docker rm (which usually works) I would get:

Error: No such image

The easiest solution to this is removing all stopped containers by running:

docker container prune

Could not resolve all dependencies for configuration ':classpath'

I had a same problem and I fix it with the following steps:

  1. check the event log and if you see the errors like "cash version is not available for the offline mode" follow the steps.
  2. click on View => Gradle then new window will open.
  3. click on the WIFI icon and then sync the Gradle.enter image description here "if you see different errors from what I mentioned in number one, please go to the file -> project structure -> and there is suggestion"

JDBC connection failed, error: TCP/IP connection to host failed

important:
after any changes or new settings you must restart SQLSERVER service. run services.msc on Windows

Failed to resolve: com.android.support:appcompat-v7:27.+ (Dependency Error)

If you are using Android Studio 3.0 or above make sure your project build.gradle should have content similar to-

buildscript {                 
    repositories {
        google()
        jcenter()
    }
    dependencies {            
        classpath 'com.android.tools.build:gradle:3.0.1'

    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

Note- position really matters add google() before jcenter()

And for below Android Studio 3.0 and starting from support libraries 26.+ your project build.gradle must look like this-

allprojects {
    repositories {
        jcenter()
        maven {
            url "https://maven.google.com"
        }
    }
}

check these links below for more details-

1- Building Android Apps

2- Add Build Dependencies

3- Configure Your Build

Cross-Origin Request Blocked

You need other headers, not only access-control-allow-origin. If your request have the "Access-Control-Allow-Origin" header, you must copy it into the response headers, If doesn't, you must check the "Origin" header and copy it into the response. If your request doesn't have Access-Control-Allow-Origin not Origin headers, you must return "*".

You can read the complete explanation here: http://www.html5rocks.com/en/tutorials/cors/#toc-adding-cors-support-to-the-server

and this is the function I'm using to write cross domain headers:

func writeCrossDomainHeaders(w http.ResponseWriter, req *http.Request) {
    // Cross domain headers
    if acrh, ok := req.Header["Access-Control-Request-Headers"]; ok {
        w.Header().Set("Access-Control-Allow-Headers", acrh[0])
    }
    w.Header().Set("Access-Control-Allow-Credentials", "True")
    if acao, ok := req.Header["Access-Control-Allow-Origin"]; ok {
        w.Header().Set("Access-Control-Allow-Origin", acao[0])
    } else {
        if _, oko := req.Header["Origin"]; oko {
            w.Header().Set("Access-Control-Allow-Origin", req.Header["Origin"][0])
        } else {
            w.Header().Set("Access-Control-Allow-Origin", "*")
        }
    }
    w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE")
    w.Header().Set("Connection", "Close")

}

Python Iterate Dictionary by Index

There are some very good answers here. I'd like to add the following here as well:

some_dict = {
    "foo": "bar",
    "lorem": "ipsum"
}

for index, (key, value) in enumerate(some_dict.items()):
    print(index, key, value)

results in

0 foo bar
1 lorem ipsum

Appears to work with Python 2.7 and 3.5

Sync data between Android App and webserver

If we think about today, accepted answer is too old. As we know that we have many new libraries which can help you to make this types of application.

You should learn following topics that will helps you surely:

  • SyncAdapter: The sync adapter component in your app encapsulates the code for the tasks that transfer data between the device and a server. Based on the scheduling and triggers you provide in your app, the sync adapter framework runs the code in the sync adapter component.

  • Realm: Realm is a mobile database: a replacement for SQLite & Core Data.

  • Retrofit Type-safe HTTP client for Android and Java by Square, Inc. Must Learn a-smart-way-to-use-retrofit

And your sync logic for database like: How to sync SQLite database on Android phone with MySQL database on server?

Best Luck to all new learner. :)

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

If you are using IIS Express and VS 2017:

Go to the Web Application Properties > Web Tab > Servers Section > And change the Bitness to x64.

How to convert an Array to a Set in Java

Quickly : you can do :

// Fixed-size list
List list = Arrays.asList(array);

// Growable list
list = new LinkedList(Arrays.asList(array));

// Duplicate elements are discarded
Set set = new HashSet(Arrays.asList(array));

and to reverse

// Create an array containing the elements in a list
Object[] objectArray = list.toArray();
MyClass[] array = (MyClass[])list.toArray(new MyClass[list.size()]);

// Create an array containing the elements in a set
objectArray = set.toArray();
array = (MyClass[])set.toArray(new MyClass[set.size()]);

How to list npm user-installed packages?

npm list -g --depth=0
  • npm: the Node package manager command line tool
  • list -g: display a tree of every package found in the user’s folders (without the -g option it only shows the current directory’s packages)
  • depth 0 / — depth=0: avoid including every package’s dependencies in the tree view

How to convert Django Model object to dict with its fields and values?

Maybe this help you. May this not covert many to many relantionship, but es pretty handy when you want to send your model in json format.

def serial_model(modelobj):
  opts = modelobj._meta.fields
  modeldict = model_to_dict(modelobj)
  for m in opts:
    if m.is_relation:
        foreignkey = getattr(modelobj, m.name)
        if foreignkey:
            try:
                modeldict[m.name] = serial_model(foreignkey)
            except:
                pass
  return modeldict

In Bootstrap open Enlarge image in modal

I know your question is tagged as boostrap-modal (althought you didn't mentioned Bootstrap explicity neither), but I loved to see the simple way W3.CSS solved this and I think is good to share it.

  <img src="/myImage.png" style="width:30%;cursor:zoom-in"
  onclick="document.getElementById('modal01').style.display='block'">

  <div id="modal01" class="w3-modal" onclick="this.style.display='none'">
    <div class="w3-modal-content w3-animate-zoom">
      <img src="/myImage.png" style="width:100%">
    </div>
  </div>

I let you a link to the W3School modal image example to see the headers to make W3.CSS work.

Concatenate rows of two dataframes in pandas

Thanks to @EdChum I was struggling with same problem especially when indexes do not match. Unfortunatly in pandas guide this case is missed (when you for example delete some rows)

import pandas as pd
t=pd.DataFrame()
t['a']=[1,2,3,4]
t=t.loc[t['a']>1] #now index starts from 1

u=pd.DataFrame()
u['b']=[1,2,3] #index starts from 0

#option 1
#keep index of t
u.index = t.index 

#option 2
#index of t starts from 0
t.reset_index(drop=True, inplace=True)

#now concat will keep number of rows 
r=pd.concat([t,u], axis=1)

Where's my invalid character (ORA-00911)

If you use the string literal exactly as you have shown us, the problem is the ; character at the end. You may not include that in the query string in the JDBC calls.

As you are inserting only a single row, a regular INSERT should be just fine even when inserting multiple rows. Using a batched statement is probable more efficient anywy. No need for INSERT ALL. Additionally you don't need the temporary clob and all that. You can simplify your method to something like this (assuming I got the parameters right):

String query1 = "select substr(to_char(max_data),1,4) as year, " + 
  "substr(to_char(max_data),5,6) as month, max_data " +
  "from dss_fin_user.acq_dashboard_src_load_success " + 
  "where source = 'CHQ PeopleSoft FS'";

String query2 = ".....";

String sql = "insert into domo_queries (clob_column) values (?)";
PreparedStatement pstmt = con.prepareStatement(sql);
StringReader reader = new StringReader(query1);
pstmt.setCharacterStream(1, reader, query1.length());
pstmt.addBatch();

reader = new StringReader(query2);
pstmt.setCharacterStream(1, reader, query2.length());
pstmt.addBatch();

pstmt.executeBatch();   
con.commit();

Selecting an element in iFrame jQuery

Take a look at this post: http://praveenbattula.blogspot.com/2009/09/access-iframe-content-using-jquery.html

$("#iframeID").contents().find("[tokenid=" + token + "]").html();

Place your selector in the find method.

This may not be possible however if the iframe is not coming from your server. Other posts talk about permission denied errors.

jQuery/JavaScript: accessing contents of an iframe

changing source on html5 video tag

I come with this to change video source dynamically. "canplay" event sometime doesn't fire in Firefox so i have added "loadedmetadata". Also i pause previous video if there is one...

var loadVideo = function(movieUrl) {
    console.log('loadVideo()');
    $videoLoading.show();
    var isReady = function (event) {
            console.log('video.isReady(event)', event.type);
            video.removeEventListener('canplay', isReady);
            video.removeEventListener('loadedmetadata', isReady);
            $videoLoading.hide();
            video.currentTime = 0;
            video.play();
        },
        whenPaused = function() {
            console.log('video.whenPaused()');
            video.removeEventListener('pause', whenPaused);
            video.addEventListener('canplay', isReady, false);
            video.addEventListener('loadedmetadata', isReady, false); // Sometimes Firefox don't trigger "canplay" event...
            video.src = movieUrl; // Change actual source
        };

    if (video.src && !video.paused) {
        video.addEventListener('pause', whenPaused, false);
        video.pause();
    }
    else whenPaused();
};

How to set specific Java version to Maven

You could configure compiling sources using different JDK with maven-compiler-plugin.

Just specify path to javac in <executable> tag. E.g for java11 it looks like:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.8.0</version>
    <configuration>
        <source>11</source>
        <target>11</target>
        <fork>true</fork>
        <executable>C:\Program Files\Java\jdk-11.0.1\bin\javac</executable> <!--PATH TO JAVAC -->
    </configuration>
</plugin>

Missing Authentication Token while accessing API Gateway?

sometimes this message shown when you are calling a wrong api

check your api endpoint

Google Maps API throws "Uncaught ReferenceError: google is not defined" only when using AJAX

What worked for me after following all your workarounds was to call the API:

 <script async defer src="https://maps.googleapis.com/maps/api/js?key=you_API_KEY&callback=initMap&libraries=places"
            type="text/javascript"></script>

before my : <div id="map"></div>

I am using .ASP NET (MVC)

What is limiting the # of simultaneous connections my ASP.NET application can make to a web service?

Most of the answers provided here address the number of incoming requests to your backend webservice, not the number of outgoing requests you can make from your ASP.net application to your backend service.

It's not your backend webservice that is throttling your request rate here, it is the number of open connections your calling application is willing to establish to the same endpoint (same URL).

You can remove this limitation by adding the following configuration section to your machine.config file:

<configuration>
  <system.net>
    <connectionManagement>
      <add address="*" maxconnection="65535"/>
    </connectionManagement>
  </system.net>
</configuration>

You could of course pick a more reasonable number if you'd like such as 50 or 100 concurrent connections. But the above will open it right up to max. You can also specify a specific address for the open limit rule above rather than the '*' which indicates all addresses.

MSDN Documentation for System.Net.connectionManagement

Another Great Resource for understanding ConnectManagement in .NET

Hope this solves your problem!

EDIT: Oops, I do see you have the connection management mentioned in your code above. I will leave my above info as it is relevant for future enquirers with the same problem. However, please note there are currently 4 different machine.config files on most up to date servers!

There is .NET Framework v2 running under both 32-bit and 64-bit as well as .NET Framework v4 also running under both 32-bit and 64-bit. Depending on your chosen settings for your application pool you could be using any one of these 4 different machine.config files! Please check all 4 machine.config files typically located here:

  • C:\Windows\Microsoft.NET\Framework\v2.0.50727\CONFIG
  • C:\Windows\Microsoft.NET\Framework64\v2.0.50727\CONFIG
  • C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config
  • C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config

The character encoding of the plain text document was not declared - mootool script

Check your URL's protocol.

You will also see this error if you host an encrypted page (https) and open it as plain text (http) in Firefox.

javax.servlet.ServletException cannot be resolved to a type in spring web app

import javax.servlet

STEP 1

Go to properties of your project ( with Alt+Enter or righ-click )

STEP 2

check on Apache Tomcat v7.0 under Targeted Runtime and it works.

source: https://stackoverflow.com/a/9287149

how to apply click event listener to image in android

Try this example.

activity_main.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

<GridView
    android:numColumns="auto_fit"
    android:gravity="center"
    android:columnWidth="100dp"
    android:stretchMode="columnWidth"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/grid"
    android:background="#fff7ff"
    />

    </LinearLayout>

grid_single.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="5dp" >

    <ImageView
        android:id="@+id/grid_image"
        android:layout_width="60dp"
        android:layout_height="60dp"

        >
    </ImageView>

    <TextView
        android:id="@+id/grid_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dp"
        android:textSize="9sp"
        android:textColor="#3a0fff">
    </TextView>

</LinearLayout>

CustomGrid.java:

package com.example.lalit.gridtest;

import android.content.Context;
        import android.view.LayoutInflater;
        import android.view.View;
        import android.view.ViewGroup;
        import android.widget.BaseAdapter;
        import android.widget.ImageView;
        import android.widget.TextView;

public class CustomGrid extends BaseAdapter {
    private Context mContext;
    private final String[] web;
    private final int[] Imageid;

    public CustomGrid(Context c, String[] web, int[] Imageid) {
        mContext = c;
        this.Imageid = Imageid;
        this.web = web;
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return web.length;
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        View grid;
        LayoutInflater inflater = (LayoutInflater) mContext
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        if (convertView == null) {

            grid = new View(mContext);
            grid = inflater.inflate(R.layout.grid_single, null);
            TextView textView = (TextView) grid.findViewById(R.id.grid_text);
            ImageView imageView = (ImageView) grid.findViewById(R.id.grid_image);
            textView.setText(web[position]);
            imageView.setImageResource(Imageid[position]);
        } else {
            grid = (View) convertView;
        }

        return grid;
    }
}

MainActivity.java:

package com.example.lalit.gridtest;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity {
    GridView grid;
    String[] web = {
            "Mom",
            "Mahendra",
            "Narayan",
            "Bhai",
            "Deepak",
            "Sanjay",
            "Navdeep",
            "Lovesh",


    };
    int[] imageId = {
            R.drawable.ic_launcher,
            R.drawable.ic_launcher,
            R.drawable.ic_launcher,
            R.drawable.ic_launcher,
            R.drawable.ic_launcher,
            R.drawable.ic_launcher,
            R.drawable.ic_launcher,
            R.drawable.ic_launcher,
            R.drawable.ic_launcher,
            R.drawable.ic_launcher,
            R.drawable.ic_launcher,
            R.drawable.ic_launcher,
            R.drawable.ic_launcher,
            R.drawable.ic_launcher,
            R.drawable.ic_launcher

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final CustomGrid adapter = new CustomGrid(MainActivity.this, web, imageId);
        grid = (GridView) findViewById(R.id.grid);
        grid.setAdapter(adapter);
        grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id){

                if (web[position].toString().equals("Mom")) {
                    try {
                        String uri ="te:"+ "**********";

                        Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(uri));
                        startActivity(callIntent);
                    } catch (Exception e) {
                        Toast.makeText(getApplicationContext(), "Your call has failed...",
                                Toast.LENGTH_LONG).show();
                        e.printStackTrace();

                    }
                }


                    if (web[position].toString().equals("Mahendra")) {
                        try {
                            String uri = "tel:" + "**********";

                            Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(uri));
                            startActivity(callIntent);
                        } catch (Exception e) {
                            Toast.makeText(getApplicationContext(), "Your call has failed...",
                                    Toast.LENGTH_LONG).show();
                            e.printStackTrace();

                        }
                    }


                      if(web[position].toString().equals("Narayan")){

                    try {
                        String uri = "tel:" + "**********";

                        Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(uri));
                        startActivity(callIntent);
                    } catch (Exception e) {
                        Toast.makeText(getApplicationContext(), "Your call has failed...",
                                Toast.LENGTH_LONG).show();
                        e.printStackTrace();

                    }


             }
                if(web[position].toString().equals("Bhai")){

                    try {
                        String uri = "tel:" + "**********";

                        Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(uri));
                        startActivity(callIntent);
                    } catch (Exception e) {
                        Toast.makeText(getApplicationContext(), "Your call has failed...",
                                Toast.LENGTH_LONG).show();
                        e.printStackTrace();

                    }


                }

                if(web[position].toString().equals("Deepak")){

                    try {
                        String uri = "tel:" + "**********";

                        Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(uri));
                        startActivity(callIntent);
                    } catch (Exception e) {
                        Toast.makeText(getApplicationContext(), "Your call has failed...",
                                Toast.LENGTH_LONG).show();
                        e.printStackTrace();

                    }


                }


                if(web[position].toString().equals("Sanjay")){

                    try {
                        String uri = "tel:" + "**********";

                        Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(uri));
                        startActivity(callIntent);
                    } catch (Exception e) {
                        Toast.makeText(getApplicationContext(), "Your call has failed...",
                                Toast.LENGTH_LONG).show();
                        e.printStackTrace();

                    }


                }
                if(web[position].toString().equals("Navdeep")){

                    try {
                        String uri = "tel:" + "**********";

                        Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(uri));
                        startActivity(callIntent);
                    } catch (Exception e) {
                        Toast.makeText(getApplicationContext(), "Your call has failed...",
                                Toast.LENGTH_LONG).show();
                        e.printStackTrace();

                    }


                }
                if(web[position].toString().equals("Lovesh")){

                    try {
                        String uri = "tel:" + "**********";

                        Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(uri));
                        startActivity(callIntent);
                    } catch (Exception e) {
                        Toast.makeText(getApplicationContext(), "Your call has failed...",
                                Toast.LENGTH_LONG).show();
                        e.printStackTrace();

                    }


                }

                }



        });

    }

    }

AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.lalit.gridtest" >
    <uses-permission android:name="android.permission.CALL_PHONE" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Dart/Flutter : Converting timestamp

Full code for anyone who needs it:

String readTimestamp(int timestamp) {
    var now = DateTime.now();
    var format = DateFormat('HH:mm a');
    var date = DateTime.fromMillisecondsSinceEpoch(timestamp * 1000);
    var diff = now.difference(date);
    var time = '';

    if (diff.inSeconds <= 0 || diff.inSeconds > 0 && diff.inMinutes == 0 || diff.inMinutes > 0 && diff.inHours == 0 || diff.inHours > 0 && diff.inDays == 0) {
      time = format.format(date);
    } else if (diff.inDays > 0 && diff.inDays < 7) {
      if (diff.inDays == 1) {
        time = diff.inDays.toString() + ' DAY AGO';
      } else {
        time = diff.inDays.toString() + ' DAYS AGO';
      }
    } else {
      if (diff.inDays == 7) {
        time = (diff.inDays / 7).floor().toString() + ' WEEK AGO';
      } else {

        time = (diff.inDays / 7).floor().toString() + ' WEEKS AGO';
      }
    }

    return time;
  }

Thank you Alex Haslam for the help!

Can you use if/else conditions in CSS?

CSS is a nicely designed paradigm, and many of it's features are not much used.

If by a condition and variable you mean a mechanism to distribute a change of some value to the whole document, or under a scope of some element, then this is how to do it:

_x000D_
_x000D_
var myVar = 4;_x000D_
document.body.className = (myVar == 5 ? "active" : "normal");
_x000D_
body.active .menuItem {_x000D_
  background-position : 150px 8px;_x000D_
  background-color: black;_x000D_
}_x000D_
body.normal .menuItem {_x000D_
  background-position : 4px 8px; _x000D_
  background-color: green;_x000D_
}
_x000D_
<body>_x000D_
<div class="menuItem"></div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

This way, you distribute the impact of the variable throughout the CSS styles. This is similar to what @amichai and @SeReGa propose, but more versatile.

Another such trick is to distribute the ID of some active item throughout the document, e.g. again when highlighting a menu: (Freemarker syntax used)

_x000D_
_x000D_
var chosenCategory = 15;_x000D_
document.body.className = "category" + chosenCategory;
_x000D_
<#list categories as cat >_x000D_
    body.category${cat.id} .menuItem { font-weight: bold; }_x000D_
</#list>
_x000D_
<body>_x000D_
<div class="menuItem"></div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

Sure,this is only practical with a limited set of items, like categories or states, and not unlimited sets like e-shop goods, otherwise the generated CSS would be too big. But it is especially convenient when generating static offline documents.

One more trick to do "conditions" with CSS in combination with the generating platform is this:

_x000D_
_x000D_
.myList {_x000D_
   /* Default list formatting */_x000D_
}_x000D_
.myList.count0 {_x000D_
   /* Hide the list when there is no item. */_x000D_
   display: none;_x000D_
}_x000D_
.myList.count1 {_x000D_
   /* Special treatment if there is just 1 item */_x000D_
   color: gray;_x000D_
}
_x000D_
<ul class="myList count${items.size()}">_x000D_
<!-- Iterate list's items here -->_x000D_
<li>Something...</div>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Check if a String contains a special character

Convert the string into char array with all the letters in lower case:

char c[] = str.toLowerCase().toCharArray();

Then you can use Character.isLetterOrDigit(c[index]) to find out which index has special characters.

Printing Java Collections Nicely (toString Doesn't Return Pretty Output)

Just Modified the previous example to print even collection containing user defined objects.

public class ToStringHelper {

    private  static String separator = "\n";

    public ToStringHelper(String seperator) {
        super();
        ToStringHelper.separator = seperator;

    }

    public  static String toString(List<?> l) {
        StringBuilder sb = new StringBuilder();
        String sep = "";
        for (Object object : l) {
            String v = ToStringBuilder.reflectionToString(object);
            int start = v.indexOf("[");
            int end = v.indexOf("]");
            String st =  v.substring(start,end+1);
            sb.append(sep).append(st);
            sep = separator;
        }
        return sb.toString();
    }

    public static String toString(Map<?,?> m) {
        StringBuilder sb = new StringBuilder();
        String sep = "";
        for (Object object : m.keySet()) {
            String v = ToStringBuilder.reflectionToString(m.get(object));
            int start = v.indexOf("[");
            int end = v.indexOf("]");
            String st =  v.substring(start,end+1);
            sb.append(sep).append(st);
            sep = separator;
        }
        return sb.toString();
    }

    public static String toString(Set<?> s) {
        StringBuilder sb = new StringBuilder();
        String sep = "";
        for (Object object : s) {
            String v = ToStringBuilder.reflectionToString(object);
            int start = v.indexOf("[");
            int end = v.indexOf("]");
            String st =  v.substring(start,end+1);
            sb.append(sep).append(st);
            sep = separator;
        }
        return sb.toString();
    }

    public static void print(List<?> l) {
        System.out.println(toString(l));    
    }
    public static void print(Map<?,?> m) {
        System.out.println(toString(m));    
    }
    public static void print(Set<?> s) {
        System.out.println(toString(s));    
    }

}

Static nested class in Java, why?

One of the reasons for static vs. normal have to do with classloading. You cannot instantiate an inner class in the constructor of it's parent.

PS: I've always understood 'nested' and 'inner' to be interchangeable. There may be subtle nuances in the terms but most Java developers would understand either.

Does C# have an equivalent to JavaScript's encodeURIComponent()?

System.Uri.EscapeUriString() didn't seem to do anything, but System.Uri.EscapeDataString() worked for me.

How to position the div popup dialog to the center of browser screen?

I write a code in jquery. It isnt seen an easy way. But i hope it is useful for you.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<style type="text/css">

.popup{
    border: 4px solid #6b6a63;
    width: 800px;
    border-radius :7px;
    margin : auto;
    padding : 20px;
    position:fixed;
}

</style>

<div id="popup" class="popup">
some lengthy text<br>
some lengthy text<br>
some lengthy text<br>
some lengthy text<br>
some lengthy text<br>
some lengthy text<br>
some lengthy text<br>
some lengthy text<br>
</div>

<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script>
$(document).ready(function(){
    var popup_height = document.getElementById('popup').offsetHeight;
    var popup_width = document.getElementById('popup').offsetWidth;
    $(".popup").css('top',(($(window).height()-popup_height)/2));
    $(".popup").css('left',(($(window).width()-popup_width)/2));
});
</script>

Using git to get just the latest revision

Alternate solution to doing shallow clone (git clone --depth=1 <URL>) would be, if remote side supports it, to use --remote option of git archive:

$ git archive --format=tar --remote=<repository URL> HEAD | tar xf -

Or, if remote repository in question is browse-able using some web interface like gitweb or GitHub, then there is a chance that it has 'snapshot' feature, and you can download latest version (without versioning information) from web interface.

Eclipse: How to build an executable jar with external jar?

As a good practice you can use an Ant Script (Eclipse comes with it) to generate your JAR file. Inside this JAR you can have all dependent libs.

You can even set the MANIFEST's Class-path header to point to files in your filesystem, it's not a good practice though.

Ant build.xml script example:

<project name="jar with libs" default="compile and build" basedir=".">
<!-- this is used at compile time -->
<path id="example-classpath">
    <pathelement location="${root-dir}" />
    <fileset dir="D:/LIC/xalan-j_2_7_1" includes="*.jar" />
</path>

<target name="compile and build">
    <!-- deletes previously created jar -->
    <delete file="test.jar" />

    <!-- compile your code and drop .class into "bin" directory -->
    <javac srcdir="${basedir}" destdir="bin" debug="true" deprecation="on">
        <!-- this is telling the compiler where are the dependencies -->
        <classpath refid="example-classpath" />
    </javac>

    <!-- copy the JARs that you need to "bin" directory  -->
    <copy todir="bin">
        <fileset dir="D:/LIC/xalan-j_2_7_1" includes="*.jar" />
    </copy>

    <!-- creates your jar with the contents inside "bin" (now with your .class and .jar dependencies) -->
    <jar destfile="test.jar" basedir="bin" duplicate="preserve">
        <manifest>
            <!-- Who is building this jar? -->
            <attribute name="Built-By" value="${user.name}" />
            <!-- Information about the program itself -->
            <attribute name="Implementation-Vendor" value="ACME inc." />
            <attribute name="Implementation-Title" value="GreatProduct" />
            <attribute name="Implementation-Version" value="1.0.0beta2" />
            <!-- this tells which class should run when executing your jar -->
            <attribute name="Main-class" value="ApplyXPath" />
        </manifest>
    </jar>
</target>

Locate Git installation folder on Mac OS X

On Linux the command is whereis. Alternatively you can issue find / -name git and wait for an eternity. Alternatively try echo $PATH | sed "s/:/ /g" | xargs -L 1 ls | grep git

Is it possible to get multiple values from a subquery?

View this web: http://www.w3resource.com/sql/subqueries/multiplee-row-column-subqueries.php

Use example

select ord_num, agent_code, ord_date, ord_amount  
from orders  
where(agent_code, ord_amount) IN  
(SELECT agent_code, MIN(ord_amount)  
FROM orders   
GROUP BY agent_code);    

Faster alternative in Oracle to SELECT COUNT(*) FROM sometable

There was a relevant answer from Ask Tom published in April 2016.

If you have sufficient server power, you can do

select /*+ parallel */ count(*) from sometable

If you are just after an approximation, you can do :

select 5 * count(*) from sometable sample block (10);

Also, if there is

  1. a column that contains no nulls, but is not defined as NOT NULL, and
  2. there is an index on that column

you could try:

select /*+ index_ffs(t) */ count(*) from sometable  t where indexed_col is not null

UIScrollView scroll to bottom programmatically

Using UIScrollView's setContentOffset:animated: function to scroll to the bottom in Swift.

let bottomOffset : CGPoint = CGPointMake(0, scrollView.contentSize.height - scrollView.bounds.size.height + scrollView.contentInset.bottom)
scrollView.setContentOffset(bottomOffset, animated: true)

Searching a string in eclipse workspace

Goto Search->File

You will get an window, you can give either simple search text or regx pattern. Once you enter your search keyword click Search and make sure that Scope is Workspace.

You may use this for Replace as well.

Python Flask, how to set content type

You can try the following method(python3.6.2):

case one:

@app.route('/hello')
def hello():

    headers={ 'content-type':'text/plain' ,'location':'http://www.stackoverflow'}
    response = make_response('<h1>hello world</h1>',301)
    response.headers = headers
    return response

case two:

@app.route('/hello')
def hello():

    headers={ 'content-type':'text/plain' ,'location':'http://www.stackoverflow.com'}
    return '<h1>hello world</h1>',301,headers

I am using Flask .And if you want to return json,you can write this:

import json # 
@app.route('/search/<keyword>')
def search(keyword):

    result = Book.search_by_keyword(keyword)
    return json.dumps(result),200,{'content-type':'application/json'}


from flask import jsonify
@app.route('/search/<keyword>')
def search(keyword):

    result = Book.search_by_keyword(keyword)
    return jsonify(result)

Handle JSON Decode Error when nothing returned

There is a rule in Python programming called "it is Easier to Ask for Forgiveness than for Permission" (in short: EAFP). It means that you should catch exceptions instead of checking values for validity.

Thus, try the following:

try:
    qByUser = byUsrUrlObj.read()
    qUserData = json.loads(qByUser).decode('utf-8')
    questionSubjs = qUserData["all"]["questions"]
except ValueError:  # includes simplejson.decoder.JSONDecodeError
    print 'Decoding JSON has failed'

EDIT: Since simplejson.decoder.JSONDecodeError actually inherits from ValueError (proof here), I simplified the catch statement by just using ValueError.

Can I have multiple Xcode versions installed?

Staring with Xcode 9, the beta Xcode is labeled 'Xcode-beta.app' and is designed to live side by side with the production version. Info can be found in the Xcode release notes here. (Not using direct link because it breaks often).

From Apple:

Xcode 9 beta 4 can coexist with previous versions of Xcode. Prerelease versions of Xcode are made available from developer.apple.com, packaged in a compressed XIP file. To install Xcode during the beta period, download the XIP file, double-click the file to expand it in place, then drag Xcode-beta.app to the Applications folder

How to print pthread_t

Just a supplement to the first post: use a user defined union type to store the pthread_t:

union tid {
    pthread_t pthread_id;
    unsigned long converted_id;
};

Whenever you want to print pthread_t, create a tid and assign tid.pthread_id = ..., then print tid.converted_id.

Use Robocopy to copy only changed files?

You can use robocopy to copy files with an archive flag and reset the attribute. Use /M command line, this is my backup script with few extra tricks.

This script needs NirCmd tool to keep mouse moving so that my machine won't fall into sleep. Script is using a lockfile to tell when backup script is completed and mousemove.bat script is closed. You may leave this part out.

Another is 7-Zip tool for splitting virtualbox files smaller than 4GB files, my destination folder is still FAT32 so this is mandatory. I should use NTFS disk but haven't converted backup disks yet.

backup-robocopy.bat

@REM https://technet.microsoft.com/en-us/library/cc733145.aspx
@REM http://www.skonet.com/articles_archive/robocopy_job_template.aspx

set basedir=%~dp0
del /Q %basedir%backup-robocopy-log.txt

set dt=%date%_%time:~0,8%
echo "%dt% robocopy started" > %basedir%backup-robocopy-lock.txt
start "Keep system awake" /MIN /LOW  cmd.exe /C %basedir%backup-robocopy-movemouse.bat

set dest=E:\backup

call :BACKUP "Program Files\MariaDB 5.5\data"
call :BACKUP "projects"
call :BACKUP "Users\Myname"

:SPLIT
@REM Split +4GB file to multiple files to support FAT32 destination disk,
@REM splitted files must be stored outside of the robocopy destination folder.
set srcfile=C:\Users\Myname\VirtualBox VMs\Ubuntu\Ubuntu.vdi
set dstfile=%dest%\Users\Myname\VirtualBox VMs\Ubuntu\Ubuntu.vdi
set dstfile2=%dest%\non-robocopy\Users\Myname\VirtualBox VMs\Ubuntu\Ubuntu.vdi
IF NOT EXIST "%dstfile%" (
  IF NOT EXIST "%dstfile2%.7z.001" attrib +A "%srcfile%"
  dir /b /aa "%srcfile%" && (
    del /Q "%dstfile2%.7z.*"
    c:\apps\commands\7za.exe -mx0 -v4000m u "%dstfile2%.7z"  "%srcfile%"
    attrib -A "%srcfile%"
    @set dt=%date%_%time:~0,8%
    @echo %dt% Splitted %srcfile% >> %basedir%backup-robocopy-log.txt
  )
)

del /Q %basedir%backup-robocopy-lock.txt
GOTO :END


:BACKUP
TITLE Backup %~1
robocopy.exe "c:\%~1" "%dest%\%~1" /JOB:%basedir%backup-robocopy-job.rcj
GOTO :EOF


:END
@set dt=%date%_%time:~0,8%
@echo %dt% robocopy completed >> %basedir%backup-robocopy-log.txt
@echo %dt% robocopy completed
@pause

backup-robocopy-job.rcj

:: Robocopy Job Parameters
:: robocopy.exe "c:\projects" "E:\backup\projects" /JOB:backup-robocopy-job.rcj


:: Source Directory (this is given in command line)
::/SD:c:\examplefolder

:: Destination Directory (this is given in command line)
::/DD:E:\backup\examplefolder

:: Include files matching these names
/IF
    *.*

/M      :: copy only files with the Archive attribute and reset it.
/XJD    :: eXclude Junction points for Directories.

:: Exclude Directories
/XD
    C:\projects\bak
    C:\projects\old
    C:\project\tomcat\logs
    C:\project\tomcat\work
    C:\Users\Myname\.eclipse
    C:\Users\Myname\.m2
    C:\Users\Myname\.thumbnails
    C:\Users\Myname\AppData
    C:\Users\Myname\Favorites
    C:\Users\Myname\Links
    C:\Users\Myname\Saved Games
    C:\Users\Myname\Searches

:: Exclude files matching these names
/XF 
    C:\Users\Myname\ntuser.dat  
    *.~bpl

:: Exclude files with any of the given Attributes set
:: S=System, H=Hidden
/XA:SH      

:: Copy options
/S          :: copy Subdirectories, but not empty ones.
/E          :: copy subdirectories, including Empty ones.
/COPY:DAT   :: what to COPY for files (default is /COPY:DAT).
/DCOPY:T    :: COPY Directory Timestamps.
/PURGE      :: delete dest files/dirs that no longer exist in source.

:: Retry Options
/R:0        :: number of Retries on failed copies: default 1 million.
/W:1        :: Wait time between retries: default is 30 seconds.

:: Logging Options (LOG+ append)
/NDL        :: No Directory List - don't log directory names.
/NP         :: No Progress - don't display percentage copied.
/TEE        :: output to console window, as well as the log file.
/LOG+:c:\apps\commands\backup-robocopy-log.txt :: append to logfile

backup-robocopy-movemouse.bat

@echo off
@REM Move mouse to prevent maching from sleeping 
@rem while running a backup script

echo Keep system awake while robocopy is running,
echo this script moves a mouse once in a while.

set basedir=%~dp0
set IDX=0

:LOOP
IF NOT EXIST "%basedir%backup-robocopy-lock.txt" GOTO :EOF
SET /A IDX=%IDX% + 1
IF "%IDX%"=="240" (
  SET IDX=0
  echo Move mouse to keep system awake
  c:\apps\commands\nircmdc.exe sendmouse move 5 5
  c:\apps\commands\nircmdc.exe sendmouse move -5 -5
)
c:\apps\commands\nircmdc.exe wait 1000
GOTO :LOOP

Network tools that simulate slow network connection

In case you need to simulate network connection quality when developing for Windows Phone, you might give a try to a Visual Studio built-in tool called Simulation Dashboard (more details here http://msdn.microsoft.com/en-us/library/windowsphone/develop/jj206952(v=vs.105).aspx):

You can use the Simulation Dashboard in Visual Studio to test your app for these connection problems, and to help prevent users from encountering scenarios like the following:

  • High-resolution music or videos stutter or freeze while streaming, or take a long time to download over a low-bandwidth connection.
  • Calls to a web service fail with a timeout.
  • The app crashes when no network is available.
  • Data transfer does not resume when the network connection is lost and then restored.
  • The user’s battery is drained by a streaming app that uses the network inefficiently.
  • Mapping the user’s route is interrupted in a navigation app.

...

In Visual Studio, on the Tools menu, open Simulation Dashboard. Find the network simulation section of the dashboard and check the Enable Network Simulation check box.

What are good message queue options for nodejs?

Take a look at node-busmq - it's a production grade, highly available and scalable message bus backed by redis.

I wrote this module for our global cloud and it's currently deployed in our production environment in several datacenters around the world. It supports named queues, peer-to-peer communication, guaranteed delivery and federation.

For more information on why we created this module you can read this blog post: All Aboard The Message Bus

Git push hangs when pushing to Github?

In my case the issue was there was some process that had locked my keychain access...

Force quit all other apps to make sure keychain access is not locked on your Mac

How can I programmatically freeze the top row of an Excel worksheet in Excel 2007 VBA?

Rows("2:2").Select
ActiveWindow.FreezePanes = True

Select a different range for a different effect, much the same way you would do manually. The "Freeze Top Row" really just is a shortcut new in Excel 2007 (and up), it contains no added functionality compared to earlier versions of Excel.

It says that TypeError: document.getElementById(...) is null

You can use JQuery to ensure that all elements of the documents are ready before it starts the client side scripting

$(document).ready(
    function()
    {
        document.getElementById(elmId).innerHTML = value;
    }
);

How do I check if a column is empty or null in MySQL?

SELECT column_name FROM table_name WHERE column_name IN (NULL, '')

hibernate: LazyInitializationException: could not initialize proxy

It seems only your DAO are using session. Thus a new session is open then close for each call to a DAO method. Thus the execution of the program can be resumed as:

// open a session, get the number of entity and close the session
int startingCount = sfdao.count();

// open a session, create a new entity and close the session
sfdao.create( sf );

// open a session, read an entity and close the session
SecurityFiling sf2 = sfdao.read( sf.getId() );

// open a session, delete an entity and close the session
sfdao.delete( sf );

etc...

By default, collection and association in an entity are lazy: they are loaded from the database on demand. Thus:

sf.getSfSubmissionType().equals( sf2.getSfSubmissionType() )

is throwing an exception because it request a new loading from the database, and the session associated with the loading of the entity has already been closed.

There is two approaches to resolve this problem:

  • create a session to enclosed all our code. Thus it would mean changing your DAO content to avoid opening a second session

  • create a session then update (i.e. reconnect) your entity to this session before the assertions.

    session.update(object);

Convert SVG to PNG in Python

I did not find any of the answers satisfactory. All the mentioned libraries have some problem or the other like Cairo dropping support for python 3.6 (they dropped Python 2 support some 3 years ago!). Also, installing the mentioned libraries on the Mac was a pain.

Finally, I found the best solution was svglib + reportlab. Both installed without a hitch using pip and first call to convert from svg to png worked beautifully! Very happy with the solution.

Just 2 commands do the trick:

from svglib.svglib import svg2rlg
from reportlab.graphics import renderPM
drawing = svg2rlg("my.svg")
renderPM.drawToFile(drawing, "my.png", fmt="PNG")

Are there any limitations with these I should be aware of?

How do I get the old value of a changed cell in Excel VBA?

Here's a way I've used in the past. Please note that you have to add a reference to the Microsoft Scripting Runtime so you can use the Dictionary object - if you don't want to add that reference you can do this with Collections but they're slower and there's no elegant way to check .Exists (you have to trap the error).

Dim OldVals As New Dictionary
Private Sub Worksheet_Change(ByVal Target As Range)
Dim cell As Range
    For Each cell In Target
        If OldVals.Exists(cell.Address) Then
            Debug.Print "New value of " & cell.Address & " is " & cell.Value & "; old value was " & OldVals(cell.Address)
        Else
            Debug.Print "No old value for " + cell.Address
        End If
        OldVals(cell.Address) = cell.Value
    Next
End Sub

Like any similar method, this has its problems - first off, it won't know the "old" value until the value has actually been changed. To fix this you'd need to trap the Open event on the workbook and go through Sheet.UsedRange populating OldVals. Also, it will lose all its data if you reset the VBA project by stopping the debugger or some such.

Multiple select statements in Single query

SELECT  (
    SELECT COUNT(*)
    FROM   user_table
) AS tot_user,
(
    SELECT COUNT(*)
    FROM   cat_table
) AS tot_cat,
(
    SELECT COUNT(*)
    FROM   course_table
) AS tot_course

How do I link to part of a page? (hash?)

You use an anchor and a hash. For example:

Target of the Link:

 <a name="name_of_target">Content</a>

Link to the Target:

 <a href="#name_of_target">Link Text</a>

Or, if linking from a different page:

 <a href="http://path/to/page/#name_of_target">Link Text</a>

Convert double to string C++?

std::string stringify(double x)
 {
   std::ostringstream o;
   if (!(o << x))
     throw BadConversion("stringify(double)");
   return o.str();
 }

C++ FAQ: http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.1

How do I run a file on localhost?

i am working in VScode currently. i was wanting to run my html page just to see all my main elements.

1) first, in vs, right click desired html file and choose "copy path". do not choose relative.

2) finally, paste html path in address bar (i used chrome) and hit enter. your html page should display. hope this helps someone out.

how to draw directed graphs using networkx in python?

Instead of regular nx.draw you may want to use:

nx.draw_networkx(G[, pos, arrows, with_labels])

For example:

nx.draw_networkx(G, arrows=True, **options)

You can add options by initialising that ** variable like this:

options = {
    'node_color': 'blue',
    'node_size': 100,
    'width': 3,
    'arrowstyle': '-|>',
    'arrowsize': 12,
}

Also some functions support the directed=True parameter In this case this state is the default one:

G = nx.DiGraph(directed=True)

The networkx reference is found here.

Graph with arrows image

How to bind inverse boolean properties in WPF?

I had an inversion problem, but a neat solution.

Motivation was that the XAML designer would show an empty control e.g. when there was no datacontext / no MyValues (itemssource).

Initial code: hide control when MyValues is empty. Improved code: show control when MyValues is NOT null or empty.

Ofcourse the problem is how to express '1 or more items', which is the opposite of 0 items.

<ListBox ItemsSource={Binding MyValues}">
  <ListBox.Style x:Uid="F404D7B2-B7D3-11E7-A5A7-97680265A416">
    <Style TargetType="{x:Type ListBox}">
      <Style.Triggers>
        <DataTrigger Binding="{Binding MyValues.Count}">
          <Setter Property="Visibility" Value="Collapsed"/>
        </DataTrigger>
      </Style.Triggers>
    </Style>
  </ListBox.Style>
</ListBox>

I solved it by adding:

<DataTrigger Binding="{Binding MyValues.Count, FallbackValue=0, TargetNullValue=0}">

Ergo setting the default for the binding. Ofcourse this doesn't work for all kinds of inverse problems, but helped me out with clean code.

Git refusing to merge unrelated histories on rebase

This usually happens when you commit first time to remote repository. As error clearly says "refusing to merge unrelated histories", we need to use --allow-unrelated-histories flag.

git pull origin master  --allow-unrelated-histories

Now there would be some conflicts which we have to solve manually. After that just commit the code and push it.

How to window.scrollTo() with a smooth effect

$('html, body').animate({scrollTop:1200},'50');

You can do this!

How do I get a list of folders and sub folders without the files?

I am using this from PowerShell:

dir -directory -name -recurse > list_my_folders.txt

How to set min-font-size in CSS

It will work perfectly with 50px. Which will act as a static and thus as min-width.

font-size: calc(50px + 5vw);

Changing the JFrame title

If your class extends JFrame then use this.setTitle(newTitle.getText());

If not and it contains a JFrame let's say named myFrame, then use myFrame.setTitle(newTitle.getText());

Now that you have posted your program, it is obvious that you need only one JTextField to get the new title. These changes will do the trick:

JTextField poolLengthText, poolWidthText, poolDepthText, poolVolumeText, hotTub,
        hotTubLengthText, hotTubWidthText, hotTubDepthText, hotTubVolumeText, temp, results,
        newTitle;

and:

    public void createOptions()
    {
        options = new JPanel();
        options.setLayout(null);
        JLabel labelOptions = new JLabel("Change Company Name:");
        labelOptions.setBounds(120, 10, 150, 20);
        options.add(labelOptions);
        newTitle = new JTextField("Some Title");
        newTitle.setBounds(80, 40, 225, 20);
        options.add(newTitle);
//        myTitle = new JTextField("My Title...");
//        myTitle.setBounds(80, 40, 225, 20);
//        myTitle.add(labelOptions);
        JButton newName = new JButton("Set New Name");
        newName.setBounds(60, 80, 150, 20);
        newName.addActionListener(this);
        options.add(newName);
        JButton Exit = new JButton("Exit");
        Exit.setBounds(250, 80, 80, 20);
        Exit.addActionListener(this);
        options.add(Exit);
    }

and:

private void New_Name()
{
    this.setTitle(newTitle.getText());
}

Is there a command to undo git init?

I'm running Windows 7 with git bash console. The above commands wouldn't work for me.

So I did it via Windows Explorer. I checked show hidden files, went to my projects directory and manually deleted the .git folder. Then back in the command line I checked by running git status.

Which returned...

fatal: Not a git repository (or any of the parent directories): .git

Which is exactly the result I wanted. It returned that the directory is not a git repository (anymore!).

C Linking Error: undefined reference to 'main'

Generally you compile most .c files in the following way:

gcc foo.c -o foo. It might vary depending on what #includes you used or if you have any external .h files. Generally, when you have a C file, it looks somewhat like the following:

#include <stdio.h>
    /* any other includes, prototypes, struct delcarations... */
    int main(){
    */ code */
}

When I get an 'undefined reference to main', it usually means that I have a .c file that does not have int main() in the file. If you first learned java, this is an understandable manner of confusion since in Java, your code usually looks like the following:

//any import statements you have
public class Foo{
    int main(){}
 }

I would advise looking to see if you have int main() at the top.

Making a div vertically scrollable using CSS

You can use overflow-y: scroll for vertical scrolling.

_x000D_
_x000D_
<div  style="overflow-y:scroll; height:400px; background:gray">_x000D_
  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum._x000D_
  _x000D_
  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum._x000D_
  _x000D_
  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum._x000D_
  _x000D_
  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum._x000D_
  _x000D_
  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum._x000D_
  _x000D_
 </div>
_x000D_
_x000D_
_x000D_

Collection was modified; enumeration operation may not execute in ArrayList

I agree with several of the points I've read in this post and I've incorporated them into my solution to solve the exact same issue as the original posting.

That said, the comments I appreciated are:

  • "unless you are using .NET 1.0 or 1.1, use List<T> instead of ArrayList. "

  • "Also, add the item(s) to be deleted to a new list. Then go through and delete those items." .. in my case I just created a new List and the populated it with the valid data values.

e.g.

private List<string> managedLocationIDList = new List<string>();
string managedLocationIDs = ";1321;1235;;" // user input, should be semicolon seperated list of values

managedLocationIDList.AddRange(managedLocationIDs.Split(new char[] { ';' }));
List<string> checkLocationIDs = new List<string>();

// Remove any duplicate ID's and cleanup the string holding the list if ID's
Functions helper = new Functions();
checkLocationIDs = helper.ParseList(managedLocationIDList);

...
public List<string> ParseList(List<string> checkList)
{
    List<string> verifiedList = new List<string>();

    foreach (string listItem in checkList)
    if (!verifiedList.Contains(listItem.Trim()) && listItem != string.Empty)
        verifiedList.Add(listItem.Trim());

    verifiedList.Sort();
    return verifiedList;
}        

Why does checking a variable against multiple values with `OR` only check the first value?

("Jesse" or "jesse")

The above expression tests whether or not "Jesse" evaluates to True. If it does, then the expression will return it; otherwise, it will return "jesse". The expression is equivalent to writing:

"Jesse" if "Jesse" else "jesse"

Because "Jesse" is a non-empty string though, it will always evaluate to True and thus be returned:

>>> bool("Jesse")  # Non-empty strings evaluate to True in Python
True
>>> bool("")  # Empty strings evaluate to False
False
>>>
>>> ("Jesse" or "jesse")
'Jesse'
>>> ("" or "jesse")
'jesse'
>>>

This means that the expression:

name == ("Jesse" or "jesse")

is basically equivalent to writing this:

name == "Jesse"

In order to fix your problem, you can use the in operator:

# Test whether the value of name can be found in the tuple ("Jesse", "jesse")
if name in ("Jesse", "jesse"):

Or, you can lowercase the value of name with str.lower and then compare it to "jesse" directly:

# This will also handle inputs such as "JeSSe", "jESSE", "JESSE", etc.
if name.lower() == "jesse":

Mailto on submit button

The full list of possible fields in the html based email-creating form:

  • subject
  • cc
  • bcc
  • body
<form action="mailto:[email protected]" method="GET">
  <input name="subject" type="text" /></br>
  <input name="cc" type="email" /><br />
  <input name="bcc" type="email" /><br />
  <textarea name="body"></textarea><br />
  <input type="submit" value="Send" />
</form>

https://codepen.io/garfunkel61/pen/oYGNGp

Powershell get ipv4 address into a variable

Here is another solution:

$env:HostIP = (
    Get-NetIPConfiguration |
    Where-Object {
        $_.IPv4DefaultGateway -ne $null -and
        $_.NetAdapter.Status -ne "Disconnected"
    }
).IPv4Address.IPAddress

What is the difference between the remap, noremap, nnoremap and vnoremap mapping commands in Vim?

One difference is that:

  • :map does nvo == normal + (visual + select) + operator pending
  • :map! does ic == insert + command-line mode

as stated on help map-modes tables.

So: map does not map to all modes.

To map to all modes you need both :map and :map!.

Spring schemaLocation fails when there is no internet connection

You need to add schema locations to your bean definition, and then they can be found in classpath instead of fetched over the net. Given your formatting problems, I'm not 100% sure that you aren't doing this already.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<!-- empty: the beans we use are in the base class's context. -->
</beans>

How to delete files recursively from an S3 bucket

With the latest aws-cli python command line tools, to recursively delete all the files under a folder in a bucket is just:

aws s3 rm --recursive s3://your_bucket_name/foo/

Or delete everything under the bucket:

aws s3 rm --recursive s3://your_bucket_name

If what you want is to actually delete the bucket, there is one-step shortcut:

aws s3 rb --force s3://your_bucket_name

which will remove the contents in that bucket recursively then delete the bucket.

Note: the s3:// protocol prefix is required for these commands to work

Fatal error: Please read "Security" section of the manual to find out how to run mysqld as root

Try this for Amazon Linux AMI or for centOS

sudo service mysqld restart

Foreach loop in java for a custom object list

Using can also use Java 8 stream API and do the same thing in one line.

If you want to print any specific property then use this syntax:

ArrayList<Room> rooms = new ArrayList<>();
rooms.forEach(room -> System.out.println(room.getName()));

OR

ArrayList<Room> rooms = new ArrayList<>();
rooms.forEach(room -> {
    // here room is available
});

if you want to print all the properties of Java object then use this:

ArrayList<Room> rooms = new ArrayList<>();
rooms.forEach(System.out::println);

How to read and write excel file

Sure , you will find the code below useful and easy to read and write. This is a util class which you can use in your main method and then you are good to use all methods below.

     public class ExcelUtils {
     private static XSSFSheet ExcelWSheet;
     private static XSSFWorkbook ExcelWBook;
     private static XSSFCell Cell;
     private static XSSFRow Row;
     File fileName = new File("C:\\Users\\satekuma\\Pro\\Fund.xlsx");
     public void setExcelFile(File Path, String SheetName) throws Exception                

    try {
        FileInputStream ExcelFile = new FileInputStream(Path);
        ExcelWBook = new XSSFWorkbook(ExcelFile);
        ExcelWSheet = ExcelWBook.getSheet(SheetName);
    } catch (Exception e) {
        throw (e);
    }

}


      public static String getCellData(int RowNum, int ColNum) throws Exception {

    try {
        Cell = ExcelWSheet.getRow(RowNum).getCell(ColNum);
        String CellData = Cell.getStringCellValue();
        return CellData;
    } catch (Exception e) {

        return "";

    }

}
public static void setCellData(String Result, int RowNum, int ColNum, File Path) throws Exception {

    try {
        Row = ExcelWSheet.createRow(RowNum - 1);
        Cell = Row.createCell(ColNum - 1);
        Cell.setCellValue(Result);
        FileOutputStream fileOut = new FileOutputStream(Path);
        ExcelWBook.write(fileOut);
        fileOut.flush();
        fileOut.close();
    } catch (Exception e) {

        throw (e);

    }

}

}

javascript: using a condition in switch case

This works:

switch (true) {
    case liCount == 0:
        setLayoutState('start');
        var api = $('#UploadList').data('jsp');
        api.reinitialise();
        break;
    case liCount<=5 && liCount>0:
        setLayoutState('upload1Row');
        var api = $('#UploadList').data('jsp');
        api.reinitialise();
        break;
    case liCount<=10 && liCount>5:
        setLayoutState('upload2Rows');
        var api = $('#UploadList').data('jsp');
        api.reinitialise();
        break;
    case liCount>10:
        var api = $('#UploadList').data('jsp');
        api.reinitialise();
        break;                  
}

A previous version of this answer considered the parentheses to be the culprit. In truth, the parentheses are irrelevant here - the only thing necessary is switch(true){...} and for your case expressions to evaluate to booleans.

It works because, the value we give to the switch is used as the basis to compare against. Consequently, the case expressions, also evaluating to booleans will determine which case is run. Could also turn this around, and pass switch(false){..} and have the desired expressions evaluate to false instead of true.. but personally prefer dealing with conditions that evaluate to truthyness. However, it does work too, so worth keeping in mind to understand what it is doing.

Eg: if liCount is 3, the first comparison is true === (liCount == 0), meaning the first case is false. The switch then moves on to the next case true === (liCount<=5 && liCount>0). This expression evaluates to true, meaning this case is run, and terminates at the break. I've added parentheses here to make it clearer, but they are optional, depending on the complexity of your expression.

It's pretty simple, and a neat way (if it fits with what you are trying to do) of handling a long series of conditions, where perhaps a long series of ìf() ... else if() ... else if () ... might introduce a lot of visual noise or fragility.

Use with caution, because it is a non-standard pattern, despite being valid code.

How to enable support of CPU virtualization on Macbook Pro?

Here is a way to check is virtualization is enabled or disabled by the firmware as suggested by this link in parallels.com.

How to check that Intel VT-x is supported in CPU:

  1. Open Terminal application from Application/Utilities

  2. Copy/paste command bellow

sysctl -a | grep machdep.cpu.features

  1. You may see output similar to:

Mac:~ user$ sysctl -a | grep machdep.cpu.features kern.exec: unknown type returned machdep.cpu.features: FPU VME DE PSE TSC MSR PAE MCE CX8 APIC SEP MTRR PGE MCA CMOV PAT CLFSH DS ACPI MMX FXSR SSE SSE2 SS HTT TM SSE3 MON VMX EST TM2 TPR PDCM

If you see VMX entry then CPU supports Intel VT-x feature, but it still may be disabled.

Refer to this link on Apple.com to enable hardware support for virtualization:

Cannot deserialize the current JSON array (e.g. [1,2,3])

You can use this to solve your problem:

private async void btn_Go_Click(object sender, RoutedEventArgs e)
{
    HttpClient webClient = new HttpClient();
    Uri uri = new Uri("http://www.school-link.net/webservice/get_student/?id=" + txtVCode.Text);
    HttpResponseMessage response = await webClient.GetAsync(uri);
    var jsonString = await response.Content.ReadAsStringAsync();
    var _Data = JsonConvert.DeserializeObject <List<Student>>(jsonString);
    foreach (Student Student in _Data)
    {
        tb1.Text = Student.student_name;
    }
}

How to set an "Accept:" header on Spring RestTemplate request?

I suggest using one of the exchange methods that accepts an HttpEntity for which you can also set the HttpHeaders. (You can also specify the HTTP method you want to use.)

For example,

RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));

HttpEntity<String> entity = new HttpEntity<>("body", headers);

restTemplate.exchange(url, HttpMethod.POST, entity, String.class);

I prefer this solution because it's strongly typed, ie. exchange expects an HttpEntity.

However, you can also pass that HttpEntity as a request argument to postForObject.

HttpEntity<String> entity = new HttpEntity<>("body", headers);
restTemplate.postForObject(url, entity, String.class); 

This is mentioned in the RestTemplate#postForObject Javadoc.

The request parameter can be a HttpEntity in order to add additional HTTP headers to the request.

Video streaming over websockets using JavaScript

The Media Source Extensions has been proposed which would allow for Adaptive Bitrate Streaming implementations.

Is there a decent wait function in C++?

Well, this is an old post but I will just contribute to the question -- someone may find it useful later:

adding 'cin.get();' function just before the return of the main() seems to always stop the program from exiting before printing the results: see sample code below:

int main(){ string fname, lname;

  //ask user to enter name first and last name
  cout << "Please enter your first name: ";
  cin >> fname;

  cout << "Please enter your last name: ";
  cin >> lname;     
  cout << "\n\n\n\nyour first name is: " << fname << "\nyour last name is: " 
  << lname <<endl;

  //stop program from exiting before printing results on the screen
  cin.get();
  return 0;

}

Git status shows files as changed even though contents are the same

So, I tried just about everything here and want to contribute one more solution that fixed all of my problems. My issues was not with line endings or actual permissions or anything like that. It was because I had installed Cygwin and whole host of stuff that comes with that, which unbeknownst to me also installed its own version of git. I never noticed this, just that I was having strange issues with users and files being marked as changed (because of perms changes).

It turns out that I figured this out because I thought I should just update Git to the latest version, which I did, but running git --version returned the old version number. After the ensuing hunt for why, I found the cygwin bin directory root in my environment path, which contained a git executable, running at the old version number. Go figure.

This was also hard to find because I have TortoiseGit installed. My command line tools would use the cygwin version due to path fallbacks, and TortoiseGit was configured to use the windows version, making it even more confusing.

Hope this helps somebody.

Is it possible to use argsort in descending order?

Instead of using np.argsort you could use np.argpartition - if you only need the indices of the lowest/highest n elements.

That doesn't require to sort the whole array but just the part that you need but note that the "order inside your partition" is undefined, so while it gives the correct indices they might not be correctly ordered:

>>> avgDists = [1, 8, 6, 9, 4]
>>> np.array(avgDists).argpartition(2)[:2]  # indices of lowest 2 items
array([0, 4], dtype=int64)

>>> np.array(avgDists).argpartition(-2)[-2:]  # indices of highest 2 items
array([1, 3], dtype=int64)

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

  1. Standard Windows performance counters (look for other correlated activity, such as many GET requests, excessive network or disk I/O, etc); you can read them from code as well as from perfmon (to trigger data collection if CPU use exceeds a threshold, for example)
  2. Custom performance counters (particularly to time for off-box requests and other calls where execution time is uncertain)
  3. Load testing, using tools such as Visual Studio Team Test or WCAT
  4. If you can test on or upgrade to IIS 7, you can configure Failed Request Tracing to generate a trace if requests take more a certain amount of time
  5. Use logparser to see which requests arrived at the time of the CPU spike
  6. Code reviews / walk-throughs (in particular, look for loops that may not terminate properly, such as if an error happens, as well as locks and potential threading issues, such as the use of statics)
  7. CPU and memory profiling (can be difficult on a production system)
  8. Process Explorer
  9. Windows Resource Monitor
  10. Detailed error logging
  11. Custom trace logging, including execution time details (perhaps conditional, based on the CPU-use perf counter)
  12. Are the errors happening when the AppPool recycles? If so, it could be a clue.

Using Regular Expressions to Extract a Value in Java

Pattern p = Pattern.compile("(\\D+)(\\d+)(.*)");
Matcher m = p.matcher("this is your number:1234 thank you");
if (m.find()) {
    String someNumberStr = m.group(2);
    int someNumberInt = Integer.parseInt(someNumberStr);
}

Can I use multiple versions of jQuery on the same page?

Absolutely, yes you can. This link contains details about how you can achieve that: https://api.jquery.com/jquery.noconflict/.

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

Figured out quick solution, update your @NgModule code like this :

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';

@NgModule({
imports: [ BrowserModule, FormsModule ],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})

export class AppModule { }

Source: Can’t bind to ‘ngModel’ since it isn’t a known property of ‘input’

Boxplot in R showing the mean

I also think chart.Boxplot is the best option, it gives you the position of the mean but if you have a matrix with returns all you need is one line of code to get all the boxplots in one graph.

Here is a small ETF portfolio example.

library(zoo)
library(PerformanceAnalytics)
library(tseries)
library(xts)

VTI.prices = get.hist.quote(instrument = "VTI", start= "2007-03-01", end="2013-03-01",
                        quote = c("AdjClose"),provider = "yahoo",origin ="1970-01-01", 
                        compression = "m", retclass = c("zoo"))

VEU.prices = get.hist.quote(instrument = "VEU", start= "2007-03-01", end="2013-03-01",
                        quote = c("AdjClose"),provider = "yahoo",origin ="1970-01-01", 
                        compression = "m", retclass = c("zoo"))

VWO.prices = get.hist.quote(instrument = "VWO", start= "2007-03-01", end="2013-03-01",
                        quote = c("AdjClose"),provider = "yahoo",origin ="1970-01-01", 
                        compression = "m", retclass = c("zoo"))


VNQ.prices = get.hist.quote(instrument = "VNQ", start= "2007-03-01", end="2013-03-01",
                       quote = c("AdjClose"),provider = "yahoo",origin ="1970-01-01", 
                       compression = "m", retclass = c("zoo"))

TLT.prices = get.hist.quote(instrument = "TLT", start= "2007-03-01", end="2013-03-01",
                        quote = c("AdjClose"),provider = "yahoo",origin ="1970-01-01", 
                        compression = "m", retclass = c("zoo"))

TIP.prices = get.hist.quote(instrument = "TIP", start= "2007-03-01", end="2013-03-01",
                         quote = c("AdjClose"),provider = "yahoo",origin ="1970-01-01", 
                         compression = "m", retclass = c("zoo"))

index(VTI.prices) = as.yearmon(index(VTI.prices))
index(VEU.prices) = as.yearmon(index(VEU.prices))
index(VWO.prices) = as.yearmon(index(VWO.prices))

index(VNQ.prices) = as.yearmon(index(VNQ.prices))
index(TLT.prices) = as.yearmon(index(TLT.prices))
index(TIP.prices) = as.yearmon(index(TIP.prices))

Prices.z=merge(VTI.prices, VEU.prices, VWO.prices, VNQ.prices, 
           TLT.prices, TIP.prices)

colnames(Prices.z) = c("VTI", "VEU", "VWO" , "VNQ", "TLT", "TIP")

returnscc.z = diff(log(Prices.z))

start(returnscc.z)
end(returnscc.z)
colnames(returnscc.z) 
head(returnscc.z)

Return Matrix

ret.mat = coredata(returnscc.z)
class(ret.mat)
colnames(ret.mat)
head(ret.mat)

Box Plot of Return Matrix

chart.Boxplot(returnscc.z, names=T, horizontal=TRUE, colorset="darkgreen", as.Tufte =F,
          mean.symbol = 20, median.symbol="|", main="Return Distributions Comparison",
          element.color = "darkgray", outlier.symbol = 20, 
          xlab="Continuously Compounded Returns", sort.ascending=F)

You can try changing the mean.symbol, and remove or change the median.symbol. Hope it helped. :)

Plotting lines connecting points

Use the matplotlib.arrow() function and set the parameters head_length and head_width to zero to don't get an "arrow-end". The connections between the different points can be simply calculated using vector addition with: A = [1,2], B=[3,4] --> Connection between A and B is B-A = [2,2]. Drawing this vector starting at the tip of A ends at the tip of B.

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
style.use('fivethirtyeight')


A = np.array([[10,8],[1,2],[7,5],[3,5],[7,6],[8,7],[9,9],[4,5],[6,5],[6,8]])


fig = plt.figure(figsize=(10,10))
ax0 = fig.add_subplot(212)

ax0.scatter(A[:,0],A[:,1])


ax0.arrow(A[0][0],A[0][1],A[1][0]-A[0][0],A[1][1]-A[0][1],width=0.02,color='red',head_length=0.0,head_width=0.0)
ax0.arrow(A[2][0],A[2][1],A[9][0]-A[2][0],A[9][1]-A[2][1],width=0.02,color='red',head_length=0.0,head_width=0.0)
ax0.arrow(A[4][0],A[4][1],A[6][0]-A[4][0],A[6][1]-A[4][1],width=0.02,color='red',head_length=0.0,head_width=0.0)


plt.show()

enter image description here

PostgreSQL next value of the sequences?

I stumbled upon this question b/c I was trying to find the next sequence value by table. This didn't answer my question however this is how its done, and it may help those looking for the sequence value not by name but by table:

SELECT nextval(pg_get_serial_sequence('<your_table>', 'id')) AS new_id; 

Hope it helps :)

How can I use break or continue within for loop in Twig template?

This can be nearly done by setting a new variable as a flag to break iterating:

{% set break = false %}
{% for post in posts if not break %}
    <h2>{{ post.heading }}</h2>
    {% if post.id == 10 %}
        {% set break = true %}
    {% endif %}
{% endfor %}

An uglier, but working example for continue:

{% set continue = false %}
{% for post in posts %}
    {% if post.id == 10 %}
        {% set continue = true %}
    {% endif %}
    {% if not continue %}
        <h2>{{ post.heading }}</h2>
    {% endif %}
    {% if continue %}
        {% set continue = false %}
    {% endif %}
{% endfor %}

But there is no performance profit, only similar behaviour to the built-in break and continue statements like in flat PHP.

Custom checkbox image android

Copy the btn_check.xml from android-sdk/platforms/android-#/data/res/drawable to your project's drawable folder and change the 'on' and 'off' image states to your custom images.

Then your xml will just need android:button="@drawable/btn_check"

<CheckBox
    android:button="@drawable/btn_check"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:checked="true" />

If you want to use different default android icons, you can use android:button="@android:drawable/..."

Java ArrayList - Check if list is empty

You should use method listName.isEmpty()

Can I serve multiple clients using just Flask app.run() as standalone?

Tips from 2020:

From Flask 1.0, it defaults to enable multiple threads (source), you don't need to do anything, just upgrade it with:

$ pip install -U flask

If you are using flask run instead of app.run() with older versions, you can control the threaded behavior with a command option (--with-threads/--without-threads):

$ flask run --with-threads

It's same as app.run(threaded=True)

Using Default Arguments in a Function

My 2 cents with null coalescing operator ?? (since PHP 7)

function foo($blah, $x = null, $y = null) {
    $varX = $x ?? 'Default value X';
    $varY = $y ?? 'Default value Y';
    // ...
}

You can check more examples on my repl.it

Map a 2D array onto a 1D array

You should be able to access the 2d array with a simple pointer in place. The array[x][y] will be arranged in the pointer as p[0x * width + 0y][0x * width + 1y]...[0x * width + n-1y][1x * width + 0y] etc.

How can I debug a Perl script?

Use Eclipse with EPIC: It gives you a nice IDE with debugging possibilities, including the ability to place breakpoints and the Perl Expression View for inspecting the value of variables.

Disabling of EditText in Android

Set below properties in class:

editText.setFocusable(false);
editText.setEnabled(false);

It will work smoothly as you required.

Python unicode equal comparison failed

You may use the == operator to compare unicode objects for equality.

>>> s1 = u'Hello'
>>> s2 = unicode("Hello")
>>> type(s1), type(s2)
(<type 'unicode'>, <type 'unicode'>)
>>> s1==s2
True
>>> 
>>> s3='Hello'.decode('utf-8')
>>> type(s3)
<type 'unicode'>
>>> s1==s3
True
>>> 

But, your error message indicates that you aren't comparing unicode objects. You are probably comparing a unicode object to a str object, like so:

>>> u'Hello' == 'Hello'
True
>>> u'Hello' == '\x81\x01'
__main__:1: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
False

See how I have attempted to compare a unicode object against a string which does not represent a valid UTF8 encoding.

Your program, I suppose, is comparing unicode objects with str objects, and the contents of a str object is not a valid UTF8 encoding. This seems likely the result of you (the programmer) not knowing which variable holds unicide, which variable holds UTF8 and which variable holds the bytes read in from a file.

I recommend http://nedbatchelder.com/text/unipain.html, especially the advice to create a "Unicode Sandwich."

Can lambda functions be templated?

In C++11, lambda functions can not be templated, but in the next version of the ISO C++ Standard (often called C++14), this feature will be introduced. [Source]

Usage example:

auto get_container_size = [] (auto container) { return container.size(); };

Note that though the syntax uses the keyword auto, the type deduction will not use the rules of auto type deduction, but instead use the rules of template argument deduction. Also see the proposal for generic lambda expressions(and the update to this).

How to get a list of programs running with nohup

You cannot exactly get a list of commands started with nohup but you can see them along with your other processes by using the command ps x. Commands started with nohup will have a question mark in the TTY column.

Using Image control in WPF to display System.Drawing.Bitmap

It's easy for disk file, but harder for Bitmap in memory.

System.Drawing.Bitmap bmp;
Image image;
...
MemoryStream ms = new MemoryStream();
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
ms.Position = 0;
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.StreamSource = ms;
bi.EndInit();

image.Source = bi;

Stealed here

Server.Mappath in C# classlibrary

HostingEnvironment.MapPath
System.Web.Hosting.HostingEnvironment.MapPath(path);

Changes in import statement python3

For relative imports see the documentation. A relative import is when you import from a module relative to that module's location, instead of absolutely from sys.path.

As for import *, Python 2 allowed star imports within functions, for instance:

>>> def f():
...     from math import *
...     print sqrt

A warning is issued for this in Python 2 (at least recent versions). In Python 3 it is no longer allowed and you can only do star imports at the top level of a module (not inside functions or classes).

How to add a boolean datatype column to an existing table in sql?

In phpmyadmin, If you need to add a boolean datatype column to an existing table with default value true:

ALTER TABLE books
   isAvailable boolean default true;

More than 1 row in <Input type="textarea" />

Although <input> ignores the rows attribute, you can take advantage of the fact that <textarea> doesn't have to be inside <form> tags, but can still be a part of a form by referencing the form's id:

<form method="get" id="testformid">
    <input type="submit" />
</form> 
<textarea form ="testformid" name="taname" id="taid" cols="35" wrap="soft"></textarea>

Of course, <textarea> now appears below "submit" button, but maybe you'll find a way to reposition it.

'mat-form-field' is not a known element - Angular 5 & Material2

You're trying to use the MatFormFieldComponent in SearchComponent but you're not importing the MatFormFieldModule (which exports MatFormFieldComponent); you only export it.

Your MaterialModule needs to import it.

@NgModule({
  imports: [
    MatFormFieldModule,
  ],
  exports: [
    MatButtonModule,
    MatFormFieldModule,
    MatInputModule,
    MatRippleModule,
  ],
  declarations: [
    SearchComponent,
  ],
})
export class MaterialModule { }

Connect to SQL Server through PDO using SQL Server Driver

try
{

    $conn = new PDO("sqlsrv:Server=$server_name;Database=$db_name;ConnectionPooling=0", "", "");
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

}
catch(PDOException $e)
{

    $e->getMessage();

}

How to load all modules in a folder?

Add the __all__ Variable to __init__.py containing:

__all__ = ["bar", "spam", "eggs"]

See also http://docs.python.org/tutorial/modules.html

Not equal <> != operator on NULL

The only test for NULL is IS NULL or IS NOT NULL. Testing for equality is nonsensical because by definition one doesn't know what the value is.

Here is a wikipedia article to read:

https://en.wikipedia.org/wiki/Null_(SQL)

Pretty print in MongoDB shell as default

Give a try to Mongo-hacker(node module), it alway prints pretty. https://github.com/TylerBrock/mongo-hacker

More it enhances mongo shell (supports only ver>2.4, current ver is 3.0), like

  • Colorization
  • Additional shell commands (count documents/count docs/etc)
  • API Additions (db.collection.find({ ... }).last(), db.collection.find({ ... }).reverse(), etc)
  • Aggregation Framework

I am using for while in production env, no problems yet.

Meaning of "[: too many arguments" error from if [] (square brackets)

Another scenario that you can get the [: too many arguments or [: a: binary operator expected errors is if you try to test for all arguments "$@"

if [ -z "$@" ]
then
    echo "Argument required."
fi

It works correctly if you call foo.sh or foo.sh arg1. But if you pass multiple args like foo.sh arg1 arg2, you will get errors. This is because it's being expanded to [ -z arg1 arg2 ], which is not a valid syntax.

The correct way to check for existence of arguments is [ "$#" -eq 0 ]. ($# is the number of arguments).

Project has no default.properties file! Edit the project properties to set one

I got the default.properties error because the Android SDK wasn't installed on the machine I was using. What happened in my case was that I was setting up a second machine to development on.

After installing the SDK, the project imported just fine. You don't have to do New Project.

JavaScript - Use variable in string match

xxx.match(yyy, 'g').length

Algorithm to detect overlapping periods

I'm building a booking system and found this page. I'm interested in range intersection only, so I built this structure; it is enough to play with DateTime ranges.

You can check Intersection and check if a specific date is in range, and get the intersection type and the most important: you can get intersected Range.

public struct DateTimeRange
{

    #region Construction
    public DateTimeRange(DateTime start, DateTime end) {
        if (start>end) {
            throw new Exception("Invalid range edges.");
        }
        _Start = start;
        _End = end;
    }
    #endregion

    #region Properties
    private DateTime _Start;

    public DateTime Start {
        get { return _Start; }
        private set { _Start = value; }
    }
    private DateTime _End;

    public DateTime End {
        get { return _End; }
        private set { _End = value; }
    }
    #endregion

    #region Operators
    public static bool operator ==(DateTimeRange range1, DateTimeRange range2) {
        return range1.Equals(range2);
    }

    public static bool operator !=(DateTimeRange range1, DateTimeRange range2) {
        return !(range1 == range2);
    }
    public override bool Equals(object obj) {
        if (obj is DateTimeRange) {
            var range1 = this;
            var range2 = (DateTimeRange)obj;
            return range1.Start == range2.Start && range1.End == range2.End;
        }
        return base.Equals(obj);
    }
    public override int GetHashCode() {
        return base.GetHashCode();
    }
    #endregion

    #region Querying
    public bool Intersects(DateTimeRange range) {
        var type = GetIntersectionType(range);
        return type != IntersectionType.None;
    }
    public bool IsInRange(DateTime date) {
        return (date >= this.Start) && (date <= this.End);
    }
    public IntersectionType GetIntersectionType(DateTimeRange range) {
        if (this == range) {
            return IntersectionType.RangesEqauled;
        }
        else if (IsInRange(range.Start) && IsInRange(range.End)) {
            return IntersectionType.ContainedInRange;
        }
        else if (IsInRange(range.Start)) {
            return IntersectionType.StartsInRange;
        }
        else if (IsInRange(range.End)) {
            return IntersectionType.EndsInRange;
        }
        else if (range.IsInRange(this.Start) && range.IsInRange(this.End)) {
            return IntersectionType.ContainsRange;
        }
        return IntersectionType.None;
    }
    public DateTimeRange GetIntersection(DateTimeRange range) {
        var type = this.GetIntersectionType(range);
        if (type == IntersectionType.RangesEqauled || type==IntersectionType.ContainedInRange) {
            return range;
        }
        else if (type == IntersectionType.StartsInRange) {
            return new DateTimeRange(range.Start, this.End);
        }
        else if (type == IntersectionType.EndsInRange) {
            return new DateTimeRange(this.Start, range.End);
        }
        else if (type == IntersectionType.ContainsRange) {
            return this;
        }
        else {
            return default(DateTimeRange);
        }
    }
    #endregion


    public override string ToString() {
        return Start.ToString() + " - " + End.ToString();
    }
}
public enum IntersectionType
{
    /// <summary>
    /// No Intersection
    /// </summary>
    None = -1,
    /// <summary>
    /// Given range ends inside the range
    /// </summary>
    EndsInRange,
    /// <summary>
    /// Given range starts inside the range
    /// </summary>
    StartsInRange,
    /// <summary>
    /// Both ranges are equaled
    /// </summary>
    RangesEqauled,
    /// <summary>
    /// Given range contained in the range
    /// </summary>
    ContainedInRange,
    /// <summary>
    /// Given range contains the range
    /// </summary>
    ContainsRange,
}

Django - filtering on foreign key properties

student_user = User.objects.get(id=user_id)
available_subjects = Subject.objects.exclude(subject_grade__student__user=student_user) # My ans
enrolled_subjects = SubjectGrade.objects.filter(student__user=student_user)
context.update({'available_subjects': available_subjects, 'student_user': student_user, 
                'request':request, 'enrolled_subjects': enrolled_subjects})

In my application above, i assume that once a student is enrolled, a subject SubjectGrade instance will be created that contains the subject enrolled and the student himself/herself.

Subject and Student User model is a Foreign Key to the SubjectGrade Model.

In "available_subjects", i excluded all the subjects that are already enrolled by the current student_user by checking all subjectgrade instance that has "student" attribute as the current student_user

PS. Apologies in Advance if you can't still understand because of my explanation. This is the best explanation i Can Provide. Thank you so much

Difference in Months between two dates in JavaScript

Sometimes you may want to get just the quantity of the months between two dates totally ignoring the day part. So for instance, if you had two dates- 2013/06/21 and 2013/10/18- and you only cared about the 2013/06 and 2013/10 parts, here are the scenarios and possible solutions:

var date1=new Date(2013,5,21);//Remember, months are 0 based in JS
var date2=new Date(2013,9,18);
var year1=date1.getFullYear();
var year2=date2.getFullYear();
var month1=date1.getMonth();
var month2=date2.getMonth();
if(month1===0){ //Have to take into account
  month1++;
  month2++;
}
var numberOfMonths; 

1.If you want just the number of the months between the two dates excluding both month1 and month2

numberOfMonths = (year2 - year1) * 12 + (month2 - month1) - 1;

2.If you want to include either of the months

numberOfMonths = (year2 - year1) * 12 + (month2 - month1);

3.If you want to include both of the months

numberOfMonths = (year2 - year1) * 12 + (month2 - month1) + 1;

adding comment in .properties files

The property file task is for editing properties files. It contains all sorts of nice features that allow you to modify entries. For example:

<propertyfile file="build.properties">
    <entry key="build_number"
        type="int"
        operation="+"
        value="1"/>
</propertyfile>

I've incremented my build_number by one. I have no idea what the value was, but it's now one greater than what it was before.

  • Use the <echo> task to build a property file instead of <propertyfile>. You can easily layout the content and then use <propertyfile> to edit that content later on.

Example:

<echo file="build.properties">
# Default Configuration
source.dir=1
dir.publish=1
# Source Configuration
dir.publish.html=1
</echo>
  • Create separate properties files for each section. You're allowed a comment header for each type. Then, use to batch them together into one single file:

Example:

<propertyfile file="default.properties"
    comment="Default Configuration">
    <entry key="source.dir" value="1"/>
    <entry key="dir.publish" value="1"/>
<propertyfile>

<propertyfile file="source.properties"
    comment="Source Configuration">
    <entry key="dir.publish.html" value="1"/>
<propertyfile>
<concat destfile="build.properties">
    <fileset dir="${basedir}">
        <include name="default.properties"/>
        <include name="source.properties"/>
    </fileset>
</concat>

<delete>
    <fileset dir="${basedir}">
         <include name="default.properties"/>
        <include name="source.properties"/>
    </fileset>
</delete>      

Plot a horizontal line using matplotlib

You can use plt.grid to draw a horizontal line.

import numpy as np
from matplotlib import pyplot as plt
from scipy.interpolate import UnivariateSpline
from matplotlib.ticker import LinearLocator

# your data here
annual = np.arange(1,21,1)
l = np.random.random(20)
spl = UnivariateSpline(annual,l)
xs = np.linspace(1,21,200)

# plot your data
plt.plot(xs,spl(xs),'b')

# horizental line?
ax = plt.axes()
# three ticks:
ax.yaxis.set_major_locator(LinearLocator(3))
# plot grids only on y axis on major locations
plt.grid(True, which='major', axis='y')

# show
plt.show()

random data plot example

Crystal Reports 13 And Asp.Net 3.5

I have same problem. I solved install this setup. (I use vs 2015 (4.6))

How to set an iframe src attribute from a variable in AngularJS

You need also $sce.trustAsResourceUrl or it won't open the website inside the iframe:

_x000D_
_x000D_
angular.module('myApp', [])_x000D_
    .controller('dummy', ['$scope', '$sce', function ($scope, $sce) {_x000D_
_x000D_
    $scope.url = $sce.trustAsResourceUrl('https://www.angularjs.org');_x000D_
_x000D_
    $scope.changeIt = function () {_x000D_
        $scope.url = $sce.trustAsResourceUrl('https://docs.angularjs.org/tutorial');_x000D_
    }_x000D_
}]);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
_x000D_
<div ng-app="myApp" ng-controller="dummy">_x000D_
    <iframe ng-src="{{url}}" width="300" height="200"></iframe>_x000D_
    <br>_x000D_
    <button ng-click="changeIt()">Change it</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Retrieving the COM class factory for component with CLSID {XXXX} failed due to the following error: 80040154

I found that my problem related to the actual registration of the DLL.

  • First run "Regedit.exe" from a CMD prompt (I raised it's security level to Administrator, "just in case")
  • then search the Registry (by clicking on "Edit/Find" in the RegEdit menu or by pressing Ctrl+F) for the CLSID showing in the error message which you received regarding the COM class factory. My CLSID was 29AB7A12-B531-450E-8F7A-EA94C2F3C05F.
  • When this key is found, select the sub-key "InProcServer2" under that Hive node and ascertain the filename of the problem DLL in the right hand Regedit frame. showing under "Default".
  • If that file resides in "C:\Windows\SysWow64"(such as C:\Windows\SysWow64\Redemption.dll") then it is important that you use the "C:\Windows\SysWow64\RegSvr32.exe" file to register that DLL from the command line and NOT the default "C:\Windows\System32\RegSvr32.exe" file.
  • So I ran a CMD prompt (under Administrative level control (just in case this level is need required) and type on the command line (in the case of my DLL): C:\Windows\SysWow64\RegSvr32.exe c:\Windows\SysWow64\Redemption.dll the press enter.
  • Close the command window (via "Exit" then Restart your computer (always use restart instead of Close Down then start up, since (strangely) Restart perform a thorough shut down and reload of everything whereas "Shut Down" and Power-Up reloads a stored cache of drivers and other values (which may be faulty).
  • Whenever you register a DLL in the future, remember to use the SysWow64 "RegSvr32.exe" for any DLL stored in the C:\Windows\SysWow64 folder and this problem c(if it is caused by incorrect registration) should not happen again.

How to Initialize char array from a string

Simply

const char S[] = "ABCD";

should work.

What's your compiler?

How to run DOS/CMD/Command Prompt commands from VB.NET?

You Can try This To Run Command Then cmd Exits

Process.Start("cmd", "/c YourCode")

You Can try This To Run The Command And Let cmd Wait For More Commands

Process.Start("cmd", "/k YourCode")

Adding a user on .htpasswd

FWIW, htpasswd -n username will output the result directly to stdout, and avoid touching files altogether.

What is the difference between Task.Run() and Task.Factory.StartNew()

According to this post by Stephen Cleary, Task.Factory.StartNew() is dangerous:

I see a lot of code on blogs and in SO questions that use Task.Factory.StartNew to spin up work on a background thread. Stephen Toub has an excellent blog article that explains why Task.Run is better than Task.Factory.StartNew, but I think a lot of people just haven’t read it (or don’t understand it). So, I’ve taken the same arguments, added some more forceful language, and we’ll see how this goes. :) StartNew does offer many more options than Task.Run, but it is quite dangerous, as we’ll see. You should prefer Task.Run over Task.Factory.StartNew in async code.

Here are the actual reasons:

  1. Does not understand async delegates. This is actually the same as point 1 in the reasons why you would want to use StartNew. The problem is that when you pass an async delegate to StartNew, it’s natural to assume that the returned task represents that delegate. However, since StartNew does not understand async delegates, what that task actually represents is just the beginning of that delegate. This is one of the first pitfalls that coders encounter when using StartNew in async code.
  2. Confusing default scheduler. OK, trick question time: in the code below, what thread does the method “A” run on?
Task.Factory.StartNew(A);

private static void A() { }

Well, you know it’s a trick question, eh? If you answered “a thread pool thread”, I’m sorry, but that’s not correct. “A” will run on whatever TaskScheduler is currently executing!

So that means it could potentially run on the UI thread if an operation completes and it marshals back to the UI thread due to a continuation as Stephen Cleary explains more fully in his post.

In my case, I was trying to run tasks in the background when loading a datagrid for a view while also displaying a busy animation. The busy animation didn't display when using Task.Factory.StartNew() but the animation displayed properly when I switched to Task.Run().

For details, please see https://blog.stephencleary.com/2013/08/startnew-is-dangerous.html

phpMyAdmin - can't connect - invalid setings - ever since I added a root password - locked out

Go inside your phpMyAdmin directory inside XAMPP installation folder. There will be a file called config.inc.php. Inside that file, find this line:

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

you must make sure that this field has your mysql root password (the one that you set).

Meaning of "487 Request Terminated"

It's the response code a SIP User Agent Server (UAS) will send to the client after the client sends a CANCEL request for the original unanswered INVITE request (yet to receive a final response).

Here is a nice CANCEL SIP Call Flow illustration.

What is 'Context' on Android?

Context means Android get to know in which activity I should go for or act in.

1 - Toast.makeText(context, "Enter All Details", Toast.LENGTH_SHORT).show(); it used in this. Context context = ActivityName.this;

2 -startActivity(new Intent(context,LoginActivity.class));

in this context means from which activity you wanna go to other activity. context or ActivityName.this is faster then , getContext and getApplicatinContext.

PHPmailer sending HTML CODE

do like this-paste your html code inside your separate html file using GET method.

$mail->IsHTML(true);                                 
    $mail->WordWrap = 70;                                 
    $mail->addAttachment= $_GET['addattachment']; $mail->AltBody   
    =$_GET['AltBody'];  $mail->Subject = $_GET['subject']; $mail->Body = $_GET['body'];

count distinct values in spreadsheet

=UNIQUE({filter(Core!L8:L27,isblank(Core!L8:L27)=false),query(ArrayFormula(countif(Core!L8:L27,Core!L8:L27)),"select Col1 where Col1 <> 0")})

Core!L8:L27 = list

Extract substring using regexp in plain bash

Using pure :

$ cat file.txt
US/Central - 10:26 PM (CST)
$ while read a b time x; do [[ $b == - ]] && echo $time; done < file.txt

another solution with bash regex :

$ [[ "US/Central - 10:26 PM (CST)" =~ -[[:space:]]*([0-9]{2}:[0-9]{2}) ]] &&
    echo ${BASH_REMATCH[1]}

another solution using grep and look-around advanced regex :

$ echo "US/Central - 10:26 PM (CST)" | grep -oP "\-\s+\K\d{2}:\d{2}"

another solution using sed :

$ echo "US/Central - 10:26 PM (CST)" |
    sed 's/.*\- *\([0-9]\{2\}:[0-9]\{2\}\).*/\1/'

another solution using perl :

$ echo "US/Central - 10:26 PM (CST)" |
    perl -lne 'print $& if /\-\s+\K\d{2}:\d{2}/'

and last one using awk :

$ echo "US/Central - 10:26 PM (CST)" |
    awk '{for (i=0; i<=NF; i++){if ($i == "-"){print $(i+1);exit}}}'

How to add composite primary key to table

You don't need to create the table first and then add the keys in subsequent steps. You can add both primary key and foreign key while creating the table:

This example assumes the existence of a table (Codes) that we would want to reference with our foreign key.

CREATE TABLE d (
id [numeric](1),
code [varchar](2),
PRIMARY KEY (id, code),
CONSTRAINT fk_d_codes FOREIGN KEY (code) REFERENCES Codes (code)
)

If you don't have a table that we can reference, add one like this so that the example will work:

CREATE TABLE Codes (
    Code [varchar](2) PRIMARY KEY   
    )

NOTE: you must have a table to reference before creating the foreign key.

What is the difference between the dot (.) operator and -> in C++?

The . (dot) operator is usually used to get a field / call a method from an instance of class (or a static field / method of a class).

p.myField, p.myMethod() - p instance of a class

The -> (arrow) operator is used to get a field / call a method from the content pointed by the class.

p->myField, p->myMethod() - p points to a class

Django: How can I call a view function from template?

For deleting all data:

HTML FILE

  class="btn btn-primary" href="{% url 'delete_product'%}">Delete

Put the above code in an anchor tag. (the a tag!)

url.py

path('delete_product', views.delete_product, name='delete_product')]

views.py

def delete_product(request):
    if request.method == "GET":
        dest = Racket.objects.all()
        dest.delete()
        return render(request, "admin_page.html")

Get age from Birthdate

Try this function...

function calculate_age(birth_month,birth_day,birth_year)
{
    today_date = new Date();
    today_year = today_date.getFullYear();
    today_month = today_date.getMonth();
    today_day = today_date.getDate();
    age = today_year - birth_year;

    if ( today_month < (birth_month - 1))
    {
        age--;
    }
    if (((birth_month - 1) == today_month) && (today_day < birth_day))
    {
        age--;
    }
    return age;
}

OR

function getAge(dateString) 
{
    var today = new Date();
    var birthDate = new Date(dateString);
    var age = today.getFullYear() - birthDate.getFullYear();
    var m = today.getMonth() - birthDate.getMonth();
    if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) 
    {
        age--;
    }
    return age;
}

See Demo.

Retrieving Property name from lambda expression

Well, there's no need to call .Name.ToString(), but broadly that is about it, yes. The only consideration you might need is whether x.Foo.Bar should return "Foo", "Bar", or an exception - i.e. do you need to iterate at all.

(re comment) for more on flexible sorting, see here.

PHP PDO with foreach and fetch

A PDOStatement (which you have in $users) is a forward-cursor. That means, once consumed (the first foreach iteration), it won't rewind to the beginning of the resultset.

You can close the cursor after the foreach and execute the statement again:

$users       = $dbh->query($sql);
foreach ($users as $row) {
    print $row["name"] . "-" . $row["sex"] ."<br/>";
}

$users->execute();

foreach ($users as $row) {
    print $row["name"] . "-" . $row["sex"] ."<br/>";
}

Or you could cache using tailored CachingIterator with a fullcache:

$users       = $dbh->query($sql);

$usersCached = new CachedPDOStatement($users);

foreach ($usersCached as $row) {
    print $row["name"] . "-" . $row["sex"] ."<br/>";
}
foreach ($usersCached as $row) {
    print $row["name"] . "-" . $row["sex"] ."<br/>";
}

You find the CachedPDOStatement class as a gist. The caching itertor is probably more sane than storing the resultset into an array because it still offers all properties and methods of the PDOStatement object it has wrapped.

Java Array Sort descending?

without explicit comparator:

Collections.sort(list, Collections.reverseOrder());

with explicit comparator:

Collections.sort(list, Collections.reverseOrder(new Comparator()));

How do you run a SQL Server query from PowerShell?

For others who need to do this with just stock .NET and PowerShell (no additional SQL tools installed) here is the function that I use:

function Invoke-SQL {
    param(
        [string] $dataSource = ".\SQLEXPRESS",
        [string] $database = "MasterData",
        [string] $sqlCommand = $(throw "Please specify a query.")
      )

    $connectionString = "Data Source=$dataSource; " +
            "Integrated Security=SSPI; " +
            "Initial Catalog=$database"

    $connection = new-object system.data.SqlClient.SQLConnection($connectionString)
    $command = new-object system.data.sqlclient.sqlcommand($sqlCommand,$connection)
    $connection.Open()
    
    $adapter = New-Object System.Data.sqlclient.sqlDataAdapter $command
    $dataset = New-Object System.Data.DataSet
    $adapter.Fill($dataSet) | Out-Null
    
    $connection.Close()
    $dataSet.Tables

}

I have been using this so long I don't know who wrote which parts. This was distilled from others' examples, but simplified to be clear and just what is needed without extra dependencies or features.

I use and share this often enough that I have turned this into a script module on GitHub so that you can now go to your modules directory and execute git clone https://github.com/ChrisMagnuson/InvokeSQL and from that point forward invoke-sql will automatically be loaded when you go to use it (assuming your using PowerShell v3 or later).

How to close a GUI when I push a JButton?

JButton close = new JButton("Close");
close.addActionListener(this);
public void actionPerformed(ActionEvent closing) { 
// getSource() checks for the source of clicked Button , compares with the name of button in which here is close .     
if(closing.getSource()==close)
   System.exit(0);
   // This exit Your GUI 
}
/*Some Answers were asking for @override which is overriding the method the super class or the parent class and creating different objects and etc which makes the answer too long . Note : we just need to import java.awt.*; and java.swing.*; and Adding this command : class className implements actionListener{} */

VBScript: Using WScript.Shell to Execute a Command Line Program That Accesses Active Directory

Taking Shiraz's idea and running with it...

In your application, are you explicitly defining a domain User Account and Password to access AD?

When you are executing the application explicitly it may be inherently using your credentials (your currently logged in domain account) to interrogate AD. However, when calling the application from the script, I'm not sure if the application is in the System context.

A VBScript example would be as follows:

  Dim objConnection As ADODB.Connection
    Set objConnection = CreateObject("ADODB.Connection")
    objConnection.Provider = "ADsDSOObject"
    objConnection.Properties("User ID") = "MyDomain\MyAccount"
    objConnection.Properties("Password") = "MyPassword"
    objConnection.Open "Active Directory Provider"

If this works, of course it would be best practice to create and use a service account specifically for this task, and to deny interactive login to that account.

How to check if keras tensorflow backend is GPU or CPU version?

According to the documentation.

If you are running on the TensorFlow or CNTK backends, your code will automatically run on GPU if any available GPU is detected.

You can check what all devices are used by tensorflow by -

from tensorflow.python.client import device_lib
print(device_lib.list_local_devices())

Also as suggested in this answer

import tensorflow as tf
sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))

This will print whether your tensorflow is using a CPU or a GPU backend. If you are running this command in jupyter notebook, check out the console from where you have launched the notebook.

If you are sceptic whether you have installed the tensorflow gpu version or not. You can install the gpu version via pip.

pip install tensorflow-gpu

How to use Collections.sort() in Java?

Sort the unsorted hashmap in ascending order.

// Sorting the list based on values
Collections.sort(list, new Comparator<Entry<String, Integer>>() {
public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) 
{
                return o2.getValue().compareTo(o1.getValue());
        }
    });

    // Maintaining insertion order with the help of LinkedList
    Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
    for (Entry<String, Integer> entry : list) {
        sortedMap.put(entry.getKey(), entry.getValue());
    }

How to count items in JSON object using command line?

Just throwing another solution in the mix...

Try jq, a lightweight and flexible command-line JSON processor:

jq length /tmp/test.json

Prints the length of the array of objects.

Getting path of captured image in Android using camera intent

Try this method to get path of original image captured by camera.

public String getOriginalImagePath() {
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = getActivity().managedQuery(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                projection, null, null, null);
        int column_index_data = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToLast();

        return cursor.getString(column_index_data);
    }

This method will return path of the last image captured by camera. So this path would be of original image not of thumbnail bitmap.

How to parse JSON and access results

The main problem with your example code is that the $result variable you use to store the output of curl_exec() does not contain the body of the HTTP response - it contains the value true. If you try to print_r() that, it will just say "1".

The curl_exec() reference explains:

Return Values

Returns TRUE on success or FALSE on failure. However, if the CURLOPT_RETURNTRANSFER option is set, it will return the result on success, FALSE on failure.

So if you want to get the HTTP response body in your $result variable, you must first run

curl_setopt($cURL, CURLOPT_RETURNTRANSFER, true);

After that, you can call json_decode() on $result, as other answers have noted.

On a general note - the curl library for PHP is useful and has a lot of features to handle the minutia of HTTP protocol (and others), but if all you want is to GET some resource or even POST to some URL, and read the response - then file_get_contents() is all you'll ever need: it is much simpler to use and have much less surprising behavior to worry about.

How can I display the users profile pic using the facebook graph api?

I was having a problem fetching profile photos while using CURL. I thought for a while there was something wrong my implementation of the Facebook API, but I need to add a bit to my CURL called:

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

How to add element in List while iterating in java?

You could iterate on a copy (clone) of your original list:

List<String> copy = new ArrayList<String>(list);
for (String s : copy) {
    // And if you have to add an element to the list, add it to the original one:
    list.add("some element");
}

Note that it is not even possible to add a new element to a list while iterating on it, because it will result in a ConcurrentModificationException.

Counting inversions in an array

Here's my O(n log n) solution in Ruby:

def solution(t)
    sorted, inversion_count = sort_inversion_count(t)
    return inversion_count
end

def sort_inversion_count(t)
    midpoint = t.length / 2
    left_half = t[0...midpoint]
    right_half = t[midpoint..t.length]

    if midpoint == 0
        return t, 0
    end

    sorted_left_half, left_half_inversion_count = sort_inversion_count(left_half)
    sorted_right_half, right_half_inversion_count = sort_inversion_count(right_half)

    sorted = []
    inversion_count = 0
    while sorted_left_half.length > 0 or sorted_right_half.length > 0
        if sorted_left_half.empty?
            sorted.push sorted_right_half.shift
        elsif sorted_right_half.empty?
            sorted.push sorted_left_half.shift
        else
            if sorted_left_half[0] > sorted_right_half[0]
                inversion_count += sorted_left_half.length
                sorted.push sorted_right_half.shift
            else
                sorted.push sorted_left_half.shift
            end
        end
    end

    return sorted, inversion_count + left_half_inversion_count + right_half_inversion_count
end

And some test cases:

require "minitest/autorun"

class TestCodility < Minitest::Test
    def test_given_example
        a = [-1, 6, 3, 4, 7, 4]
        assert_equal solution(a), 4
    end

    def test_empty
        a = []
        assert_equal solution(a), 0
    end

    def test_singleton
        a = [0]
        assert_equal solution(a), 0
    end

    def test_none
        a = [1,2,3,4,5,6,7]
        assert_equal solution(a), 0
    end

    def test_all
        a = [5,4,3,2,1]
        assert_equal solution(a), 10
    end

    def test_clones
        a = [4,4,4,4,4,4]
        assert_equal solution(a), 0
    end
end