Programs & Examples On #Sequence points

Undefined behavior and sequence points

C++98 and C++03

This answer is for the older versions of the C++ standard. The C++11 and C++14 versions of the standard do not formally contain 'sequence points'; operations are 'sequenced before' or 'unsequenced' or 'indeterminately sequenced' instead. The net effect is essentially the same, but the terminology is different.

Disclaimer : Okay. This answer is a bit long. So have patience while reading it. If you already know these things, reading them again won't make you crazy.

Pre-requisites : An elementary knowledge of C++ Standard

What are Sequence Points?

The Standard says

At certain specified points in the execution sequence called sequence points, all side effects of previous evaluations shall be complete and no side effects of subsequent evaluations shall have taken place. (§1.9/7)

Side effects? What are side effects?

Evaluation of an expression produces something and if in addition there is a change in the state of the execution environment it is said that the expression (its evaluation) has some side effect(s).

For example:

int x = y++; //where y is also an int

In addition to the initialization operation the value of y gets changed due to the side effect of ++ operator.

So far so good. Moving on to sequence points. An alternation definition of seq-points given by the comp.lang.c author Steve Summit:

Sequence point is a point in time at which the dust has settled and all side effects which have been seen so far are guaranteed to be complete.

What are the common sequence points listed in the C++ Standard ?

Those are:

  • at the end of the evaluation of full expression (§1.9/16) (A full-expression is an expression that is not a subexpression of another expression.)1

    Example :

    int a = 5; // ; is a sequence point here
  • in the evaluation of each of the following expressions after the evaluation of the first expression (§1.9/18) 2

    • a && b (§5.14)
    • a || b (§5.15)
    • a ? b : c (§5.16)
    • a , b (§5.18) (here a , b is a comma operator; in func(a,a++) , is not a comma operator, it's merely a separator between the arguments a and a++. Thus the behaviour is undefined in that case (if a is considered to be a primitive type))
  • at a function call (whether or not the function is inline), after the evaluation of all function arguments (if any) which takes place before execution of any expressions or statements in the function body (§1.9/17).

1 : Note : the evaluation of a full-expression can include the evaluation of subexpressions that are not lexically part of the full-expression. For example, subexpressions involved in evaluating default argument expressions (8.3.6) are considered to be created in the expression that calls the function, not the expression that defines the default argument

2 : The operators indicated are the built-in operators, as described in clause 5. When one of these operators is overloaded (clause 13) in a valid context, thus designating a user-defined operator function, the expression designates a function invocation and the operands form an argument list, without an implied sequence point between them.

What is Undefined Behaviour?

The Standard defines Undefined Behaviour in Section §1.3.12 as

behavior, such as might arise upon use of an erroneous program construct or erroneous data, for which this International Standard imposes no requirements 3.

Undefined behavior may also be expected when this International Standard omits the description of any explicit definition of behavior.

3 : permissible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment (with or with- out the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message).

In short, undefined behaviour means anything can happen from daemons flying out of your nose to your girlfriend getting pregnant.

What is the relation between Undefined Behaviour and Sequence Points?

Before I get into that you must know the difference(s) between Undefined Behaviour, Unspecified Behaviour and Implementation Defined Behaviour.

You must also know that the order of evaluation of operands of individual operators and subexpressions of individual expressions, and the order in which side effects take place, is unspecified.

For example:

int x = 5, y = 6;

int z = x++ + y++; //it is unspecified whether x++ or y++ will be evaluated first.

Another example here.

Now the Standard in §5/4 says

  • 1) Between the previous and next sequence point a scalar object shall have its stored value modified at most once by the evaluation of an expression.

What does it mean?

Informally it means that between two sequence points a variable must not be modified more than once. In an expression statement, the next sequence point is usually at the terminating semicolon, and the previous sequence point is at the end of the previous statement. An expression may also contain intermediate sequence points.

From the above sentence the following expressions invoke Undefined Behaviour:

i++ * ++i;   // UB, i is modified more than once btw two SPs
i = ++i;     // UB, same as above
++i = 2;     // UB, same as above
i = ++i + 1; // UB, same as above
++++++i;     // UB, parsed as (++(++(++i)))

i = (i, ++i, ++i); // UB, there's no SP between `++i` (right most) and assignment to `i` (`i` is modified more than once btw two SPs)

But the following expressions are fine:

i = (i, ++i, 1) + 1; // well defined (AFAIK)
i = (++i, i++, i);   // well defined 
int j = i;
j = (++i, i++, j*i); // well defined

  • 2) Furthermore, the prior value shall be accessed only to determine the value to be stored.

What does it mean? It means if an object is written to within a full expression, any and all accesses to it within the same expression must be directly involved in the computation of the value to be written.

For example in i = i + 1 all the access of i (in L.H.S and in R.H.S) are directly involved in computation of the value to be written. So it is fine.

This rule effectively constrains legal expressions to those in which the accesses demonstrably precede the modification.

Example 1:

std::printf("%d %d", i,++i); // invokes Undefined Behaviour because of Rule no 2

Example 2:

a[i] = i++ // or a[++i] = i or a[i++] = ++i etc

is disallowed because one of the accesses of i (the one in a[i]) has nothing to do with the value which ends up being stored in i (which happens over in i++), and so there's no good way to define--either for our understanding or the compiler's--whether the access should take place before or after the incremented value is stored. So the behaviour is undefined.

Example 3 :

int x = i + i++ ;// Similar to above

Follow up answer for C++11 here.

Is Python faster and lighter than C++?

I think you're reading those stats incorrectly. They show that Python is up to about 400 times slower than C++ and with the exception of a single case, Python is more of a memory hog. When it comes to source size though, Python wins flat out.

My experiences with Python show the same definite trend that Python is on the order of between 10 and 100 times slower than C++ when doing any serious number crunching. There are many reasons for this, the major ones being: a) Python is interpreted, while C++ is compiled; b) Python has no primitives, everything including the builtin types (int, float, etc.) are objects; c) a Python list can hold objects of different type, so each entry has to store additional data about its type. These all severely hinder both runtime and memory consumption.

This is no reason to ignore Python though. A lot of software doesn't require much time or memory even with the 100 time slowness factor. Development cost is where Python wins with the simple and concise style. This improvement on development cost often outweighs the cost of additional cpu and memory resources. When it doesn't, however, then C++ wins.

How can I get current location from user in iOS

iOS 11.x Swift 4.0 Info.plist needs these two properties

<string>We're watching you</string>
<string>Watch Out</string>

And this code ... making sure of course your a CLLocationManagerDelegate

let locationManager = CLLocationManager()

// MARK location Manager delegate code + more

func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
    switch status {
    case .notDetermined:
        print("User still thinking")
    case .denied:
        print("User hates you")
    case .authorizedWhenInUse:
    case .authorizedAlways:
    case .restricted:
        print("User dislikes you")

And of course this code too which you can put in viewDidLoad().

locationManager.delegate = self
locationManager.distanceFilter = kCLDistanceFilterNone
locationManager.desiredAccuracy = kCLLocationAccuracyBest

And these two for the requestLocation to get you going, aka save you having to get out of your seat :)

func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

Should Jquery code go in header or footer?

Standard practice is to put all of your scripts at the bottom of the page, but I use ASP.NET MVC with a number of jQuery plugins, and I find that it all works better if I put my jQuery scripts in the <head> section of the master page.

In my case, there are artifacts that occur when the page is loaded, if the scripts are at the bottom of the page. I'm using the jQuery TreeView plugin, and if the scripts are not loaded at the beginning, the tree will render without the necessary CSS classes imposed on it by the plugin. So you get this funny-looking mess when the page first loads, followed by the proper rendering of the TreeView. Very bad looking. Putting the jQuery plugins in the <head> section of the master page eliminates this problem.

How do I perform a JAVA callback between classes?

IMO, you should have a look at the Observer Pattern, and this is how most of the listeners work

jQuery plugin returning "Cannot read property of undefined"

I had same problem with 'parallax' plugin. I changed jQuery librery version to *jquery-1.6.4* from *jquery-1.10.2*. And error cleared.

static function in C

pmg is spot on about encapsulation; beyond hiding the function from other translation units (or rather, because of it), making functions static can also confer performance benefits in the presence of compiler optimizations.

Because a static function cannot be called from anywhere outside of the current translation unit (unless the code takes a pointer to its address), the compiler controls all the call points into it.

This means that it is free to use a non-standard ABI, inline it entirely, or perform any number of other optimizations that might not be possible for a function with external linkage.

How to convert a String to a Date using SimpleDateFormat?

    DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("MM/dd/uuuu");
    System.out.println(LocalDate.parse("08/16/2011", dateFormatter));



I am contributing the modern answer. The answer by Bohemian is correct and was a good answer when it was written 6 years ago. Now the notoriously troublesome SimpleDateFormat class is long outdated and we have so much better in java.time, the modern Java date and time API. I warmly recommend you use this instead of the old date-time classes.

What went wrong in your code?

When I parse 08/16/2011 using your snippet, I get Sun Jan 16 00:08:00 CET 2011. Since lowercase mm is for minutes, I get 00:08:00 (8 minutes past midnight), and since uppercase DD is for day of year, I get 16 January.

In java.time too format pattern strings are case sensitive, and we needed to use uppercase MM for month and lowercase dd for day of month.

Question: Can I use java.time with my Java version?

Yes, java.time works nicely on Java 6 and later and on both older and newer Android devices.

  • In Java 8 and later and on new Android devices (from API level 26, I’m told) the modern API comes built-in.
  • In Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310; see the links at the bottom).
  • On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.


"Cannot start compilation: the output path is not specified for module..."

You have to define a path in the "Project compiler output" field in

File > Project Structure... > Project > Project compiler output

This path will be used to store all project compilation results.

How to clear all input fields in a specific div with jQuery?


You can do it like so:

I have added two buttons in the Fiddle to illustrate how you can insert or clear values in those input fields through buttons. You just capture the onClick event and call the function.

//Fires when the Document Loads, clears all input fields
$(document).ready(function() {

//Custom Functions that you can call
function resetAllValues() {

function addSomeValues() {


Check out this great answer below by Beena as well for a more universal approach.

Unable to run Java GUI programs with Ubuntu

Check what your environment variable DISPLAY's value is. Try running a simple X application from the command line. If it works, check DISPLAY's value for the right value.

You can experiment with different values of and environment variable on a per invocation basis by doing the following on the command line:

DISPLAY=:0.0 <your-java-executable-here>

How are you calling your program?

How to word wrap text in HTML?

In HTML body try:

            <div style="word-wrap: break-word; width: 800px">
                Hello world, how are you? More text here to see if it wraps after a long while of writing and it does on Firefox but I have not tested it on Chrome yet. It also works wonders if you have a medium to long paragraph. Just avoid writing in the CSS file that the words have to break-all, that's a small tip.

In CSS body try:

background-size: auto;

table-layout: fixed;

Run PHP function on html button click

Use an AJAX Request on your PHP file, then display the result on your page, without any reloading. This is a simple solution if you don't need any POST data.

Creating a JSON array in C#

You're close. This should do the trick:

new {items = new [] {
    new {name = "command" , index = "X", optional = "0"}, 
    new {name = "command" , index = "X", optional = "0"}

If your source was an enumerable of some sort, you might want to do this:

new {items = source.Select(item => new 
    name = item.Name, index = item.Index, options = item.Optional

How to grep for two words existing on the same line?

you could use awk. like this...

cat <yourFile> | awk '/word1/ && /word2/'

Order is not important. So if you have a file and...

a file named , file1 contains:

word1 is in this file as well as word2
word2 is in this file as well as word1
word4 is in this file as well as word1
word5 is in this file as well as word2


/tmp$ cat file1| awk '/word1/ && /word2/'

will result in,

word1 is in this file as well as word2
word2 is in this file as well as word1

yes, awk is slower.

Bloomberg Open API

The API's will provide full access to LIVE data, and developers can thus provide applications and develop against the API without paying licencing fees. Consumers will pay for any data received from the apps provided by third party developers, and so BB will grow their audience and revenue in that way.

NOTE: Bloomberg is offering this programming interface (BLPAPI) under a free-use license. This license does not include nor provide access to any Bloomberg data or content.


Java - How to access an ArrayList of another class?

import java.util.ArrayList;
public class numbers {
   private int number1 = 50;
   private int number2 = 100;
   private List<Integer> list;

   public numbers() {
       list = new ArrayList<Integer>();

   public List<Integer> getList() {
       return list;

And the test class:

import java.util.ArrayList;
public class test {
   private numbers number;

   public test() {
     number = new numbers();
     List<Integer> list = number.getList();
     //hurray !

document.getElementById().value doesn't set the value

Your response is almost certainly a string. You need to make sure it gets converted to a number:

document.getElementById("points").value= new Number(request.responseText);

You might take a closer look at your responseText. It sound like you are getting a string that contains quotes. If you are getting JSON data via AJAX, you might have more consistent results running it through JSON.parse().

document.getElementById("points").value= new Number(JSON.parse(request.responseText));

add to array if it isn't there already

if (!in_array($value, $a))

Shell - How to find directory of some command?

An alternative to type -a is command -V

Since most of the times I am interested in the first result only, I also pipe from head. This way the screen will not flood with code in case of a bash function.

command -V lshw | head -n1

How to use Simple Ajax Beginform in MVC 4?

All This Work :)


  public partial class ClientMessage
        public int IdCon { get; set; } 
        public string Name { get; set; }
        public string Email { get; set; }  


   public class TestAjaxBeginFormController : Controller{  

 projectNameEntities db = new projectNameEntities();

        public ActionResult Index(){  
            return View();

        public ActionResult GetClientMessages(ClientMessage Vm) {
            var model = db.ClientMessages.Where(x => x.Name.Contains(Vm.Name));
            return PartialView("_PartialView", model);

View index.cshtml

@model  projectName.Models.ClientMessage 
    Layout = null;

<script src="~/Scripts/jquery-1.9.1.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
    //\\\\\\\ JS  retrun message SucccessPost or FailPost
    function SuccessMessage() {
        alert("Succcess Post");
    function FailMessage() {
        alert("Fail Post");

<h1>Page Index</h1> 

@using (Ajax.BeginForm("GetClientMessages", "TestAjaxBeginForm", null , new AjaxOptions
    HttpMethod = "POST",
    OnSuccess = "SuccessMessage",
    OnFailure = "FailMessage" ,
    UpdateTargetId = "resultTarget"  
}, new { id = "MyNewNameId" })) // set new Id name for  Form

    @Html.EditorFor(x => x.Name) 
     <input type="submit" value="Search" /> 


<div id="resultTarget">  </div>

View _PartialView.cshtml

@model  IEnumerable<projectName.Models.ClientMessage >

@foreach (var item in Model) { 

        <td>@Html.DisplayFor(modelItem => item.IdCon)</td>
        <td>@Html.DisplayFor(modelItem => item.Name)</td>
        <td>@Html.DisplayFor(modelItem => item.Email)</td>



Parse JSON String into List<string>

Wanted to post this as a comment as a side note to the accepted answer, but that got a bit unclear. So purely as a side note:

If you have no need for the objects themselves and you want to have your project clear of further unused classes, you can parse with something like:

var list = JObject.Parse(json)["People"].Select(el => new { FirstName = (string)el["FirstName"], LastName = (string)el["LastName"] }).ToList();

var firstNames = list.Select(p => p.FirstName).ToList();
var lastNames = list.Select(p => p.LastName).ToList();

Even when using a strongly typed person class, you can still skip the root object by creating a list with JObject.Parse(json)["People"].ToObject<List<Person>>() Of course, if you do need to reuse the objects, it's better to create them from the start. Just wanted to point out the alternative ;)

Django: Get list of model fields?

Why not just use that: inspectdb

Example output:

class GuardianUserobjectpermission(models.Model):
    id = models.IntegerField(primary_key=True)  # AutoField?
    object_pk = models.CharField(max_length=255)
    content_type = models.ForeignKey(DjangoContentType, models.DO_NOTHING)
    permission = models.ForeignKey(AuthPermission, models.DO_NOTHING)
    user = models.ForeignKey(CustomUsers, models.DO_NOTHING)

    class Meta:
        managed = False
        db_table = 'guardian_userobjectpermission'
        unique_together = (('user', 'permission', 'object_pk'),)

Get class name using jQuery

To complete Whitestock answer (which is the best I found) I did :

className = $(this).attr('class').match(/[\d\w-_]+/g);
className = '.' + className.join(' .');

So for " myclass1 myclass2 " the result will be '.myclass1 .myclass2'

No String-argument constructor/factory method to deserialize from String value ('')

Try setting mapper.configure(DeserializationConfig.Feature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true)



depending on your Jackson version.

Insert 2 million rows into SQL Server quickly

I ran into this scenario recently (well over 7 million rows) and eneded up using sqlcmd via powershell (after parsing raw data into SQL insert statements) in segments of 5,000 at a time (SQL can't handle 7 million lines in one lump job or even 500,000 lines for that matter unless its broken down into smaller 5K pieces. You can then run each 5K script one after the other.) as I needed to leverage the new sequence command in SQL Server 2012 Enterprise. I couldn't find a programatic way to insert seven million rows of data quickly and efficiently with said sequence command.

Secondly, one of the things to look out for when inserting a million rows or more of data in one sitting is the CPU and memory consumption (mostly memory) during the insert process. SQL will eat up memory/CPU with a job of this magnitude without releasing said processes. Needless to say if you don't have enough processing power or memory on your server you can crash it pretty easily in a short time (which I found out the hard way). If you get to the point to where your memory consumption is over 70-75% just reboot the server and the processes will be released back to normal.

I had to run a bunch of trial and error tests to see what the limits for my server was (given the limited CPU/Memory resources to work with) before I could actually have a final execution plan. I would suggest you do the same in a test environment before rolling this out into production.

error: Libtool library used but 'LIBTOOL' is undefined

Fixed it. I needed to run libtoolize in the directory, then re-run:

  • aclocal

  • autoheader

How to store standard error in a variable

There are a lot of duplicates for this question, many of which have a slightly simpler usage scenario where you don't want to capture stderr and stdout and the exit code all at the same time.

if result=$( 2>&1); then

works for the common scenario where you expect either proper output in the case of success, or a diagnostic message on stderr in the case of failure.

Note that the shell's control statements already examine $? under the hood; so anything which looks like

if [ $? -eq 0 ], then ...

is just a clumsy, unidiomatic way of saying

if cmd; then ...

Java - Convert image to Base64

Late GraveDig ... Just constrain your byte array to the file size.

FileInputStream fis = new FileInputStream( file );
byte[] byteArray= new byte[(int) file.length()];

How to initialize static variables

Instead of finding a way to get static variables working, I prefer to simply create a getter function. Also helpful if you need arrays belonging to a specific class, and a lot simpler to implement.

class MyClass
   public static function getTypeList()
       return array(
           "type_a"=>"Type A",
           "type_b"=>"Type B",
           //... etc.

Wherever you need the list, simply call the getter method. For example:

if (array_key_exists($type, MyClass::getTypeList()) {
     // do something important...

WAMP won't turn green. And the VCRUNTIME140.dll error

VCRUNTIME140.dll error

This error means you don't have required Visual C++ packages installed in your computer. If you have installed wampserver then firstly uninstall wampserver.

Download the VC packages

Download all these VC packages and install all of them. You should install both 64 bit and 32 bit version.

-- VC9 Packages (Visual C++ 2008 SP1)--

-- VC10 Packages (Visual C++ 2010 SP1)--

-- VC11 Packages (Visual C++ 2012 Update 4)--
The two files VSU4\vcredist_x86.exe and VSU4\vcredist_x64.exe to be download are on the same page

-- VC13 Packages] (Visual C++ 2013)--
The two files VSU4\vcredist_x86.exe and VSU4\vcredist_x64.exe to be download are on the same page

-- VC14 Packages (Visual C++ 2015)--
The two files vcredist_x86.exe and vcredist_x64.exe to be download are on the same page

install packages with admin priviliges
Right click->Run as Administrator

install wampserver again
After you installed both 64bits and 32 bits version of VC packages then install wampserver again.

cancelling a handler.postdelayed process

In case you do have multiple inner/anonymous runnables passed to same handler, and you want to cancel all at same event use


As per documentation,

Remove any pending posts of callbacks and sent messages whose obj is token. If token is null, all callbacks and messages will be removed.

git clone through ssh

Easy way to do this issue
try this.

Step 1:

ls -al ~/.ssh

enter image description here

Step 2:


(using enter key for default value) enter image description here Step 3: To setup config file

vim /c/Users/Willie/.ssh/config

User git
IdentityFile ~/.ssh/id_rsa

Step 4:

git clone [email protected]:<username>/test2.git

enter image description here

Step 5:
When you finished Step 4
1.the test2.git file will be download done will get the new file(known_hosts) in the ~/.ssh
enter image description here

PS: I create the id_rsa and id_rsa.ub by meself and I deliver it to the Gitlab server. using both keys to any client-sides(windows and Linux).

How to refresh table contents in div using jquery/ajax

You can load HTML page partial, in your case is everything inside div#mytable.

   $( "#mytable" ).load( "your-current-page.html #mytable" );
}, 2000); //refresh every 2 seconds

more information read this

Update Code (if you don't want it auto-refresh)

<button id="refresh-btn">Refresh Table</button>

$(document).ready(function() {

   function RefreshTable() {
       $( "#mytable" ).load( "your-current-page.html #mytable" );

   $("#refresh-btn").on("click", RefreshTable);

   // $("#refresh-btn").on("click", function() {
   //    $( "#mytable" ).load( "your-current-page.html #mytable" );
   // });


How do I create a chart with multiple series using different X values for each series?

You need to use the Scatter chart type instead of Line. That will allow you to define separate X values for each series.

Get UserDetails object from Security Context in Spring MVC controller

Let Spring 3 injection take care of this.

Thanks to tsunade21 the easiest way is:

 @RequestMapping(method = RequestMethod.GET)   
 public ModelAndView anyMethodNameGoesHere(Principal principal) {
        final String loggedInUserName = principal.getName();


How to style UITextview to like Rounded Rect text field?

I don't think that it is possible. but you can do UITableView(grouped) with 1 section and 1 empty cell and use it as a container for your UITextView.

Is it possible to add an array or object to SharedPreferences on Android

Regardless of the API level, Check String arrays and Object arrays in SharedPreferences


public boolean saveArray(String[] array, String arrayName, Context mContext) {   
    SharedPreferences prefs = mContext.getSharedPreferences("preferencename", 0);  
    SharedPreferences.Editor editor = prefs.edit();  
    editor.putInt(arrayName +"_size", array.length);  
    for(int i=0;i<array.length;i++)  
        editor.putString(arrayName + "_" + i, array[i]);  
    return editor.commit();  


public String[] loadArray(String arrayName, Context mContext) {  
    SharedPreferences prefs = mContext.getSharedPreferences("preferencename", 0);  
    int size = prefs.getInt(arrayName + "_size", 0);  
    String array[] = new String[size];  
    for(int i=0;i<size;i++)  
        array[i] = prefs.getString(arrayName + "_" + i, null);  
    return array;  

Is #pragma once a safe include guard?

#pragma once does have one drawback (other than being non-standard) and that is if you have the same file in different locations (we have this because our build system copies files around) then the compiler will think these are different files.

Entity Framework - Generating Classes

  1. Open the EDMX model
  2. Right click -> Update Model from Browser -> Stored Procedure -> Select your stored procedure -> Finish
  3. See the Model Browser popping up next to Solution Explorer.
  4. Go to Function Imports -> Right click on your Stored Procedure -> Add Function Import
  5. Select the Entities under Return a Collection of -> Select your Entity name from the drop down
  6. Build your Solution.

Why don't self-closing script elements work?

To add to what Brad and squadette have said, the self-closing XML syntax <script /> actually is correct XML, but for it to work in practice, your web server also needs to send your documents as properly formed XML with an XML mimetype like application/xhtml+xml in the HTTP Content-Type header (and not as text/html).

However, sending an XML mimetype will cause your pages not to be parsed by IE7, which only likes text/html.

From w3:

In summary, 'application/xhtml+xml' SHOULD be used for XHTML Family documents, and the use of 'text/html' SHOULD be limited to HTML-compatible XHTML 1.0 documents. 'application/xml' and 'text/xml' MAY also be used, but whenever appropriate, 'application/xhtml+xml' SHOULD be used rather than those generic XML media types.

I puzzled over this a few months ago, and the only workable (compatible with FF3+ and IE7) solution was to use the old <script></script> syntax with text/html (HTML syntax + HTML mimetype).

If your server sends the text/html type in its HTTP headers, even with otherwise properly formed XHTML documents, FF3+ will use its HTML rendering mode which means that <script /> will not work (this is a change, Firefox was previously less strict).

This will happen regardless of any fiddling with http-equiv meta elements, the XML prolog or doctype inside your document -- Firefox branches once it gets the text/html header, that determines whether the HTML or XML parser looks inside the document, and the HTML parser does not understand <script />.

What is logits, softmax and softmax_cross_entropy_with_logits?

Whatever goes to softmax is logit, this is what J. Hinton repeats in coursera videos all the time.

PowerShell: Format-Table without headers

Another approach is to use ForEach-Object to project individual items to a string and then use the Out-String CmdLet to project the final results to a string or string array:

gci Microsoft.PowerShell.Core\Registry::HKEY_CLASSES_ROOT\CID | foreach { "CID Key {0}" -f $_.Name } | Out-String

#Result: One multi-line string equal to:
CID Key HKEY_CLASSES_ROOT\CID\2a621c8a-7d4b-4d7b-ad60-a957fd70b0d0
CID Key HKEY_CLASSES_ROOT\CID\2ec6f5b2-8cdc-461e-9157-ffa84c11ba7d
CID Key HKEY_CLASSES_ROOT\CID\5da2ceaf-bc35-46e0-aabd-bd826023359b
CID Key HKEY_CLASSES_ROOT\CID\d13ad82e-d4fb-495f-9b78-01d2946e6426

gci Microsoft.PowerShell.Core\Registry::HKEY_CLASSES_ROOT\CID | foreach { "CID Key {0}" -f $_.Name } | Out-String -Stream

#Result: An array of single line strings equal to:
"CID Key HKEY_CLASSES_ROOT\CID\2a621c8a-7d4b-4d7b-ad60-a957fd70b0d0",
"CID Key HKEY_CLASSES_ROOT\CID\2ec6f5b2-8cdc-461e-9157-ffa84c11ba7d",
"CID Key HKEY_CLASSES_ROOT\CID\5da2ceaf-bc35-46e0-aabd-bd826023359b",
"CID Key HKEY_CLASSES_ROOT\CID\d13ad82e-d4fb-495f-9b78-01d2946e6426")

The benefit of this approach is that you can store the result to a variable and it will NOT have any empty lines.

Unable to run 'adb root' on a rooted Android phone

I finally found out how to do this! Basically you need to run adb shell first and then while you're in the shell run su, which will switch the shell to run as root!

$: adb shell
$: su

The one problem I still have is that sqlite3 is not installed so the command is not recognized.

Vertical align middle with Bootstrap responsive grid

Add !important rule to display: table of your .v-center class.

.v-center {
    display:table !important;
    border:2px solid gray;

Your display property is being overridden by bootstrap to display: block.


How can I download a file from a URL and save it in Rails?

If you're using PaperClip, downloading from a URL is now handled automatically.

Assuming you've got something like:

class MyModel < ActiveRecord::Base
  has_attached_file :image, ...

On your model, just specify the image as a URL, something like this (written in deliberate longhand):

@my_model =
image_url = params[:image_url]
@my_model.image = URI.parse(image_url)

You'll probably want to put this in a method in your model. This will also work just fine on Heroku's temporary filesystem.

Paperclip will take it from there.

source: paperclip documentation

How to copy files between two nodes using ansible

I was able to solve this using local_action to scp to file from machineA to machineC and then copying the file to machineB.

How do I change a PictureBox's image?

If you have an image imported as a resource in your project there is also this:

picPreview.Image = Properties.Resources.ImageName;

Where picPreview is the name of the picture box and ImageName is the name of the file you want to display.

*Resources are located by going to: Project --> Properties --> Resources

Highest Salary in each department

Here is a way to get maximum values and names on any version of SQL.

Test Data:

CREATE TABLE EmpDetails(DeptID VARCHAR(10), EmpName VARCHAR(10), Salary DECIMAL(8,2))
INSERT INTO EmpDetails VALUES('Engg','Sam',1000)
INSERT INTO EmpDetails VALUES('Engg','Smith',2000)
INSERT INTO EmpDetails VALUES('HR','Denis',1500)
INSERT INTO EmpDetails VALUES('HR','Danny',3000)
INSERT INTO EmpDetails VALUES('IT','David',2000)
INSERT INTO EmpDetails VALUES('IT','John',3000)


FROM (SELECT DeptID, MAX(Salary) MaxSal
      FROM EmpDetails
      GROUP BY DeptID)AS empmaxsal
INNER JOIN EmpDetails ed
  ON empmaxsal.DeptID = ed.DeptID
 AND empmaxsal.MaxSal = ed.Salary

Not the most elegant, but it works.

Importing JSON into an Eclipse project

Download the ZIP file from this URL and extract it to get the Jar. Add the Jar to your build path. To check the available classes in this Jar use this URL.

To Add this Jar to your build path Right click the Project > Build Path > Configure build path> Select Libraries tab > Click Add External Libraries > Select the Jar file Download

I hope this will solve your problem

Unicode character for "X" cancel / close?

× &#215; or &times; (same thing) U+00D7 multiplication sign

× same character with a strong font weight

? &#10799; U+2A2F Gibbs product

? &#10006; U+2716 heavy multiplication sign

There's also an emoji ❌ if you support it. If you don't you just saw a square = &#10060;

I also made this simple code example on Codepen when I was working with a designer who asked me to show her what it would look like when I asked if I could replace your close button with a coded version rather than an image.

  <li class="ele">
    <div class="x large"><b></b><b></b><b></b><b></b></div>
    <div class="x spin large"><b></b><b></b><b></b><b></b></div>
    <div class="x spin large slow"><b></b><b></b><b></b><b></b></div>
    <div class="x flop large"><b></b><b></b><b></b><b></b></div>
    <div class="x t large"><b></b><b></b><b></b><b></b></div>
    <div class="x shift large"><b></b><b></b><b></b><b></b></div>
  <li class="ele">
    <div class="x medium"><b></b><b></b><b></b><b></b></div>
    <div class="x spin medium"><b></b><b></b><b></b><b></b></div>
    <div class="x spin medium slow"><b></b><b></b><b></b><b></b></div>
    <div class="x flop medium"><b></b><b></b><b></b><b></b></div>
    <div class="x t medium"><b></b><b></b><b></b><b></b></div>
    <div class="x shift medium"><b></b><b></b><b></b><b></b></div>

  <li class="ele">
    <div class="x small"><b></b><b></b><b></b><b></b></div>
    <div class="x spin small"><b></b><b></b><b></b><b></b></div>
    <div class="x spin small slow"><b></b><b></b><b></b><b></b></div>
    <div class="x flop small"><b></b><b></b><b></b><b></b></div>
    <div class="x t small"><b></b><b></b><b></b><b></b></div>
    <div class="x shift small"><b></b><b></b><b></b><b></b></div>
    <div class="x small grow"><b></b><b></b><b></b><b></b></div>

  <li class="ele">
    <div class="x switch"><b></b><b></b><b></b><b></b></div>

How to tell if a JavaScript function is defined

I was looking for how to check if a jQuery function was defined and I didn't find it easily.

Perhaps might need it ;)

if(typeof jQuery.fn.datepicker !== "undefined")

throw checked Exceptions from mocks with Mockito

Note that in general, Mockito does allow throwing checked exceptions so long as the exception is declared in the message signature. For instance, given

class BarException extends Exception {
  // this is a checked exception

interface Foo {
  Bar frob() throws BarException

it's legal to write:

Foo foo = mock(Foo.class);

However, if you throw a checked exception not declared in the method signature, e.g.

class QuxException extends Exception {
  // a different checked exception

Foo foo = mock(Foo.class);

Mockito will fail at runtime with the somewhat misleading, generic message:

Checked exception is invalid for this method!
Invalid: QuxException

This may lead you to believe that checked exceptions in general are unsupported, but in fact Mockito is only trying to tell you that this checked exception isn't valid for this method.

I get a "An attempt was made to load a program with an incorrect format" error on a SQL Server replication project

Go to IIS -> Application Pool -> Advance Settings -> Enable 32-bit Applications

Get PostGIS version

Since some of the functions depend on other libraries like GEOS and proj4 you might want to get their versions too. Then use:

SELECT PostGIS_full_version();

Jersey client: How to add a list as query parameter

If you are sending anything other than simple strings I would recommend using a POST with an appropriate request body, or passing the entire list as an appropriately encoded JSON string. However, with simple strings you just need to append each value to the request URL appropriately and Jersey will deserialize it for you. So given the following example endpoint:

@Path("/service/echo") public class MyServiceImpl {
    public MyServiceImpl() {

    public Response echoInputList(@QueryParam("list") final List<String> inputList) {
        return Response.ok(inputList).build();

Your client would send a request corresponding to:


Which would result in inputList being deserialized to contain the values 'Hello', 'Stay' and 'Goodbye'

Compilation fails with "relocation R_X86_64_32 against `.rodata.str1.8' can not be used when making a shared object"

Fixed it with -no-pie option in linker stage:

g++-8 -L"/home/pedro/workspace/project/lib" -no-pie ...

How do I PHP-unserialize a jQuery-serialized form?

This is in reply to user1256561. Thanks for your idea.. however i have not taken care of the url decode stuff mentioned in step3.

so here is the php code that will decode the serialized form data, if anyone else needs it. By the way, use this code at your own discretion.

function xyz($strfromAjaxPOST)
    $array = "";
    $returndata = "";
    $strArray = explode("&", $strfromPOST);
    $i = 0;
    foreach ($strArray as $str)
        $array = explode("=", $str);
        $returndata[$i] = $array[0];
        $i = $i + 1;
        $returndata[$i] = $array[1];
        $i = $i + 1;

The url post data input will be like: attribute1=value1&attribute2=value2&attribute3=value3 and so on

Output of above code will still be in an array and you can modify it to get it assigned to any variable you want and it depends on how you want to use this data further.

    [0] => attribute1
    [1] => value1
    [2] => attribute2
    [3] => value2
    [4] => attribute3
    [5] => value3

How to find Port number of IP address?

If it is a normal then the port number is always 80 and may be written as Though you don't need to specify it as :80 is the default of every web browser.

If the site chose to use something else then they are intending to hide from anything not sent by a "friendly" or linked to. Those ones usually show with https and their port number is unknown and decided by their admin.

If you choose to runn a port scanner trying every number nn from say 10000 to 30000 in Then your isp or their antivirus will probably notice and disconnect you.


On Debian 9 I had to:

$ sudo update-ca-certificates --fresh
$ export SSL_CERT_DIR=/etc/ssl/certs

I'm not sure why, but this enviroment variable was never set.

How do I install a pip package globally instead of locally?

Maybe --force-reinstall would work, otherwise --ignore-installed should do the trick.

How to dismiss keyboard iOS programmatically when pressing return

First you need to add textfield delegete in .h file. if not declare (BOOL)textFieldShouldReturn:(UITextField *)textField this method not first add delegate and write keyboard hide code into that method.

- (BOOL)textFieldShouldReturn:(UITextField *)textField
    [textField resignFirstResponder];
    return YES;

try this one..

Variables within app.config/web.config

Inside <appSettings> you can create application keys,

<add key="KeyName" value="Keyvalue"/>

Later on you can access these values using:


Why is AJAX returning HTTP status code 0?

I had the same problem, and it was related to XSS (cross site scripting) block by the browser. I managed to make it work using a server.

Take a look at:

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

I'm one of the noob too when I encountered something like this. So... I set the passwords using the command security page gave me: /opt/lampp/lampp security Then I used password xyz for all the passwords... Then when I go to site/, it ask for a basic authentication. But when I tried root//xyz, it does not allow me login. So, after some digging, it turns out the xyz password was set for a default user named 'lampp'. When I tried to login using lampp//xyz, it worked like a charm.

The issue is that they made an assumption that everyone knows to use lampp//rootpw as their login o.O And... that is a basic auth for the directory! not pw for phpmyadmin or pw for mysql...

Working around MySQL error "Deadlock found when trying to get lock; try restarting transaction"

If you are using InnoDB or any row-level transactional RDBMS, then it is possible that any write transaction can cause a deadlock, even in perfectly normal situations. Larger tables, larger writes, and long transaction blocks will often increase the likelihood of deadlocks occurring. In your situation, it's probably a combination of these.

The only way to truly handle deadlocks is to write your code to expect them. This generally isn't very difficult if your database code is well written. Often you can just put a try/catch around the query execution logic and look for a deadlock when errors occur. If you catch one, the normal thing to do is just attempt to execute the failed query again.

I highly recommend you read this page in the MySQL manual. It has a list of things to do to help cope with deadlocks and reduce their frequency.

TypeError: $(...).modal is not a function with bootstrap Modal

In my experience, most probably its happened with jquery version(using multiple version) conflicts, for sort out the issue we can use a no-conflict method like below.

(function( $ ) {
  $(function() {
    // More code using $ as alias to jQuery

What is the difference between MOV and LEA?

If you only specify a literal, there is no difference. LEA has more abilities, though, and you can read about them here:

How to decode a Base64 string?

This page shows up when you google how to convert to base64, so for completeness:

$b  = [System.Text.Encoding]::UTF8.GetBytes("blahblah")

How can I copy a Python string?

Copying a string can be done two ways either copy the location a = "a" b = a or you can clone which means b wont get affected when a is changed which is done by a = 'a' b = a[:]

What is the functionality of setSoTimeout and how it works?

This example made everything clear for me:
As you can see setSoTimeout prevent the program to hang! It wait for SO_TIMEOUT time! if it does not get any signal it throw exception! It means that time expired!


public class SocketTest extends Thread {
  private ServerSocket serverSocket;

  public SocketTest() throws IOException {
    serverSocket = new ServerSocket(8008);

  public void run() {
    while (true) {
      try {
        System.out.println("Waiting for client on port " + serverSocket.getLocalPort() + "...");
        Socket client = serverSocket.accept();

        System.out.println("Just connected to " + client.getRemoteSocketAddress());
      } catch (SocketTimeoutException s) {
        System.out.println("Socket timed out!");
      } catch (IOException e) {

  public static void main(String[] args) {
    try {
      Thread t = new SocketTest();
    } catch (IOException e) {

Java reading a file into an ArrayList?

//CS124 HW6 Wikipedia Relation Extraction
//Alan Joyce (ajoyce)
public List<String> addWives(String fileName) {
    List<String> wives = new ArrayList<String>();
    try {
        BufferedReader input = new BufferedReader(new FileReader(fileName));
        // for each line
        for(String line = input.readLine(); line != null; line = input.readLine()) {
    } catch(IOException e) {
        return null;
    return wives;

Is it possible to preview stash contents in git?

yes the best way to see what is modified is to save in file like that:

git stash show -p stash@{0} > stash.txt

How to hide the Google Invisible reCAPTCHA badge

I decided to hide the badge on all pages except my contact page (using Wordpress):

/* Hides the reCAPTCHA on every page */
.grecaptcha-badge {
    visibility: hidden !important;

/* Shows the reCAPTCHA on the Contact page */
/* Obviously change the page number to your own */
.page-id-17 .grecaptcha-badge {
    visibility: visible !important;

I'm not a web developer so please correct me if there's something wrong.

EDIT: Updated to use visibility instead of display.

How to delete a selected DataGridViewRow and update a connected database table?

This code removes selected items of dataGridView1:

 private void btnDelete_Click(object sender, EventArgs e)
     foreach (DataGridViewRow item in this.dataGridView1.SelectedRows)

How To Auto-Format / Indent XML/HTML in Notepad++

Install Tidy2 plugin. I have Notepad++ v6.2.2, and Tidy2 works fine so far.

Print series of prime numbers in python

A Python Program function module that returns the 1'st N prime numbers:

def get_primes(count):
        Return the 1st count prime integers.
    result = []
    while len(result) in range(count):
        for i in range(2,x):
            if x%i == 0:
        if flag == 0:
    return result

How to return 2 values from a Java method?

I'm curious as to why nobody has come up with the more elegant callback solution. So instead of using a return type you use a handler passed into the method as an argument. The example below has the two contrasting approaches. I know which of the two is more elegant to me. :-)

public class DiceExample {

    public interface Pair<T1, T2> {
        T1 getLeft();

        T2 getRight();

    private Pair<Integer, Integer> rollDiceWithReturnType() {

        double dice1 = (Math.random() * 6);
        double dice2 = (Math.random() * 6);

        return new Pair<Integer, Integer>() {
            public Integer getLeft() {
                return (int) Math.ceil(dice1);

            public Integer getRight() {
                return (int) Math.ceil(dice2);

    public interface ResultHandler {
        void handleDice(int ceil, int ceil2);

    private void rollDiceWithResultHandler(ResultHandler resultHandler) {
        double dice1 = (Math.random() * 6);
        double dice2 = (Math.random() * 6);

        resultHandler.handleDice((int) Math.ceil(dice1), (int) Math.ceil(dice2));

    public static void main(String[] args) {

        DiceExample object = new DiceExample();

        Pair<Integer, Integer> result = object.rollDiceWithReturnType();
        System.out.println("Dice 1: " + result.getLeft());
        System.out.println("Dice 2: " + result.getRight());

        object.rollDiceWithResultHandler((dice1, dice2) -> {
            System.out.println("Dice 1: " + dice1);
            System.out.println("Dice 2: " + dice2);

What is "origin" in Git?

Origin is the shortname that acts like an alias for the url of the remote repository.

Let me explain with an example.

Suppose you have a remote repository called amazing-project and then you clone that remote repository to your local machine so that you have a local repository. Then you would have something like what you can see in the diagram below:

enter image description here

Because you cloned the repository. The remote repository and the local repository are linked.

If you run the command git remote -v it will list all the remote repositories that are linked to your local repository. There you will see that in order to push or fetch code from your remote repository you will use the shortname 'origin'. enter image description here

Now, this may be a bit confusing because in GitHub (or the remote server) the project is called 'amazing-project'. So why does it seem like there are two names for the remote repository?

enter image description here

Well one of the names that we have for our repository is the name it has on GitHub or a remote server somewhere. This can be kind of thought like a project name. And in our case that is 'amazing-project'.

The other name that we have for our repository is the shortname that it has in our local repository that is related to the URL of the repository. It is the shortname we are going to use whenever we want to push or fetch code from that remote repository. And this shortname kind of acts like an alias for the url, it's a way for us to avoid having to use that entire long url in order to push or fetch code. And in our example above it is called origin.

So, what is origin?

Basically origin is the default shortname that Git uses for a remote repository when you clone that remote repository. So it's just the default.

In many cases you will have links to multiple remote repositories in your local repository and each of those will have a different shortname.

So final question, why don't we just use the same name?

I will answer that question with another example. Suppose we have a friend who forks our remote repository so they can help us on our project. And let's assume we want to be able to fetch code from their remote repository. We can use the command git remote add <shortname> <url> in order to add a link to their remote repository in our local repository.

enter image description here

In the above image you can see that I used the shortname friend to refer to my friend's remote repository. You can also see that both of the remote repositories have the same project name amazing-project and that gives us one reason why the remote repository names in the remote server and the shortnames in our local repositories should not be the same!

There is a really helpful video that explains all of this that can be found here.

Error - is not marked as serializable

You need to add a Serializable attribute to the class which you want to serialize.

public class OrgPermission

Angularjs -> ng-click and ng-show to show a div

Just get rid of the display: none; from your CSS. AngularJS is in control of showing/hiding that div.

If you want to hide it by default, just set the value of scope.myvalue to false initially - which you're already doing.

Nginx Different Domains on Same IP

Your "listen" directives are wrong. See this page:

They should be

server {
    listen      80;
    root /var/www/domain1;

server {
    listen       80;
    root /var/www/domain2;

Note, I have only included the relevant lines. Everything else looked okay but I just deleted it for clarity. To test it you might want to try serving a text file from each server first before actually serving php. That's why I left the 'root' directive in there.

Easy pretty printing of floats in python?

I just ran into this problem while trying to use pprint to output a list of tuples of floats. Nested comprehensions might be a bad idea, but here's what I did:

tups = [
        (12.0, 9.75, 23.54),
        (12.5, 2.6, 13.85),
        (14.77, 3.56, 23.23),
        (12.0, 5.5, 23.5)
pprint([['{0:0.02f}'.format(num) for num in tup] for tup in tups])

I used generator expressions at first, but pprint just repred the generator...

Using CookieContainer with WebClient class

The HttpWebRequest modifies the CookieContainer assigned to it. There is no need to process returned cookies. Simply assign your cookie container to every web request.

public class CookieAwareWebClient : WebClient
    public CookieContainer CookieContainer { get; set; } = new CookieContainer();

    protected override WebRequest GetWebRequest(Uri uri)
        WebRequest request = base.GetWebRequest(uri);
        if (request is HttpWebRequest)
            (request as HttpWebRequest).CookieContainer = CookieContainer;
        return request;

How to check if "Radiobutton" is checked?

Simple Solution

radioSection.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
          public void onCheckedChanged(RadioGroup group1, int checkedId1) {
              switch (checkedId1) {
                      //do what you want
                      //do what you want

How to iterate over arguments in a Bash script

Rewrite of a now-deleted answer by VonC.

Robert Gamble's succinct answer deals directly with the question. This one amplifies on some issues with filenames containing spaces.

See also: ${1:+"$@"} in /bin/sh

Basic thesis: "$@" is correct, and $* (unquoted) is almost always wrong. This is because "$@" works fine when arguments contain spaces, and works the same as $* when they don't. In some circumstances, "$*" is OK too, but "$@" usually (but not always) works in the same places. Unquoted, $@ and $* are equivalent (and almost always wrong).

So, what is the difference between $*, $@, "$*", and "$@"? They are all related to 'all the arguments to the shell', but they do different things. When unquoted, $* and $@ do the same thing. They treat each 'word' (sequence of non-whitespace) as a separate argument. The quoted forms are quite different, though: "$*" treats the argument list as a single space-separated string, whereas "$@" treats the arguments almost exactly as they were when specified on the command line. "$@" expands to nothing at all when there are no positional arguments; "$*" expands to an empty string — and yes, there's a difference, though it can be hard to perceive it. See more information below, after the introduction of the (non-standard) command al.

Secondary thesis: if you need to process arguments with spaces and then pass them on to other commands, then you sometimes need non-standard tools to assist. (Or you should use arrays, carefully: "${array[@]}" behaves analogously to "$@".)


    $ mkdir "my dir" anotherdir
    $ ls
    anotherdir      my dir
    $ cp /dev/null "my dir/my file"
    $ cp /dev/null "anotherdir/myfile"
    $ ls -Fltr
    total 0
    drwxr-xr-x   3 jleffler  staff  102 Nov  1 14:55 my dir/
    drwxr-xr-x   3 jleffler  staff  102 Nov  1 14:55 anotherdir/
    $ ls -Fltr *
    my dir:
    total 0
    -rw-r--r--   1 jleffler  staff  0 Nov  1 14:55 my file

    total 0
    -rw-r--r--   1 jleffler  staff  0 Nov  1 14:55 myfile
    $ ls -Fltr "./my dir" "./anotherdir"
    ./my dir:
    total 0
    -rw-r--r--   1 jleffler  staff  0 Nov  1 14:55 my file

    total 0
    -rw-r--r--   1 jleffler  staff  0 Nov  1 14:55 myfile
    $ var='"./my dir" "./anotherdir"' && echo $var
    "./my dir" "./anotherdir"
    $ ls -Fltr $var
    ls: "./anotherdir": No such file or directory
    ls: "./my: No such file or directory
    ls: dir": No such file or directory

Why doesn't that work? It doesn't work because the shell processes quotes before it expands variables. So, to get the shell to pay attention to the quotes embedded in $var, you have to use eval:

    $ eval ls -Fltr $var
    ./my dir:
    total 0
    -rw-r--r--   1 jleffler  staff  0 Nov  1 14:55 my file

    total 0
    -rw-r--r--   1 jleffler  staff  0 Nov  1 14:55 myfile

This gets really tricky when you have file names such as "He said, "Don't do this!"" (with quotes and double quotes and spaces).

    $ cp /dev/null "He said, \"Don't do this!\""
    $ ls
    He said, "Don't do this!"       anotherdir                      my dir
    $ ls -l
    total 0
    -rw-r--r--   1 jleffler  staff    0 Nov  1 15:54 He said, "Don't do this!"
    drwxr-xr-x   3 jleffler  staff  102 Nov  1 14:55 anotherdir
    drwxr-xr-x   3 jleffler  staff  102 Nov  1 14:55 my dir

The shells (all of them) do not make it particularly easy to handle such stuff, so (funnily enough) many Unix programs do not do a good job of handling them. On Unix, a filename (single component) can contain any characters except slash and NUL '\0'. However, the shells strongly encourage no spaces or newlines or tabs anywhere in a path names. It is also why standard Unix file names do not contain spaces, etc.

When dealing with file names that may contain spaces and other troublesome characters, you have to be extremely careful, and I found long ago that I needed a program that is not standard on Unix. I call it escape (version 1.1 was dated 1989-08-23T16:01:45Z).

Here is an example of escape in use - with the SCCS control system. It is a cover script that does both a delta (think check-in) and a get (think check-out). Various arguments, especially -y (the reason why you made the change) would contain blanks and newlines. Note that the script dates from 1992, so it uses back-ticks instead of $(cmd ...) notation and does not use #!/bin/sh on the first line.

:   "@(#)$Id:,v 1.8 1992/12/29 10:46:21 jl Exp $"
#   Delta and get files
#   Uses escape to allow for all weird combinations of quotes in arguments

case `basename $0 .sh` in
deledit)    eflag="-e";;

for arg in "$@"
    case "$arg" in
    -r*)    gargs="$gargs `escape \"$arg\"`"
            dargs="$dargs `escape \"$arg\"`"
    -e)     gargs="$gargs `escape \"$arg\"`"
    -*)     dargs="$dargs `escape \"$arg\"`"
    *)      gargs="$gargs `escape \"$arg\"`"
            dargs="$dargs `escape \"$arg\"`"

eval delta "$dargs" && eval get $eflag $sflag "$gargs"

(I would probably not use escape quite so thoroughly these days - it is not needed with the -e argument, for example - but overall, this is one of my simpler scripts using escape.)

The escape program simply outputs its arguments, rather like echo does, but it ensures that the arguments are protected for use with eval (one level of eval; I do have a program which did remote shell execution, and that needed to escape the output of escape).

    $ escape $var
    '"./my' 'dir"' '"./anotherdir"'
    $ escape "$var"
    '"./my dir" "./anotherdir"'
    $ escape x y z
    x y z

I have another program called al that lists its arguments one per line (and it is even more ancient: version 1.1 dated 1987-01-27T14:35:49). It is most useful when debugging scripts, as it can be plugged into a command line to see what arguments are actually passed to the command.

    $ echo "$var"
    "./my dir" "./anotherdir"
    $ al $var
    $ al "$var"
    "./my dir" "./anotherdir"

[Added: And now to show the difference between the various "$@" notations, here is one more example:

$ cat
set -x
al $@
al $*
al "$*"
al "$@"
$ sh     *      */*
+ al He said, '"Don'\''t' do 'this!"' anotherdir my dir anotherdir/myfile my dir/my file
+ al He said, '"Don'\''t' do 'this!"' anotherdir my dir anotherdir/myfile my dir/my file
+ al 'He said, "Don'\''t do this!" anotherdir my dir anotherdir/myfile my dir/my file'
He said, "Don't do this!" anotherdir my dir anotherdir/myfile my dir/my file
+ al 'He said, "Don'\''t do this!"' anotherdir 'my dir' anotherdir/myfile 'my dir/my file'
He said, "Don't do this!"
my dir
my dir/my file

Notice that nothing preserves the original blanks between the * and */* on the command line. Also, note that you can change the 'command line arguments' in the shell by using:

set -- -new -opt and "arg with space"

This sets 4 options, '-new', '-opt', 'and', and 'arg with space'.

Hmm, that's quite a long answer - perhaps exegesis is the better term. Source code for escape available on request (email to firstname dot lastname at gmail dot com). The source code for al is incredibly simple:

#include <stdio.h>
int main(int argc, char **argv)
    while (*++argv != 0)

That's all. It is equivalent to the script that Robert Gamble showed, and could be written as a shell function (but shell functions didn't exist in the local version of Bourne shell when I first wrote al).

Also note that you can write al as a simple shell script:

[ $# != 0 ] && printf "%s\n" "$@"

The conditional is needed so that it produces no output when passed no arguments. The printf command will produce a blank line with only the format string argument, but the C program produces nothing.

What is the exact meaning of Git Bash?

I think the question asker is (was) thinking that git bash is a command like git init or git checkout. Git bash is not a command, it is an interface. I will also assume the asker is not a linux user because bash is very popular the unix/linux world. The name "bash" is an acronym for "Bourne Again SHell". Bash is a text-only command interface that has features which allow automated scripts to be run. A good analogy would be to compare bash to the new PowerShell interface in Windows7/8. A poor analogy (but one likely to be more readily understood by more people) is the combination of the command prompt and .BAT (batch) command files from the days of DOS and early versions of Windows.


How to read a file in other directory in python

i found this way useful also.

import tkinter.filedialog
from_filename = tkinter.filedialog.askopenfilename()  

here a window will appear so you can browse till you find the file , you click on it then you can continue using open , and read .

from_file = open(from_filename, 'r')
contents =

The following artifacts could not be resolved: javax.jms:jms:jar:1.1

Thanks for the suggestions. I finally found a solution to this problem after reading this. It turns out that these dependencies were coming from a dependency to ZooKeeper.

I modified my pom.xml as following and it solved the problem:


What is the use of "assert"?

The assert statement exists in almost every programming language. It helps detect problems early in your program, where the cause is clear, rather than later as a side-effect of some other operation. They always expect a True condition.

When you do something like:

assert condition

You're telling the program to test that condition and immediately trigger an error if it is false.

In Python, assert expression, is equivalent to:

if __debug__:
    if not <expression>: raise AssertionError

You can use the extended expression to pass an optional message:

if __debug__:
    if not (expression_1): raise AssertionError(expression_2)

Try it in the Python interpreter:

>>> assert True # Nothing happens because the condition returns a True value.
>>> assert False # A traceback is triggered because this evaluation did not yield an expected value.
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>

There are some caveats to seen before using them mainly for those who deem to toggles between the assert and if statements. The aim to use assert is on occasions when the program verifies a condition and return a value that should stop the program immediately instead of taking some alternative way to bypass the error:

1. Parentheses

As you may have noticed, the assert statement uses two conditions. Hence, do not use parentheses to englobe them as one for obvious advice. If you do such as:

assert (condition, message)


>>> assert (1==2, 1==1)
<stdin>:1: SyntaxWarning: assertion is always true, perhaps remove parentheses?

You will be running the assert with a (condition, message) which represents a tuple as the first parameter, and this happens cause non-empty tuple in Python is always True. However, you can do separately without problem:

assert (condition), "message"


>>> assert (1==2), ("This condition returns a %s value.") % "False"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError: This condition returns a False value.

2. Debug purpose

If you are wondering regarding when use assert statement. Take an example used in real life:

* When your program tends to control each parameter entered by the user or whatever else:

def loremipsum(**kwargs):
    kwargs.pop('bar') # return 0 if "bar" isn't in parameter
    kwargs.setdefault('foo', type(self)) # returns `type(self)` value by default
    assert (len(kwargs) == 0), "unrecognized parameter passed in %s" % ', '.join(kwargs.keys())

* Another case is on math when 0 or non-positive as a coefficient or constant on a certain equation:

def discount(item, percent):
    price = int(item['price'] * (1.0 - percent))
    assert (0 <= price <= item['price']),\
            "Discounted prices cannot be lower than 0 "\
            "and they cannot be higher than the original price."

    return price

* or even a simple example of a boolean implementation:

def true(a, b):
    assert (a == b), "False"
    return 1

def false(a, b):
    assert (a != b), "True"
    return 0

3. Data processing or data validation

The utmost importance is to not rely on the assert statement to execute data processing or data validation because this statement can be turned off on the Python initialization with -O or -OO flag – meaning value 1, 2, and 0 (as default), respectively – or PYTHONOPTIMIZE environment variable.

Value 1:

* asserts are disabled;

* bytecode files are generated using .pyo extension instead of .pyc;

* sys.flags.optimize is set to 1 (True);

* and, __debug__ is set to False;

Value 2: disables one more stuff

* docstrings are disabled;

Therefore, using the assert statement to validate a sort of expected data is extremely dangerous, implying even to some security issues. Then, if you need to validate some permission I recommend you raise AuthError instead. As a preconditional effective, an assert is commonly used by programmers on libraries or modules that do not have a user interact directly.

Executing another application from Java

If you don't care about the return value you could just use Runtime.getRuntime().exec("");

How to find the remainder of a division in C?

All the above answers are correct. Just providing with your dataset to find perfect divisor:

#include <stdio.h>

int main() 

int arr[7] = {3,5,7,8,9,17,19};
int j = 51;
int i = 0;

for (i=0 ; i < 7; i++) {
    if (j % arr[i] == 0)
        printf("%d is the perfect divisor of %d\n", arr[i], j);

return 0;

If (Array.Length == 0)

Jon Skeet answered correctly. Just remember that the order of the test in the "IF" is important. Check for the null before the length. I also prefer to put the null on the left side of the equal which is a habit I got from Java that made the code more efficient and fast… I don't think it's important in a lot of application today, but it's a good practice!

if (null == array || array.Length == 0)

How to use jQuery in chrome extension?

You have to add your jquery script to your chrome-extension project and to the background section of your manifest.json like this :

        "scripts": ["thirdParty/jquery-2.0.3.js", "background.js"]

If you need jquery in a content_scripts, you have to add it in the manifest too:

            "js":["thirdParty/jquery.1.10.2.min.js", "script.js"],
            "css": ["css/style.css"],
            "run_at": "document_end"

This is what I did.

Also, if I recall correctly, the background scripts are executed in a background window that you can open via chrome://extensions.

Make REST API call in Swift

Here is the complete code for REST API requests using NSURLSession in swift

For GET Request

 let configuration = NSURLSessionConfiguration .defaultSessionConfiguration()
    let session = NSURLSession(configuration: configuration)

    let urlString = NSString(format: "your URL here")

    print("get wallet balance url string is \(urlString)")
    //let url = NSURL(string: urlString as String)
    let request : NSMutableURLRequest = NSMutableURLRequest()
    request.URL = NSURL(string: NSString(format: "%@", urlString) as String)
    request.HTTPMethod = "GET"
    request.timeoutInterval = 30

    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")

    let dataTask = session.dataTaskWithRequest(request) {
        (let data: NSData?, let response: NSURLResponse?, let error: NSError?) -> Void in

        // 1: Check HTTP Response for successful GET request
        guard let httpResponse = response as? NSHTTPURLResponse, receivedData = data
            else {
                print("error: not a valid http response")

        switch (httpResponse.statusCode)
        case 200:

            let response = NSString (data: receivedData, encoding: NSUTF8StringEncoding)
            print("response is \(response)")

            do {
                let getResponse = try NSJSONSerialization.JSONObjectWithData(receivedData, options: .AllowFragments)

                EZLoadingActivity .hide()

               // }
            } catch {
                print("error serializing JSON: \(error)")

        case 400:

            print("wallet GET request got response \(httpResponse.statusCode)")

For POST request ...

let configuration = NSURLSessionConfiguration .defaultSessionConfiguration()
    let session = NSURLSession(configuration: configuration)

    let params = ["username":bindings .objectForKey("username"), "provider":"walkingcoin", "securityQuestion":securityQuestionField.text!, "securityAnswer":securityAnswerField.text!] as Dictionary<String, AnyObject>

    let urlString = NSString(format: “your URL”);
    print("url string is \(urlString)")
    let request : NSMutableURLRequest = NSMutableURLRequest()
    request.URL = NSURL(string: NSString(format: "%@", urlString)as String)
    request.HTTPMethod = "POST"
    request.timeoutInterval = 30
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")      
    request.HTTPBody  = try! NSJSONSerialization.dataWithJSONObject(params, options: [])

    let dataTask = session.dataTaskWithRequest(request)
            (let data: NSData?, let response: NSURLResponse?, let error: NSError?) -> Void in
            // 1: Check HTTP Response for successful GET request
            guard let httpResponse = response as? NSHTTPURLResponse, receivedData = data
                else {
                    print("error: not a valid http response")

            switch (httpResponse.statusCode)
            case 200:

                let response = NSString (data: receivedData, encoding: NSUTF8StringEncoding)

                if response == "SUCCESS"


                print("save profile POST request got response \(httpResponse.statusCode)")

I hope it works.

Delete a row in Excel VBA

Chris Nielsen's solution is simple and will work well. A slightly shorter option would be...


...note there is no need to specify a Shift when deleting a row as, by definition, it's not possible to shift left

Incidentally, my preferred method for deleting rows is to use...

ws.Rows(Rand) = "" the initial loop. I then use a Sort function to push these rows to the bottom of the data. The main reason for this is because deleting single rows can be a very slow procedure (if you are deleting >100). It also ensures nothing gets missed as per Robert Ilbrink's comment

You can learn the code for sorting by recording a macro and reducing the code as demonstrated in this expert Excel video. I have a suspicion that the neatest method (Range("A1:Z10").Sort Key1:=Range("A1"), Order1:=xlSortAscending/Descending, Header:=xlYes/No) can only be discovered on pre-2007 versions of Excel...but you can always reduce the 2007/2010 equivalent code

Couple more points...if your list is not already sorted by a column and you wish to retain the order, you can stick the row number 'Rand' in a spare column to the right of each row as you loop through. You would then sort by that comment and eliminate it

If your data rows contain formatting, you may wish to find the end of the new data range and delete the rows that you cleared earlier. That's to keep the file size down. Note that a single large delete at the end of the procedure will not impair your code's performance in the same way that deleting single rows does

How to override Bootstrap's Panel heading background color?

How about creating your own Custom Panel class? That way you won't have to worry about overriding Bootstrap.


<div class="panel panel-custom-horrible-red">
   <div class="panel-heading">
      <h3 class="panel-title">Panel title</h3>
   <div class="panel-body">
      Panel content


.panel-custom-horrible-red {
    border-color: #ff0000;
.panel-custom-horrible-red > .panel-heading {
    background: #ff0000; 
    color: #ffffff;
    border-color: #ff0000;


How to attach a process in gdb

Try one of these:

gdb -p 12271
gdb /path/to/exe 12271

gdb /path/to/exe
(gdb) attach 12271

Is Safari on iOS 6 caching $.ajax results?

That's the work around for GWT-RPC

class AuthenticatingRequestBuilder extends RpcRequestBuilder 
       protected RequestBuilder doCreate(String serviceEntryPoint) 
               RequestBuilder requestBuilder = super.doCreate(serviceEntryPoint);           
               requestBuilder.setHeader("Cache-Control", "no-cache");

               return requestBuilder;

AuthenticatingRequestBuilder builder = new AuthenticatingRequestBuilder();

PHP post_max_size overrides upload_max_filesize

upload_max_filesize is the limit of any single file. post_max_size is the limit of the entire body of the request, which could include multiple files.

Given post_max_size = 20M and upload_max_filesize = 6M you could upload up to 3 files of 6M each. If instead post_max_size = 6M and upload_max_filesize = 20M then you could only upload one 6M file before hitting post_max_size. It doesn't help to have upload_max_size > post_max_size.

It's not obvious how to recognize going over post_max_size. $_POST and $_FILES will be empty, but $_SERVER['CONTENT_LENGTH'] will be > 0. If the client just didn't upload any post variables or files, then $_SERVER['CONTENT_LENGTH'] will be 0.

Getting the source HTML of the current page from chrome extension

Here is my solution:

chrome.runtime.onMessage.addListener(function(request, sender) {
        if (request.action == "getSource") {
            this.pageSource = request.source;
            var title = this.pageSource.match(/<title[^>]*>([^<]+)<\/title>/)[1];

    chrome.tabs.query({ active: true, currentWindow: true }, tabs => {
            { code: 'var s = document.documentElement.outerHTML; chrome.runtime.sendMessage({action: "getSource", source: s});' }

Android setOnClickListener method - How does it work?

That what manual says about setOnClickListener method is:

public void setOnClickListener (View.OnClickListener l)

Added in API level 1 Register a callback to be invoked when this view is clicked. If this view is not clickable, it becomes clickable.


l View.OnClickListener: The callback that will run

And normally you have to use it like this

public class ExampleActivity extends Activity implements OnClickListener {
    protected void onCreate(Bundle savedValues) {
        Button button = (Button)findViewById(;

    // Implement the OnClickListener callback
    public void onClick(View v) {
      // do something when the button is clicked

Take a look at this lesson as well Building a Simple Calculator using Android Studio.

Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints

Short and easy Soloution:

Go to MSSQL Studio Sever ;

Run the query of the cause of this error : in my case i see that id value was null because i forget to set Identity specification increment by 1.

enter image description here

So entered 1 for the id field as its is autoincremane and modify dont allow NULLS in desing view

enter image description here

That was the error that caused my bindingsource and tabel adapter throwin error at this code:


How to set ChartJS Y axis title?

For me it works like this:

    options : {
      scales: {
        yAxes: [{
          scaleLabel: {
            display: true,
            labelString: 'probability'

What is the correct XPath for choosing attributes that contain "foo"?

If you also need to match the content of the link itself, use text():

//a[contains(@href,"/some_link")][text()="Click here"]

Initialize 2D array

Easy to read/type.

  table = new char[][] {
    , "abcdefghij".toCharArray()

Visual Studio Community 2015 expiration date

Here is a simple approach to sneak by that stupid blocker screen in Visual Studio after 30-days expires using Process Hacker:

VS2015 Trial

Details at:

It's more of a quick 'n dirty fix than a real solution. However, it may be quicker than doing all that official login/sign up, subscribe, whatever crap Microsoft wants you to do, in order to use Visual Studio Community Version for free.

convert string to specific datetime format?

"2011-05-19 10:30:14".to_time

sudo: npm: command not found

Installl node.js & simply run

npm install -g bower 

from your project dir

How to make FileFilter in java?

Another simple example:

public static void listFilesInDirectory(String pathString) {
  // A local class (a class defined inside a block, here a method).
  class MyFilter implements FileFilter {
    public boolean accept(File file) {
      return !file.isHidden() && file.getName().endsWith(".txt");

  File directory = new File(pathString);
  File[] files = directory.listFiles(new MyFilter());

  for (File fileLoop : files) {

// Call it

// Output

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

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

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

Highlight text similar to grep, but don't filter out text

Since you want matches highlighted, this is probably for human consumption (as opposed to piping to another program for instance), so a nice solution would be to use:

less -p <your-pattern> <your-file>

And if you don't care about case sensitivity:

less -i -p <your-pattern> <your-file>

This also has the advantage of having pages, which is nice when having to go through a long output

diff to output only the file names

From the diff man page:

-q   Report only whether the files differ, not the details of the differences.
-r   When comparing directories, recursively compare any subdirectories found.

Example command:

diff -qr dir1 dir2

Example output (depends on locale):

$ ls dir1 dir2
same-file  different  only-1

same-file  different  only-2
$ diff -qr dir1 dir2
Files dir1/different and dir2/different differ
Only in dir1: only-1
Only in dir2: only-2

How to fix request failed on channel 0

Try this:

vi /etc/security/limits.d/20-nproc.conf
*          soft    nproc     4096   # change to 65535 
root       soft    nproc     unlimited

Are PHP short tags acceptable to use?

The problem with this whole discussion lies in the use of PHP as a templating language. No one is arguing that tags should be used in application source files.

However PHP's embeddable syntax allows it to be used as a powerful template language, and templates should be as simple and readable as possible. Many have found it easier to use a much slower, add-on templating engine like Smarty, but for those purists among us who demand fast rendering and a pure code base, PHP is the only way to write templates.

The ONLY valid argument AGAINST the use of short tags is that they aren't supported on all servers. Comments about conflicts with XML documents are ludicrous, because you probably shouldn't be mixing PHP and XML anyway; and if you are, you should be using PHP to output strings of text. Security should never be an issue, because if you're putting sensitive information like database access credentials inside of template files, well then, you've got bigger issues!

Now then, as to the issue of server support, admittedly one has to be aware of their target platform. If shared hosting is a likely target, then short tags should be avoided. But for many professional developers (such as myself), the client acknowledges (and indeed, depends on the fact) that we will be dictating the server requirements. Often I'm responsible for setting up the server myself.

And we NEVER work with a hosting provider that does not give us absolute control of the server configuration -- in such a case we could count on running to much more trouble than just losing short tag support. It just doesn't happen.

So yes -- I agree that the use of short tags should be carefully weighed. But I also firmly believe that it should ALWAYS be an option, and that a developer who is aware of his environment should feel free to use them.

List all column except for one in R

You can index and use a negative sign to drop the 3rd column:


Or you can list only the first 2 columns:

data[,c("c1", "c2")]

Don't forget the comma and referencing data frames works like this: data[row,column]

correct configuration for nginx to localhost?

Fundamentally you hadn't declare location which is what nginx uses to bind URL with resources.

 server {
            listen       80;
            server_name  localhost;

            access_log  logs/localhost.access.log  main;

            location / {
                root /var/www/board/public;
                index index.html index.htm index.php;

Creating a Menu in Python

def my_add_fn():
   print "SUM:%s"%sum(map(int,raw_input("Enter 2 numbers seperated by a space").split()))

def my_quit_fn():
   raise SystemExit

def invalid():
   print "INVALID CHOICE!"

menu = {"1":("Sum",my_add_fn),
for key in sorted(menu.keys()):
     print key+":" + menu[key][0]

ans = raw_input("Make A Choice")

How to git clone a specific tag

Cloning a specific tag, might return 'detached HEAD' state.

As a workaround, try to clone the repo first, and then checkout a specific tag. For example:

repo_dir=$(basename $repo_url .git)

git clone --single-branch $repo_url # using --depth 1 can show no tags
git --work-tree=$repo_dir --git-dir=$repo_dir/.git checkout tags/$repo_tag

Note: Since Git 1.8.5, you can use -C <path>, instead of --work-tree and --git-dir.

Array vs. Object efficiency in JavaScript

I had a similar problem that I am facing where I need to store live candlesticks from an event source limited to x items. I could have them stored in an object where the timestamp of each candle would act as the key and the candle itself would act as the value. Another possibility was that I could store it in an array where each item was the candle itself. One problem about live candles is that they keep sending updates on the same timestamp where the latest update holds the most recent data therefore you either update an existing item or add a new one. So here is a nice benchmark that attempts to combine all 3 possibilities. Arrays in the solution below are atleast 4x faster on average. Feel free to play

"use strict";

const EventEmitter = require("events");
let candleEmitter = new EventEmitter();

//Change this to set how fast the setInterval should run
const frequency = 1;

setInterval(() => {
    // Take the current timestamp and round it down to the nearest second
    let time = Math.floor( / 1000) * 1000;
    let open = Math.random();
    let high = Math.random();
    let low = Math.random();
    let close = Math.random();
    let baseVolume = Math.random();
    let quoteVolume = Math.random();

    //Clear the console everytime before printing fresh values

    candleEmitter.emit("candle", {
        symbol: "ABC:DEF",
        time: time,
        open: open,
        high: high,
        low: low,
        close: close,
        baseVolume: baseVolume,
        quoteVolume: quoteVolume

}, frequency)

// Test 1 would involve storing the candle in an object
candleEmitter.on('candle', storeAsObject)

// Test 2 would involve storing the candle in an array
candleEmitter.on('candle', storeAsArray)

//Container for the object version of candles
let objectOhlc = {}

//Container for the array version of candles
let arrayOhlc = {}

//Store a max 30 candles and delete older ones
let limit = 30

function storeAsObject(candle) {

    //measure the start time in nanoseconds
    const hrtime1 = process.hrtime()
    const start = hrtime1[0] * 1e9 + hrtime1[1]

    const { symbol, time } = candle;

    // Create the object structure to store the current symbol
    if (typeof objectOhlc[symbol] === 'undefined') objectOhlc[symbol] = {}

    // The timestamp of the latest candle is used as key with the pair to store this symbol
    objectOhlc[symbol][time] = candle;

    // Remove entries if we exceed the limit
    const keys = Object.keys(objectOhlc[symbol]);
    if (keys.length > limit) {
        for (let i = 0; i < (keys.length - limit); i++) {
            delete objectOhlc[symbol][keys[i]];

    //measure the end time in nano seocnds
    const hrtime2 = process.hrtime()
    const end = hrtime2[0] * 1e9 + hrtime2[1]

    console.log("Storing as objects", end - start, Object.keys(objectOhlc[symbol]).length)

function storeAsArray(candle) {

    //measure the start time in nanoseconds
    const hrtime1 = process.hrtime()
    const start = hrtime1[0] * 1e9 + hrtime1[1]

    const { symbol, time } = candle;
    if (typeof arrayOhlc[symbol] === 'undefined') arrayOhlc[symbol] = []

    //Get the bunch of candles currently stored
    const candles = arrayOhlc[symbol];

    //Get the last candle if available
    const lastCandle = candles[candles.length - 1] || {};

    // Add a new entry for the newly arrived candle if it has a different timestamp from the latest one we storeds
    if (time !== lastCandle.time) {

    //If our newly arrived candle has the same timestamp as the last stored candle, update the last stored candle
    else {
        candles[candles.length - 1] = candle

    if (candles.length > limit) {
        candles.splice(0, candles.length - limit);

    //measure the end time in nano seocnds
    const hrtime2 = process.hrtime()
    const end = hrtime2[0] * 1e9 + hrtime2[1]

    console.log("Storing as array", end - start, arrayOhlc[symbol].length)

Conclusion 10 is the limit here

Storing as objects 4183 nanoseconds 10
Storing as array 373 nanoseconds 10

/usr/lib/ version `GLIBCXX_3.4.15' not found

Same thing with gcc version 4.8.1 (GCC) and Had to copy it here /usr/lib/x86_64-linux-gnu on my ubuntu box.

Is there a decorator to simply cache function return values?

There is yet another example of a memoize decorator at Python Wiki:

That example is a bit smart, because it won't cache the results if the parameters are mutable. (check that code, it's very simple and interesting!)

Calling UserForm_Initialize() in a Module

IMHO the method UserForm_Initialize should remain private bacause it is event handler for Initialize event of the UserForm.

This event handler is called when new instance of the UserForm is created. In this even handler u can initialize the private members of UserForm1 class.


Standard module code:

Option Explicit

Public Sub Main()
  Dim myUserForm As UserForm1

  Set myUserForm = New UserForm1

End Sub

User form code:

Option Explicit

Private m_initializationDate As Date

Private Sub UserForm_Initialize()
  m_initializationDate = VBA.DateTime.Date
  MsgBox "Hi from UserForm_Initialize event handler.", vbInformation
End Sub

Git: How to remove remote origin from Git repo

Another method

Cancel local git repository

rm -rf .git

Then; Create git repostory again

git init

Then; Repeat the remote repo connect

git remote add origin REPO_URL

EventListener Enter Key

Here is a version of the currently accepted answer (from @Trevor) with key instead of keyCode:

document.querySelector('#txtSearch').addEventListener('keypress', function (e) {
    if (e.key === 'Enter') {
      // code for enter

How to pass a URI to an intent?

The Uri.parse(extras.getString("imageUri")) was causing an error:

java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Intent android.content.Intent.putExtra(java.lang.String, android.os.Parcelable)' on a null object reference 

So I changed to the following:

intent.putExtra("imageUri", imageUri)


Uri uri = (Uri) getIntent().get("imageUri");

This solved the problem.

Redirect website after certain amount of time

Here's a complete (yet simple) example of redirecting after X seconds, while updating a counter div:

    <div id="counter">5</div>_x000D_
        setInterval(function() {_x000D_
            var div = document.querySelector("#counter");_x000D_
            var count = div.textContent * 1 - 1;_x000D_
            div.textContent = count;_x000D_
            if (count <= 0) {_x000D_
        }, 1000);_x000D_

The initial content of the counter div is the number of seconds to wait.

Convert the first element of an array to a string in PHP

You can use the reset() function, it will return the first array member.

I keep getting "Uncaught SyntaxError: Unexpected token o"

Looks like jQuery takes a guess about the datatype. It does the JSON parsing even though you're not calling getJSON()-- then when you try to call JSON.parse() on an object, you're getting the error.

Further explanation can be found in Aditya Mittal's answer.

how to call an ASP.NET c# method using javascript

There are several options. You can use the WebMethod attribute, for your purpose.

Execute a shell function with timeout

This one liner will exit your Bash session after 10s

$ TMOUT=10 && echo "foo bar"

here-document gives 'unexpected end of file' error

Along with the other answers mentioned by Barmar and Joni, I've noticed that I sometimes have to leave a blank line before and after my EOF when using <<-EOF.

How do I clone a Django model instance object and save it to the database?

Use the below code :

from django.forms import model_to_dict

instance = Some.objects.get(slug='something')

kwargs = model_to_dict(instance, exclude=['id'])
new_instance = Some.objects.create(**kwargs)

Finding even or odd ID values

dividend % divisor

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

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

SELECT 15 % 2


Dividend = 15

Divisor = 2

Let's say you wanted to query

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

Schema structure for STATION:

ID Number

CITY varchar

STATE varchar

select CITY from STATION as st where % 2 = 0

Will fetch the even set of records 

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

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

% function reduces the value to either 0 or 1

How to prevent going back to the previous activity?

Just override the onKeyDown method and check if the back button was pressed.

public boolean onKeyDown(int keyCode, KeyEvent event) 
    if (keyCode == KeyEvent.KEYCODE_BACK) 
        //Back buttons was pressed, do whatever logic you want

    return false;

Can't import Numpy in Python

Disabling pyright worked perfectly for me on VS.

Turn off enclosing <p> tags in CKEditor 3.0

In VS2015, this worked to turn the Enter key into <br>

myCKEControl.EnterMode = CKEditor.NET.EnterMode.BR

Personally, I don't care if my resulting text only has <br> and not <p>. It renders perfectly fine and it looks the way I want it to. In the end, it works.

How to convert between bytes and strings in Python 3?





Here 'StringVariable' represented as a string. 'ByteVariable' represent as Byte. Its not relevent to question Variables..

How can I convert spaces to tabs in Vim or Linux?

Changes all spaces to tab :%s/\s/\t/g

How to find keys of a hash?

you can use Object.keys


How to allow all Network connection types HTTP and HTTPS in Android (9) Pie?

You may check if you are sending clearText through HTTP Fix :
In the Case of Apache HTTP client deprecation (From Google ) : With Android 6.0, we removed support for the Apache HTTP client. Beginning with Android 9, that library is removed from the bootclasspath and is not available to apps by default. To continue using the Apache HTTP client, apps that target Android 9 and above can add the following to their AndroidManifest.xml:


Removing element from array in component state

You could use the update() immutability helper from react-addons-update, which effectively does the same thing under the hood, but what you're doing is fine.

this.setState(prevState => ({
  data: update(, {$splice: [[index, 1]]})

Spring: how do I inject an HttpServletRequest into a request-scoped bean?

Spring exposes the current HttpServletRequest object (as well as the current HttpSession object) through a wrapper object of type ServletRequestAttributes. This wrapper object is bound to ThreadLocal and is obtained by calling the static method RequestContextHolder.currentRequestAttributes().

ServletRequestAttributes provides the method getRequest() to get the current request, getSession() to get the current session and other methods to get the attributes stored in both the scopes. The following code, though a bit ugly, should get you the current request object anywhere in the application:

HttpServletRequest curRequest = 
((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())

Note that the RequestContextHolder.currentRequestAttributes() method returns an interface and needs to be typecasted to ServletRequestAttributes that implements the interface.

Spring Javadoc: RequestContextHolder | ServletRequestAttributes

Format a Go string without printing?

Sprintf is what you are looking for.


fmt.Sprintf("foo: %s", bar)

You can also see it in use in the Errors example as part of "A Tour of Go."

return fmt.Sprintf("at %v, %s", e.When, e.What)

PostgreSQL: how to convert from Unix epoch to date?

select to_timestamp(cast(epoch_ms/1000 as bigint))::date

worked for me

Command Line Tools not working - OS X El Capitan, Sierra, High Sierra, Mojave

I had the same issue after upgrading to macOS Catalina. This didn't work for me:

xcode-select --install

Downloading and installing Command Line Tools for Xcode 12 did it!

enter image description here

Getting the last revision number in SVN?

Someone else beat me to posting the answer about svnversion, which is definitely the best solution if you have a working copy (IIRC, it doesn't work with URLs). I'll add this: if you're on the server hosting SVN, the best way is to use the svnlook command. This is the command you use when writing a hook script to inspect the repository (and even the current transaction, in the case of pre-commit hooks). You can type svnlook help for details. You probably want to use the svnlook youngest command. Note that it requires direct access to the repo directory, so it must be used on the server.

Adding onClick event dynamically using jQuery

try this approach if you know your object client name ( it is not important that it is Button or TextBox )

$('#ButtonName').attr('onClick', 'FunctionName(this);');

try this ones if you want add onClick event to a server object with JQuery

$('#' + '<%= ButtonName.ClientID %>').removeAttr('onclick');
$('#' + '<%= ButtonName.ClientID %>').attr('onClick', 'FunctionName(this);');

XSS prevention in JSP/Servlet web application

The how-to-prevent-xss has been asked several times. You will find a lot of information in StackOverflow. Also, OWASP website has an XSS prevention cheat sheet that you should go through.

On the libraries to use, OWASP's ESAPI library has a java flavour. You should try that out. Besides that, every framework that you use has some protection against XSS. Again, OWASP website has information on most popular frameworks, so I would recommend going through their site.

MySQL JOIN with LIMIT 1 on joined table

Assuming you want product with MIN()imial value in sort column, it would look something like this.

SELECT, c.title, AS product_id, p.title
  categories AS c
  SELECT, p.category_id, p.title
    products AS p
    SELECT p.category_id, MIN(sort) AS sort
    FROM products
    GROUP BY category_id
  ) AS sq USING (category_id)
) AS p ON = p.category_id

Is it valid to define functions in JSON results?


JSON is purely meant to be a data description language. As noted on, it is a "lightweight data-interchange format." - not a programming language.

Per, the "basic types" supported are:

  • Number (integer, real, or floating point)
  • String (double-quoted Unicode with backslash escaping)
  • Boolean (true and false)
  • Array (an ordered sequence of values, comma-separated and enclosed in square brackets)
  • Object (collection of key:value pairs, comma-separated and enclosed in curly braces)
  • null

How do you convert a byte array to a hexadecimal string, and vice versa?

I suspect the speed of this will knock the socks off most of the other tests...

Public Function BufToHex(ByVal buf() As Byte) As String
    Dim sB As New System.Text.StringBuilder
    For i As Integer = 0 To buf.Length - 1
    Next i
    Return sB.ToString
End Function

How to remove a key from Hash and get the remaining hash in Ruby/Rails?

This is a one line way to do it, but it's not very readable. Recommend using two lines instead.

use_remaining_hash_for_something( { hash.delete(:key); hash }.call)

How to process POST data in Node.js?

A lot of answers here are not good practices anymore or don't explain anything, so that's why I'm writing this.


When the callback of http.createServer is called, is when the server have actually received all the headers for the request, but it's possible that the data have not been received yet, so we have to wait for it. The http request object(a http.IncomingMessage instance) is actually a readable stream. In readable streams whenever a chunk of data arrives, a data event is emitted(assuming you have registered a callback to it) and when all chunks have arrived an end event is emitted. Here's an example on how you listen to the events:

http.createServer((request, response) => {
  console.log('Now we have a http message with headers but no data yet.');
  request.on('data', chunk => {
    console.log('A chunk of data has arrived: ', chunk);
  request.on('end', () => {
    console.log('No more data');

Converting Buffers to Strings

If you try this you will notice the chunks are buffers. If you are not dealing with binary data and need to work with strings instead I suggest use request.setEncoding method which causes the stream emit strings interpreted with the given encoding and handles multi-byte characters properly.

Buffering Chunks

Now you are probably not interested in each chunk by it's own, so in this case probably you want to buffer it like this:

http.createServer((request, response) => {
  const chunks = [];
  request.on('data', chunk => chunks.push(chunk));
  request.on('end', () => {
    const data = Buffer.concat(chunks);
    console.log('Data: ', data);

Here Buffer.concat is used, which simply concatenates all buffers and return one big buffer. You can also use the concat-stream module which does the same:

const http = require('http');
const concat = require('concat-stream');
http.createServer((request, response) => {
  concat(request, data => {
    console.log('Data: ', data);

Parsing Content

If you are trying to accept HTML forms POST submission with no files or handing jQuery ajax calls with the default content type, then the content type is application/x-www-form-urlencoded with uft-8 encoding. You can use the querystring module to de-serialize it and access the properties:

const http = require('http');
const concat = require('concat-stream');
const qs = require('querystring');
http.createServer((request, response) => {
  concat(request, buffer => {
    const data = qs.parse(buffer.toString());
    console.log('Data: ', data);

If your content type is JSON instead, you can simply use JSON.parse instead of qs.parse.

If you are dealing with files or handling multipart content type, then in that case, you should use something like formidable which removes all the pain from dealing with it. Have a look at this other answer of mine where I have posted helpful links and modules for multipart content.


If you don't want to parse the content but rather pass it to somewhere else, for example send it to another http request as the data or save it to a file I suggest piping it rather than buffering it, as it'll be less code, handles back pressure better, it'll take less memory and in some cases faster.

So if you want to save the content to a file:

 http.createServer((request, response) => {

Limiting the Amount of Data

As other answers have noted keep in my mind that malicious clients might send you a huge amount of data to crash your application or fill your memory so to protect that make sure you drop requests which emit data pass a certain limit. If you don't use a library to handle the incoming data. I would suggest using something like stream-meter which can abort the request if reaches the specified limit:

limitedStream = request.pipe(meter(1e7));
limitedStream.on('data', ...);
limitedStream.on('end', ...);




concat(request.pipe(meter(1e7)), ...);

NPM Modules

While I described above on how you can use the HTTP request body, for simply buffering and parsing the content, I suggesting using one of these modules rather implementing on your own as they will probably handle edge cases better. For express I suggest using body-parser. For koa, there's a similar module.

If you don't use a framework, body is quite good.

SQL Server: Get data for only the past year

For some reason none of the results above worked for me.

This selects the last 365 days.


Return Bit Value as 1/0 and NOT True/False in SQL Server

This can be changed to 0/1 through using CASE WHEN like this example:

 CASE WHEN SchemaName.TableName.BitFieldName = 'true' THEN 1 ELSE 0 END AS 'bit Value' 
 FROM SchemaName.TableName

Error CS2001: Source file '.cs' could not be found

In my case, I add file as Link from another project and then rename file in source project that cause problem in destination project. I delete linked file in destination and add again with new name.

jQuery validate: How to add a rule for regular expression validation?

You may use pattern defined in the additional-methods.js file. Note that this additional-methods.js file must be included after jQuery Validate dependency, then you can just use

    rules: {_x000D_
        Textbox: {_x000D_
            pattern: /^[a-zA-Z'.\s]{1,40}$/_x000D_
    messages: {_x000D_
        Textbox: {_x000D_
            pattern: 'The Textbox string format is invalid'_x000D_
<script src=""></script>_x000D_
<script src=""></script>_x000D_
<script src=""></script>_x000D_
<form id="frm" method="get" action="">_x000D_
            <label for="fullname">Textbox</label>_x000D_
            <input id="Textbox" name="Textbox" type="text">_x000D_

How to create a custom exception type in Java?

You should be able to create a custom exception class that extends the Exception class, for example:

class WordContainsException extends Exception
      // Parameterless Constructor
      public WordContainsException() {}

      // Constructor that accepts a message
      public WordContainsException(String message)


     if(word.contains(" "))
          throw new WordContainsException();
catch(WordContainsException ex)
      // Process message however you would like

How can I use nohup to run process as a background process in linux?

In general, I use nohup CMD & to run a nohup background process. However, when the command is in a form that nohup won't accept then I run it through bash -c "...".

For example:

nohup bash -c "(time ./script arg1 arg2 > script.out) &> time_n_err.out" &

stdout from the script gets written to script.out, while stderr and the output of time goes into time_n_err.out.

So, in your case:

nohup bash -c "(time bash executeScript 1 input fileOutput > scrOutput) &> timeUse.txt" &

How to return only 1 row if multiple duplicate rows and still return rows that are not duplicates?

select * from temptable
where rnum --unique key

 SELECT RNUM --unique key
  FROM temptable
 WHERE (  HistoryStatus
) IN (SELECT                HistoryStatus

                             FROM temptable
                            GROUP BY                
                           HAVING COUNT(*) <= 1));

I have not tested this code. I have used similar code and it works. The syntax is in Oracle.

How to select and change value of table cell with jQuery?

Using eq() you can target the third cell in the table:

$('#table_header td').eq(2).html('new content');

If you wanted to target every third cell in each row, use the nth-child-selector:

$('#table_header td:nth-child(3)').html('new content');

Maximum value of maxRequestLength?

Maximum is 2097151, If you try set more error occurred.

Install a module using pip for specific python version

Have tried this on a Windows machine and it works

If you wanna install opencv for python version 3.7, heres how you do it!

py -3.7 -m pip install opencv-python

What is the difference between Release and Debug modes in Visual Studio?

Debug and Release are just labels for different solution configurations. You can add others if you want. A project I once worked on had one called "Debug Internal" which was used to turn on the in-house editing features of the application. You can see this if you go to Configuration Manager... (it's on the Build menu). You can find more information on MSDN Library under Configuration Manager Dialog Box.

Each solution configuration then consists of a bunch of project configurations. Again, these are just labels, this time for a collection of settings for your project. For example, our C++ library projects have project configurations called "Debug", "Debug_Unicode", "Debug_MT", etc.

The available settings depend on what type of project you're building. For a .NET project, it's a fairly small set: #defines and a few other things. For a C++ project, you get a much bigger variety of things to tweak.

In general, though, you'll use "Debug" when you want your project to be built with the optimiser turned off, and when you want full debugging/symbol information included in your build (in the .PDB file, usually). You'll use "Release" when you want the optimiser turned on, and when you don't want full debugging information included.

REST API Token-based Authentication

A pure RESTful API should use the underlying protocol standard features:

  1. For HTTP, the RESTful API should comply with existing HTTP standard headers. Adding a new HTTP header violates the REST principles. Do not re-invent the wheel, use all the standard features in HTTP/1.1 standards - including status response codes, headers, and so on. RESTFul web services should leverage and rely upon the HTTP standards.

  2. RESTful services MUST be STATELESS. Any tricks, such as token based authentication that attempts to remember the state of previous REST requests on the server violates the REST principles. Again, this is a MUST; that is, if you web server saves any request/response context related information on the server in attempt to establish any sort of session on the server, then your web service is NOT Stateless. And if it is NOT stateless it is NOT RESTFul.

Bottom-line: For authentication/authorization purposes you should use HTTP standard authorization header. That is, you should add the HTTP authorization / authentication header in each subsequent request that needs to be authenticated. The REST API should follow the HTTP Authentication Scheme standards.The specifics of how this header should be formatted are defined in the RFC 2616 HTTP 1.1 standards – section 14.8 Authorization of RFC 2616, and in the RFC 2617 HTTP Authentication: Basic and Digest Access Authentication.

I have developed a RESTful service for the Cisco Prime Performance Manager application. Search Google for the REST API document that I wrote for that application for more details about RESTFul API compliance here. In that implementation, I have chosen to use HTTP "Basic" Authorization scheme. - check out version 1.5 or above of that REST API document, and search for authorization in the document.

Determine which MySQL configuration file is being used

I am on Windows and I have installed the most recent version of MySQL community 5.6

What I did to see what configuration file uses was to go to Administrative Tools > Services > MySQL56 > Right click > Properties and check the path to executable:

"C:/Program Files/MySQL/MySQL Server 5.6/bin\mysqld" --defaults-file="C:\ProgramData\MySQL\MySQL Server 5.6\my.ini" MySQL56

Android get Current UTC time

System.currentTimeMillis() does give you the number of milliseconds since January 1, 1970 00:00:00 UTC. The reason you see local times might be because you convert a Date instance to a string before using it. You can use DateFormats to convert Dates to Strings in any timezone:

DateFormat df = DateFormat.getTimeInstance();
String gmtTime = df.format(new Date());

Also see this related question.

How to exit a 'git status' list in a terminal?

If you are facing this?

enter image description here Sometimes it is possible that while writing in Gitbash you get into > and you just can not get out of that.
It happens with me quite often while I type ' by mistake in Gitbash(See in the image).

How to solve this in Mac?

control + C

I have not checked it in Windows. But if it does please edit that in my answer.

How to remove package using Angular CLI?

I don't know about CLI, I had tried, but I couldn't. I deleted using IDE Idea history.

If You use an Intellij Idea, just open History changes.

Tap by main folder of the project -> right click -> local history -> show history.

Then from top to bottom revert changes.

enter image description here

It should help! Good luck!=)

Oracle: SQL query that returns rows with only numeric values

If you use Oracle 10 or higher you can use regexp functions as codaddict suggested. In earlier versions translate function will help you:

select * from tablename  where translate(x, '.1234567890', '.') is null;

More info about Oracle translate function can be found here or in official documentation "SQL Reference"

UPD: If you have signs or spaces in your numbers you can add "+-" characters to the second parameter of translate function.

How do you connect localhost in the Android emulator?

Thanks to author of this blog:

Defining network security config in xml

    <domain-config cleartextTrafficPermitted="true">
       <domain includeSubdomains="true"></domain>

And setting it on AndroidManifest.xml


Solved issue for me!

Please refer:

NotificationCompat.Builder deprecated in Android O

Simple Sample

    public void showNotification (String from, String notification, Intent intent) {
        PendingIntent pendingIntent = PendingIntent.getActivity(

        String NOTIFICATION_CHANNEL_ID = "my_channel_id_01";
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_DEFAULT);

            // Configure the notification channel.
            notificationChannel.setDescription("Channel description");
            notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});

        NotificationCompat.Builder builder = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID);
        Notification mNotification = builder

//                .setTicker("Hearty365")
//                .setContentInfo("Info")
                //     .setPriority(Notification.PRIORITY_MAX)


//                .setDefaults(Notification.DEFAULT_ALL)
//                .setWhen(System.currentTimeMillis())
                .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher))

        notificationManager.notify(/*notification id*/Notification_ID, mNotification);


How does one target IE7 and IE8 with valid CSS?

For a more complete list as of 2015:

IE 6

* html .ie6 {property:value;}


.ie6 { _property:value;}

IE 7

*+html .ie7 {property:value;}


*:first-child+html .ie7 {property:value;}

IE 6 and 7

@media screen\9 {
    .ie67 {property:value;}


.ie67 { *property:value;}


.ie67 { #property:value;}

IE 6, 7 and 8

@media \0screen\,screen\9 {
    .ie678 {property:value;}

IE 8

html>/**/body .ie8 {property:value;}


@media \0screen {
    .ie8 {property:value;}

IE 8 Standards Mode Only

.ie8 { property /*\**/: value\9 }

IE 8,9 and 10

@media screen\0 {
    .ie8910 {property:value;}

IE 9 only

@media screen and (min-width:0) and (min-resolution: .001dpcm) { 
 // IE9 CSS

IE 9 and above

@media screen and (min-width:0) and (min-resolution: +72dpi) {
  // IE9+ CSS

IE 9 and 10

@media screen and (min-width:0) {

IE 10 only

_:-ms-lang(x), .ie10 { property:value\9; }

IE 10 and above

_:-ms-lang(x), .ie10up { property:value; }


@media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {

IE 11 (and above..)

_:-ms-fullscreen, :root .ie11up { property:value; }

Javascript alternatives


Modernizr runs quickly on page load to detect features; it then creates a JavaScript object with the results, and adds classes to the html element

User agent selection

The Javascript:

var b = document.documentElement;
        b.setAttribute('data-useragent',  navigator.userAgent);
        b.setAttribute('data-platform', navigator.platform );
        b.className += ((!!('ontouchstart' in window) || !!('onmsgesturechange' in window))?' touch':'');

Adds (e.g) the below to the html element:

data-useragent='Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C)'

Allowing very targetted CSS selectors, e.g.:

html[data-useragent*='Chrome/13.0'] .nav{
    background:url(img/radial_grad.png) center bottom no-repeat;


If possible, avoid browser targeting. Identify and fix any issue(s) you identify. Support progressive enhancement and graceful degradation. With that in mind, this is an 'ideal world' scenario not always obtainable in a production environment, as such- the above should help provide some good options.

Attribution / Essential Reading

How to find the extension of a file in C#?

At the server you can check the MIME type, lookup flv mime type here or on google.

You should be checking that the mime type is


If you were using a FileUpload in C# for instance, you could do

FileUpload.PostedFile.ContentType == "video/x-flv"

How to properly highlight selected item on RecyclerView?

As noted in this linked question, setting listeners for viewHolders should be done in onCreateViewHolder. That said, the implementation below was originally aimed at multiple selection, but I threw a hack in the snippet to force single selection.(*1)

// an array of selected items (Integer indices) 
private final ArrayList<Integer> selected = new ArrayList<>();

// items coming into view
public void onBindViewHolder(final ViewHolder holder, final int position) {
    // each time an item comes into view, its position is checked
    // against "selected" indices
    if (!selected.contains(position)){
        // view not selected
        // view is selected

// selecting items
public boolean onLongClick(View v) {
        // select (set color) immediately.

        // (*1)
        // forcing single selection here...
        if (selected.isEmpty()){
            selected.add(position); // (done - see note)
        }else {
            int oldSelected = selected.get(0);
            selected.clear(); // (*1)... and here.
            // note: We do not notify that an item has been selected
            // because that work is done here.  We instead send
            // notifications for items which have been deselected.
        return false;

Can VS Code run on Android?

I don't agree with the accepted answer that the lack of electron prevents VSC on Android.

Electron is really the desktop equivelent of projects like Apache Cordova or Adobe PhoneGap (but Electron is much less efficient and will presumably give way to solutions much closer to Cordova/PhoneGap when possible - it is already being worked on eg. here.)

API's would need to be mapped from their electron equivelents, and many of the plug-ins will have their own issues (but Android is reasonably flexible about allowing stuff like Python compared to iOS) so it is doable.

On the other hand, the demand for an Android version of VSC probably comes from people using the new Chromebooks that support Android, and there is already a solution for ChromeOS using crouton, available here.

Bootstrap: Collapse other sections when one is expanded

On Bootstrap5

Like noticed in the docu you can use the "data-bs-parent=.." attribute

If parent is provided, then all collapsible elements under the specified parent will be closed when this collapsible item is shown. (similar to traditional accordion behavior - this is dependent on the card class). The attribute has to be set on the target collapsible area.

see more in bootstrap5 docu

Static variable inside of a function in C

There are two issues here, lifetime and scope.

The scope of variable is where the variable name can be seen. Here, x is visible only inside function foo().

The lifetime of a variable is the period over which it exists. If x were defined without the keyword static, the lifetime would be from the entry into foo() to the return from foo(); so it would be re-initialized to 5 on every call.

The keyword static acts to extend the lifetime of a variable to the lifetime of the programme; e.g. initialization occurs once and once only and then the variable retains its value - whatever it has come to be - over all future calls to foo().

Convert an ISO date to the date format yyyy-mm-dd in JavaScript


new Date().toISOString().substring(0, 10);

NameError: name 'python' is not defined

When you run the Windows Command Prompt, and type in python, it starts the Python interpreter.

Typing it again tries to interpret python as a variable, which doesn't exist and thus won't work:

Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> python
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'python' is not defined
>>> print("interpreter has started")
interpreter has started
>>> quit() # leave the interpreter, and go back to the command line


If you're not doing this from the command line, and instead running the Python interpreter (python.exe or IDLE's shell) directly, you are not in the Windows Command Line, and python is interpreted as a variable, which you have not defined.

How do you create different variable names while in a loop?

It's simply pointless to create variable variable names. Why?

  • They are unnecessary: You can store everything in lists, dictionarys and so on
  • They are hard to create: You have to use exec or globals()
  • You can't use them: How do you write code that uses these variables? You have to use exec/globals() again

Using a list is much easier:

# 8 strings: `Hello String 0, .. ,Hello String 8`
strings = ["Hello String %d" % x for x in range(9)]
for string in strings: # you can loop over them
    print string
print string[6] # or pick any of them

Printing Batch file results to a text file

Step 1: Simply put all the required code in a "MAIN.BAT" file.

Step 2: Create another bat file, say MainCaller.bat, and just copy/paste these 3 lines of code:

CD "File_Path_Where_Main.bat_is_located"
MAIN.BAT > log.txt

Step 3: Just double click "MainCaller.bat".

All the output will be logged into the text file named "log".

How to compare two List<String> to each other?

I discovered that SequenceEqual is not the most efficient way to compare two lists of strings (initially from

I wanted to test this myself so I created two methods:

    /// <summary>
    /// Compares two string lists using LINQ's SequenceEqual.
    /// </summary>
    public bool CompareLists1(List<string> list1, List<string> list2)
        return list1.SequenceEqual(list2);

    /// <summary>
    /// Compares two string lists using a loop.
    /// </summary>
    public bool CompareLists2(List<string> list1, List<string> list2)
        if (list1.Count != list2.Count)
            return false;

        for (int i = 0; i < list1.Count; i++)
            if (list1[i] != list2[i])
                return false;

        return true;

The second method is a bit of code I encountered and wondered if it could be refactored to be "easier to read." (And also wondered if LINQ optimization would be faster.)

As it turns out, with two lists containing 32k strings, over 100 executions:

  • Method 1 took an average of 6761.8 ticks
  • Method 2 took an average of 3268.4 ticks

I usually prefer LINQ for brevity, performance, and code readability; but in this case I think a loop-based method is preferred.


I recompiled using optimized code, and ran the test for 1000 iterations. The results still favor the loop (even more so):

  • Method 1 took an average of 4227.2 ticks
  • Method 2 took an average of 1831.9 ticks

Tested using Visual Studio 2010, C# .NET 4 Client Profile on a Core i7-920

How can I render HTML from another file in a React component?

It is common to have components that are only rendering from props. Like this:

class Template extends React.Component{
  render (){
    return <div>this.props.something</div>

Then in your upper level component where you have the logic you just import the Template component and pass the needed props. All your logic stays in the higher level component, and the Template only renders. This is a possible way to achieve 'templates' like in Angular.

There is no way to have .jsx file with jsx only and use it in React because jsx is not really html but markup for a virtual DOM, which React manages.

getting a checkbox array value from POST

I just used the following code:

<form method="post">
    <input id="user1" value="user1"  name="invite[]" type="checkbox">
    <input id="user2" value="user2"  name="invite[]" type="checkbox">
    <input type="submit">

        $invite = $_POST['invite'];

When I checked both boxes, the output was:

Array ( [0] => user1 [1] => user2 )

I know this doesn't directly answer your question, but it gives you a working example to reference and hopefully helps you solve the problem.

How do I copy a 2 Dimensional array in Java?

current=old or old=current makes the two array refer to the same thing, so if you subsequently modify current, old will be modified too. To copy the content of an array to another array, use the for loop

for(int i=0; i<old.length; i++)
  for(int j=0; j<old[i].length; j++)

PS: For a one-dimensional array, you can avoid creating your own for loop by using Arrays.copyOf

Does a `+` in a URL scheme/host/path represent a space?

Thou shalt always encode URLs.

Here is how Ruby encodes your URL:

irb(main):008:0> CGI.escape ""
=> ""

How to determine whether an object has a given property in JavaScript

One feature of my original code

if ( typeof(x.y) != 'undefined' ) ...

that might be useful in some situations is that it is safe to use whether x exists or not. With either of the methods in gnarf's answer, one should first test for x if there is any doubt if it exists.

So perhaps all three methods have a place in one's bag of tricks.

Check if a string is not NULL or EMPTY

if (-not ([string]::IsNullOrEmpty($version)))
    $request += "/" + $version

You can also use ! as an alternative to -not.

JavaScript before leaving the page

Just a bit more helpful, enable and disable

$(window).on('beforeunload.myPluginName', false); // or use function() instead of false

Python SQLite: database is locked

  1. Your cache.db is being currently used by another process.
  2. Stop that process and try again, it should work.

String delimiter in string.split method

String[] strArray= str.split(Pattern.quote("||"));


  1. str = "1||1||Abdul-Jabbar||Karim||1996||1974";
  2. Pattern.quote("||") will ignore the special character.
  3. .split function will split the string for every occurrence of ||.
  4. strArray will have the array of string that is delimited by ||.

How to use ConcurrentLinkedQueue?

Use poll to get the first element, and add to add a new last element. That's it, no synchronization or anything else.

Which programming languages can be used to develop in Android?

Here's a list of languages that can be used to develop on android:

  • Java - primary android development language

  • Kotlin, language from JetBrains which received first-party support from Google, announced in Google I/O 2017

  • C++ - NDK for libraries, not apps

  • Python, bash, et. al. - Via the Scripting Environment

  • Corona- One is to use the Corona SDK . Corona is a high level SDK built on the Lua programming language. Lua is much simpler to learn than Java and the SDK takes away a lot of the pain in developing Android app.

  • Cordova - which uses HTML5, JavaScript, CSS, and can be extended with Java

  • Xamarin technology - that uses c# and in which mono is used for that. Here MonoTouch and Mono for Android are cross-platform implementations of the Common Language Infrastructure (CLI) and Common Language Specifications.

As for your second question: android is highly dependent on it's java architecture, I find it unlikely that there will be other primary development languages available any time soon. However, there's no particular reason why someone couldn't implement another language in Java (something like Jython) and use that. However, that surely won't be easier or as performant as just writing the code in Java.

JavaScript get clipboard data on paste event (Cross browser)

The situation has changed since writing this answer: now that Firefox has added support in version 22, all major browsers now support accessing the clipboard data in a paste event. See Nico Burns's answer for an example.

In the past this was not generally possible in a cross-browser way. The ideal would be to be able to get the pasted content via the paste event, which is possible in recent browsers but not in some older browsers (in particular, Firefox < 22).

When you need to support older browsers, what you can do is quite involved and a bit of a hack that will work in Firefox 2+, IE 5.5+ and WebKit browsers such as Safari or Chrome. Recent versions of both TinyMCE and CKEditor use this technique:

  1. Detect a ctrl-v / shift-ins event using a keypress event handler
  2. In that handler, save the current user selection, add a textarea element off-screen (say at left -1000px) to the document, turn designMode off and call focus() on the textarea, thus moving the caret and effectively redirecting the paste
  3. Set a very brief timer (say 1 millisecond) in the event handler to call another function that stores the textarea value, removes the textarea from the document, turns designMode back on, restores the user selection and pastes the text in.

Note that this will only work for keyboard paste events and not pastes from the context or edit menus. By the time the paste event fires, it's too late to redirect the caret into the textarea (in some browsers, at least).

In the unlikely event that you need to support Firefox 2, note that you'll need to place the textarea in the parent document rather than the WYSIWYG editor iframe's document in that browser.

Fastest way to Remove Duplicate Value from a list<> by lambda

There is Distinct() method. it should works.

List<long> longs = new List<long> { 1, 2, 3, 4, 3, 2, 5 };
var distinctList = longs.Distinct().ToList();

How to align form at the center of the page in html/css

Or you can just use the <center></center> tags.

Why a function checking if a string is empty always returns true?

PHP have a built in function called empty() the test is done by typing if(empty($string)){...} Reference : php empty