Programs & Examples On #Fixup

Forward X11 failed: Network error: Connection refused

PuTTY can't find where your X server is, because you didn't tell it. (ssh on Linux doesn't have this problem because it runs under X so it just uses that one.) Fill in the blank box after "X display location" with your Xming server's address.

Alternatively, try MobaXterm. It has an X server builtin.

Various ways to remove local Git changes

First of all check is your important change saved or not by:

$ git status

than try

$ git reset --hard

it will reset your branch to default

but if you need just undo:

$ edit (1) $ git add frotz.c filfre.c $ mailx (2) $ git reset
(3) $ git pull git:// nitfol


Why call git branch --unset-upstream to fixup?

torek's answer is probably perfect, but I just wanted for the record to mention another case which is different than the one described in the original question but the same error may appear (as it may help others with similar problem):

I have created an empty (new) repo using git init --bare on one of my servers. Then I have git cloned it to a local workspace on my PC.

After committing a single version on the local repo I got that error after calling git status.

Following torek's answer, I understand that what happened is that the first commit on local working directory repo created "master" branch. But on the remote repo (on the server) there was never anything, so there was not even a "master" (remotes/origin/master) branch.

After running git push origin master from local repo the remote repo finally had a master branch. This stopped the error from appearing.

So to conclude - one may get such an error for a fresh new remote repo with zero commits since it has no branch, including "master".

How to close off a Git Branch?

after complete the code first merge branch to master then delete that branch

git checkout master
git merge <branch-name>
git branch -d <branch-name>

How to determine the current language of a wordpress page when using polylang?


Returns the current language


pll_current_language( $value ); 
  • $value => (optional) either name or locale or slug, defaults to slug

returns either the full name, or the WordPress locale (just as the WordPress core function ‘get_locale’ or the slug ( 2-letters code) of the current language.

How add spaces between Slick carousel item

simply add padding on to the slick-side class will do

.slick-slider .slick-slide {
  padding: 0 15px;

Storing Objects in HTML5 localStorage

Another option would be to use an existing plugin.

For example persisto is an open source project that provides an easy interface to localStorage/sessionStorage and automates persistence for form fields (input, radio buttons, and checkboxes).

persisto features

(Disclaimer: I am the author.)

jQuery removing '-' character from string

var string = $mylabel.text().replace('-', '');

if you have done it that way variable string now holds "123456"

you can also (i guess the better way) do this...

   return v.replace('-','');

Can we pass model as a parameter in RedirectToAction?

Using TempData

Represents a set of data that persists only from one request to the next

public ActionResult FillStudent(Student student1)
    TempData["student"]= new Student();
    return RedirectToAction("GetStudent","Student");

public ActionResult GetStudent(Student passedStd)
    Student std=(Student)TempData["student"];
    return View();

Alternative way Pass the data using Query string

return RedirectToAction("GetStudent","Student", new {Name="John", Class="clsz"});

This will generate a GET Request like Student/GetStudent?Name=John & Class=clsz

Ensure the method you want to redirect to is decorated with [HttpGet] as the above RedirectToAction will issue GET Request with http status code 302 Found (common way of performing url redirect)

Pass a String from one Activity to another Activity in Android

In ActivityOne,

Intent intent = new Intent(ActivityOne.this, ActivityTwo.class);
intent.putExtra("data", somedata);

In ActivityTwo,

Intent intent = getIntent();
String data = intent.getStringExtra("data");

How to make overlay control above all other controls?

Robert Rossney has a good solution. Here's an alternative solution I've used in the past that separates out the "Overlay" from the rest of the content. This solution takes advantage of the attached property Panel.ZIndex to place the "Overlay" on top of everything else. You can either set the Visibility of the "Overlay" in code or use a DataTrigger.

<Grid x:Name="LayoutRoot">

 <Grid x:Name="Overlay" Panel.ZIndex="1000" Visibility="Collapsed">
      <SolidColorBrush Color="Black" Opacity=".5"/>

    <!-- Add controls as needed -->

  <!-- Use whatever layout you need -->
  <ContentControl x:Name="MainContent" />


Position a div container on the right side

Is this what you wanted? -

Floats on both sides now




<div id="wrapper">
    <div id="c1">con1</div>
    <div id="c2">con2</div>

Keyboard shortcuts with jQuery

I recently wrote a standalone library for this. It does not require jQuery, but you can use it with jQuery no problem. It's called Mousetrap.

You can check it out at

The calling thread must be STA, because many UI components require this

I suspect that you are getting a callback to a UI component from a background thread. I recommend that you make that call using a BackgroundWorker as this is UI thread aware.

For the BackgroundWorker, the main program should be marked as [STAThread].

Incorrect integer value: '' for column 'id' at row 1

This is because your data sending column type is integer and your are sending a string value to it.

So, the following way worked for me. Try with this one.

$insertQuery = "INSERT INTO workorders VALUES (

Don't use 'null'. use it as null without single quotes.

How to embed an autoplaying YouTube video in an iframe?

December 2018,

Looking for an AUTOPLAY, LOOP, MUTE youtube video for react.

Other answers didn't worked.

I found a solution with a library: react-youtube

class Video extends Component {

    _onReady(event) {
        // add mute;
        // add autoplay;

    render() {
        const opts = {
            width: '100%',
            height: '700px',
            playerVars: {
                // remove video controls 
                controls: 0,
                // remove related video
                rel: 0

        return (
                // add autoplay
                // add loop


How do I to insert data into an SQL table using C# as well as implement an upload function?

You should use parameters in your query to prevent attacks, like if someone entered '); drop table ArticlesTBL;--' as one of the values.

string query = "INSERT INTO ArticlesTBL (ArticleTitle, ArticleContent, ArticleType, ArticleImg, ArticleBrief,  ArticleDateTime, ArticleAuthor, ArticlePublished, ArticleHomeDisplay, ArticleViews)";
query += " VALUES (@ArticleTitle, @ArticleContent, @ArticleType, @ArticleImg, @ArticleBrief, @ArticleDateTime, @ArticleAuthor, @ArticlePublished, @ArticleHomeDisplay, @ArticleViews)";

SqlCommand myCommand = new SqlCommand(query, myConnection);
myCommand.Parameters.AddWithValue("@ArticleTitle", ArticleTitleTextBox.Text);
myCommand.Parameters.AddWithValue("@ArticleContent", ArticleContentTextBox.Text);
// ... other parameters

Exploits of a Mom


How can I compare two lists in python and return matches

another a bit more functional way to check list equality for list 1 (lst1) and list 2 (lst2) where objects have depth one and which keeps the order is:

all(i == j for i, j in zip(lst1, lst2))   

Convert txt to csv python script

You need to split the line first.

import csv

with open('log.txt', 'r') as in_file:
    stripped = (line.strip() for line in in_file)
    lines = (line.split(",") for line in stripped if line)
    with open('log.csv', 'w') as out_file:
        writer = csv.writer(out_file)
        writer.writerow(('title', 'intro'))

document.createElement("script") synchronously

I am used to having multiple .js files on my web site that depend one on another. To load them and ensure that the dependencies are evaluated in the right order, I have written a function that loads all the files and then, once they are all received, eval() them. The main drawback is that since this does not work with CDN. For such libraries (e.g., jQuery) it is better to include them statically. Note that inserting script nodes in the HTML dynamically won't guarantee that scripts are evaluated in the right order, at least not in Chrome (this was the major reason for writing this function).

function xhrs(reqs) {
  var requests = [] , count = [] , callback ;

  callback = function (r,c,i) {
    return function () {
      if  ( this.readyState == 4 ) {
        if (this.status != 200 ) {
          r[i]['resp']="" ;
        else {
          r[i]['resp']= this.responseText ;
        c[0] = c[0] - 1 ;
        if ( c[0] == 0 ) {
          for ( var j = 0 ; j < r.length ; j++ ) {
            eval(r[j]['resp']) ;
  } ;
  if ( reqs ) === '[object Array]' ) {
    requests.length = reqs.length ;
  else {
    requests.length = 1 ;
    reqs = [].concat(reqs);
  count[0] = requests.length ;
  for ( var i = 0 ; i < requests.length ; i++ ) {
    requests[i] = {} ;
    requests[i]['xhr'] = new XMLHttpRequest () ;
    requests[i]['xhr'].open('GET', reqs[i]) ;
    requests[i]['xhr'].onreadystatechange = callback(requests,count,i) ;

I haven't figured out how to make references to the same value without creating an array (for count). Otherwise I think it is self-explanatory (when everything is loaded, eval() every file in the order given, otherwise just store the response).

Usage example:

xhrs( [
       root + '/global.js' ,
       window.location.href + 'config.js' ,
       root + '/js/lib/details.polyfill.min.js',
       root + '/js/scripts/address.js' ,
       root + '/js/scripts/tableofcontents.js' 
]) ;

How to find file accessed/created just few minutes ago

If you know the file is in your current directory, I would use:

ls -lt | head

This lists your most recently modified files and directories in order. In fact, I use it so much I have it aliased to 'lh'.

Several ports (8005, 8080, 8009) required by Tomcat Server at localhost are already in use

Your Tomcat is probably running already. That's why you have got an error. I've had the same problem before. I solved it very simply:

  1. Restart your computer
  2. Open Eclipse
  3. Run your Tomcat

That's all.

jquery get height of iframe content when loaded

The less complicated answer is to use .contents() to get at the iframe. Interestingly, though, it returns a different value from what I get using the code in my original answer, due to the padding on the body, I believe.

$('iframe').contents().height() + 'is the height'

This is how I've done it for cross-domain communication, so I'm afraid it's maybe unnecessarily complicated. First, I would put jQuery inside the iFrame's document; this will consume more memory, but it shouldn't increase load time as the script only needs to be loaded once.

Use the iFrame's jQuery to measure the height of your iframe's body as early as possible (onDOMReady) and then set the URL hash to that height. And in the parent document, add an onload event to the iFrame tag that will look at the location of the iframe and extract the value you need. Because onDOMReady will always occur before the document's load event, you can be fairly certain the value will get communicated correctly without a race condition complicating things.

In other words: Help.php:

var getDocumentHeight = function() {
    if (location.hash === '') { // EDIT: this should prevent the retriggering of onDOMReady
        location.hash = $('body').height(); 
        // at this point the document address will be something like help.php#1552

...and in the parent document:

var getIFrameHeight = function() {
    var iFrame = $('iframe')[0]; // this will return the DOM element
    var strHash = iFrame.contentDocument.location.hash;
    alert(strHash); // will return something like '#1552'
$('iframe').bind('load', getIFrameHeight );

Django CSRF check failing with an Ajax POST request

Add this line to your jQuery code:

  data: {csrfmiddlewaretoken: '{{ csrf_token }}' },

and done.

Html table with button on each row

Put a single listener on the table. When it gets a click from an input with a button that has a name of "edit" and value "edit", change its value to "modify". Get rid of the input's id (they aren't used for anything here), or make them all unique.

<script type="text/javascript">

function handleClick(evt) {
  var node = || evt.srcElement;
  if ( == 'edit') {
    node.value = "Modify";


<table id="table1" border="1" onclick="handleClick(event);">
               <form name="f1" action="#" >
                <input id="edit1" type="submit" name="edit" value="Edit">
               <form name="f2" action="#" >
                <input id="edit2" type="submit" name="edit" value="Edit">
               <form name="f3" action="#" >
                <input id="edit3" type="submit" name="edit" value="Edit">


How to re import an updated package while in Python Interpreter?

Not sure if this does all expected things, but you can do just like that:

>>> del mymodule
>>> import mymodule

How to display a date as iso 8601 format with PHP

For pre PHP 5:

function iso8601($time=false) {
    if(!$time) $time=time();
    return date("Y-m-d", $time) . 'T' . date("H:i:s", $time) .'+00:00';

Getting the client's time zone (and offset) in JavaScript

Using an offset to calculate Timezone is a wrong approach, and you will always encounter problems. Time zones and daylight saving rules may change on several occasions during a year, and It's difficult to keep up with changes.

To get the system's IANA timezone in JavaScript, you should use


As of September 2019, this works in 95% of the browsers used globally.

Old compatibility information

ecma-402/1.0 says that timeZone may be undefined if not provided to constructor. However, future draft (3.0) fixed that issue by changing to system default timezone.

In this version of the ECMAScript Internationalization API, the timeZone property will remain undefined if no timeZone property was provided in the options object provided to the Intl.DateTimeFormat constructor. However, applications should not rely on this, as future versions may return a String value identifying the host environment’s current time zone instead.

in ecma-402/3.0 which is still in a draft it changed to

In this version of the ECMAScript 2015 Internationalization API, the timeZone property will be the name of the default time zone if no timeZone property was provided in the options object provided to the Intl.DateTimeFormat constructor. The previous version left the timeZone property undefined in this case.

how to automatically scroll down a html page?

You can use .scrollIntoView() for this. It will bring a specific element into the viewport.


document.getElementById( 'bottom' ).scrollIntoView();



function top() {
    document.getElementById( 'top' ).scrollIntoView();    

function bottom() {
    document.getElementById( 'bottom' ).scrollIntoView();
    window.setTimeout( function () { top(); }, 2000 );



<div id="top">top</div>
<div id="bottom">bottom</div>


#top {
    border: 1px solid black;
    height: 3000px;

#bottom {
    border: 1px solid red;

Python os.path.join on Windows

You have a few possible approaches to treat path on Windows, from the most hardcoded ones (as using raw string literals or escaping backslashes) to the least ones. Here follows a few examples that will work as expected. Use what better fits your needs.

In[1]: from os.path import join, isdir

In[2]: from os import sep

In[3]: isdir(join("c:", "\\", "Users"))
Out[3]: True

In[4]: isdir(join("c:", "/", "Users"))
Out[4]: True

In[5]: isdir(join("c:", sep, "Users"))
Out[5]: True

Javascript change font color

Html code

<div id="coloredBy">
    Colored By Santa

javascript code

document.getElementById("coloredBy").style.color = colorCode; // red or #ffffff

I think this is very easy to use


Just a little tip:

I prefer to use the variant RLIKE (exactly the same command as REGEXP) as it sounds more like natural language, and is shorter; well, just 1 char.

The "R" prefix is for Reg. Exp., of course.

Base64 PNG data to HTML5 canvas

Jerryf's answer is fine, except for one flaw.

The onload event should be set before the src. Sometimes the src can be loaded instantly and never fire the onload event.

(Like Totty.js pointed out.)

var canvas = document.getElementById("c");
var ctx = canvas.getContext("2d");

var image = new Image();
image.onload = function() {
    ctx.drawImage(image, 0, 0);

Java keytool easy way to add server cert from url/port

I use openssl, but if you prefer not to, or are on a system (particularly Windows) that doesn't have it, since java 7 in 2011 keytool can do the whole job:

 keytool -printcert -sslserver host[:port] -rfc >tempfile
 keytool -import [-noprompt] -alias nm -keystore file [-storepass pw] [-storetype ty] <tempfile 
 # or with noprompt and storepass (so nothing on stdin besides the cert) piping works:
 keytool -printcert -sslserver host[:port] -rfc | keytool -import -noprompt -alias nm -keystore file -storepass pw [-storetype ty]

Conversely, for java 9 up always, and for earlier versions in many cases, Java can use a PKCS12 file for a keystore instead of the traditional JKS file, and OpenSSL can create a PKCS12 without any assistance from keytool:

openssl s_client -connect host:port </dev/null | openssl pkcs12 -export -nokeys [-name nm] [-passout option] -out p12file
# <NUL on Windows
# default is to prompt for password, but -passout supports several options 
# including actual value, envvar, or file; see the openssl(1ssl) man page 

Python: Passing variables between functions

Read up the concept of a name space. When you assign a variable in a function, you only assign it in the namespace of this function. But clearly you want to use it between all functions.

def defineAList():
    #list = ['1','2','3'] this creates a new list, named list in the current namespace.
    #same name, different list!

    list.extend['1', '2', '3', '4'] #this uses a method of the existing list, which is in an outer namespace
    print "For checking purposes: in defineAList, list is",list
    return list

Alternatively, you can pass it around:

def main():
    new_list = defineAList()

Drop rows with all zeros in pandas data frame

Another alternative:

# Is there anything in this row non-zero?
# df != 0 --> which entries are non-zero? T/F
# (df != 0).any(axis=1) --> are there 'any' entries non-zero row-wise? T/F of rows that return true to this statement.
# df.loc[all_zero_mask,:] --> mask your rows to only show the rows which contained a non-zero entry.
# df.shape to confirm a subset.

all_zero_mask=(df != 0).any(axis=1) # Is there anything in this row non-zero?

How do I read CSV data into a record array in NumPy?

Using numpy.loadtxt

A quite simple method. But it requires all the elements being float (int and so on)

import numpy as np 
data = np.loadtxt('c:\\1.csv',delimiter=',',skiprows=0)  

How to call Android contacts list?

I do it this way for Android 2.2 Froyo release: basically use eclipse to create a class like: public class SomePickContactName extends Activity

then insert this code. Remember to add the private class variables and CONSTANTS referenced in my version of the code:

protected void onCreate(Bundle savedInstanceState) 
  Intent intentContact = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI); 
  startActivityForResult(intentContact, PICK_CONTACT);

public void onActivityResult(int requestCode, int resultCode, Intent intent) 

  if (requestCode == PICK_CONTACT)
    // Your class variables now have the data, so do something with it. 

protected void getContactInfo(Intent intent)

   Cursor cursor =  managedQuery(intent.getData(), null, null, null, null);      
   while (cursor.moveToNext()) 
       String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
       name = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME)); 

       String hasPhone = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));

       if ( hasPhone.equalsIgnoreCase("1"))
           hasPhone = "true";
           hasPhone = "false" ;

       if (Boolean.parseBoolean(hasPhone)) 
        Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId,null, null);
        while (phones.moveToNext()) 
          phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

       // Find Email Addresses
       Cursor emails = getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,null,ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = " + contactId,null, null);
       while (emails.moveToNext()) 
        emailAddress = emails.getString(emails.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));

    Cursor address = getContentResolver().query(
                ContactsContract.CommonDataKinds.StructuredPostal.CONTACT_ID + " = " + contactId,
                null, null);
    while (address.moveToNext()) 
      // These are all private class variables, don't forget to create them.
      poBox      = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POBOX));
      street     = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET));
      city       = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY));
      state      = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.REGION));
      postalCode = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE));
      country    = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY));
      type       = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.TYPE));
    }  //address.moveToNext()   
  }  //while (cursor.moveToNext())        

How to convert a selection to lowercase or uppercase in Sublime Text

As a bonus for setting up a Title Case shortcut key Ctrl+kt (while holding Ctrl, press k and t), go to Preferences --> Keybindings-User

If you have a blank file open and close with the square brackets:

[  { "keys": ["ctrl+k", "ctrl+t"], "command": "title_case" } ]

Otherwise if you already have stuff in there, just make sure if it comes after another command to prepend a comma "," and add:

{ "keys": ["ctrl+k", "ctrl+t"], "command": "title_case" }

Server http:/localhost:8080 requires a user name and a password. The server says: XDB

This is caused because there is a database running on your computer. In my case, it was an Oracle data base. By default, everytime you start your computer, the services of the database automatically starts.

Go to Start >> find Oracle or whatever data-base in the list of programms >> and manually stop the database. It appears that there is a conflict of port.

How to change the server port from 3000?

1-> Using File Default Config- Angular-cli comes from the ember-cli project. To run the application on specific port, create an .ember-cli file in the project root. Add your JSON config in there:

{ "port": 1337 }

2->Using Command Line Tool Run this command in Angular-Cli

ng serve --port 1234

To change the port number permanently:



Search for var defaultPort = process.env.PORT || 4200; (change 4200 to anything else you want).

Update some specific field of an entity in android Room

I want to know how can I update some field(not all) like method 1 where id = 1

Use @Query, as you did in Method 2.

is too long query in my case because I have many field in my entity

Then have smaller entities. Or, do not update fields individually, but instead have more coarse-grained interactions with the database.

IOW, there is nothing in Room itself that will do what you seek.

UPDATE 2020-09-15: Room now has partial entity support, which can help with this scenario. See this answer for more.

How do I make calls to a REST API using C#?

Here are a few different ways of calling an external API in C# (updated 2019).

.NET's built-in ways:

  • WebRequest& WebClient - verbose APIs & Microsoft's documentation is not very easy to follow
  • HttpClient - .NET's newest kid on the block & much simpler to use than above.

Free, open-source NuGet Packages, which frankly have a much better developer experience than .NET's built in clients:

  • ServiceStack.Text (1,000 GitHub stars, 7 million NuGet downloads) (*) - fast, light and resilient.
  • RestSharp (6,000 GitHub stars, 23 million NuGet downloads) (*) - simple REST and HTTP API Client
  • Flurl (1,700 GitHub stars, 3 million NuGet downloads) (*)- a fluent, portable, testable HTTP client library

All the above packages provide a great developer experience (i.e., concise, easy API) and are well maintained.

(*) as at August 2019

Example: Getting a Todo item from a Fake Rest API using ServiceStack.Text. The other libraries have very similar syntax.

class Program
    static void Main(string[] args)
        // Fake rest API
        string url = "";

        // GET data from API & map to POCO
        var todo =  url.GetJsonFromUrl().FromJson<Todo>();

        // Print the result to screen

    public class Todo
        public int UserId { get; set; }
        public int Id { get; set; }
        public string Title { get; set; }
        public bool Completed { get; set; }


Running the above example in a .NET Core Console app, produces the following output.

Enter image description here

Install these packages using NuGet

Install-Package ServiceStack.Text, or

Install-Package RestSharp, or

Install-Package Flurl.Http

Change the project theme in Android Studio?

In Manifest theme sets with style name (AppTheme and myDialog)/ You can set new styles in styles.xml

            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />

styles.xml example


<!-- Base application theme. -->
<style name="AppTheme" parent="android:Theme.Black">
    <!-- Customize your theme here. -->

<style name="myDialog" parent="android:Theme.Dialog">


In parent you set actualy the theme

Running Composer returns: "Could not open input file: composer.phar"


It is helpful to know that there are two ways to install (and use) Composer: locally as a file in your project directory, or globally as a system-wide executable.

Installing Composer locally simply means that you are downloading a file (composer.phar - which is a PHP Archive) into your project directory. You will have to download it for every project that requires Composer.

Like a regular PHP file that you want to execute on the command line, you will have to run it with PHP:

php composer.phar update

Which basically tells the php executable to run the file composer.phar with update as argument.

However, if you install it globally, you can make composer itself executable, so you can call it without php (and don't have to download it for every project). In other words, you can use composer like this:

composer update

Since you are executing php composer.phar update, and you are getting the error Could not open input file: composer.phar, you probably don't have composer.phar in your current directory.


If you have Composer installed globally, simply run composer update instead of php composer.phar update.

If you don't have Composer installed yet, download the PHAR using the following command:

curl -sS | php

This will download the installer and run it using php. The installer will download the actual Composer PHAR to your current working directory, and make it executable.

To install Composer globally (I recommend this), copy the file to a location in your PATH. The exact location differs per operating system and setup, see for more information.

Personally, I prefer to install Composer in my home directory so I don't need sudo to install or update the composer executable (which can be a security risk). As I'm on Linux, I use the following command:

mv composer.phar ~/.local/bin/composer

How do I give ASP.NET permission to write to a folder in Windows 7?

My immediate solution (since I couldn't find the ASP.NET worker process) was to give write (that is, Modify) permission to IIS_IUSRS. This worked. I seem to recall that in WinXP I had to specifically given the ASP.NET worker process write permission to accomplish this. Maybe my memory is faulty, but anyway...

@DraganRadivojevic wrote that he thought this was dangerous from a security viewpoint. I do not disagree, but since this was my workstation and not a network server, it seemed relatively safe. In any case, his answer is better and is what I finally settled on after chasing down a fail-path due to not specifying the correct domain for the AppPool user.

How to make a new line or tab in <string> XML (eclipse/android)?

add this line at the top of string.xml

<?xml version="1.0" encoding="utf-8"?>

and use


from where you want to break your line.

ex. <string> Hello world. \n its awesome. <string>


Hello world.
its awesome.

SQL Query to concatenate column values from multiple rows in Oracle

Try this code:

 SELECT XMLAGG(XMLELEMENT(E,fieldname||',')).EXTRACT('//text()') "FieldNames"

How to remove leading and trailing white spaces from a given html string?

If you're working with a multiline string, like a code file:


And want to replace all leading lines, to get this result:


You must add the multiline flag to your regex, ^ and $ match line by line:

string.replace(/^\s+|\s+$/gm, '');

Relevant quote from docs:

The "m" flag indicates that a multiline input string should be treated as multiple lines. For example, if "m" is used, "^" and "$" change from matching at only the start or end of the entire string to the start or end of any line within the string.

Can I use Homebrew on Ubuntu?

As of February 2018, installing brew on Ubuntu (mine is 17.10) machine is as simple as:

sudo apt install linuxbrew-wrapper

Then, on first brew execution (just type brew --help) you will be asked for two installation options:

me@computer:~/$ brew --help
==> Select the Linuxbrew installation directory
- Enter your password to install to /home/linuxbrew/.linuxbrew (recommended)
- Press Control-D to install to /home/me/.linuxbrew
- Press Control-C to cancel installation
[sudo] password for me:

For recommended option type your password (if your current user is in sudo group), or, if you prefer installing all the dependencies in your own home folder, hit Ctrl+D. Enjoy.

Currency Formatting in JavaScript

You can use standard JS toFixed method

var num = 5.56789;
var n=num.toFixed(2);


In order to add commas (to separate 1000's) you can add regexp as follows (where num is a number):

num.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")

//100000 => 100,000
//8000 => 8,000
//1000000 => 1,000,000

Complete example:

var value = 1250.223;
var num = '$' + value.toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");

//document.write(num) would write value as follows: $1,250.22

Separation character depends on country and locale. For some countries it may need to be .

How to Correctly Use Lists in R?

Regarding your questions, let me address them in order and give some examples:

1) A list is returned if and when the return statement adds one. Consider

 R> retList <- function() return(list(1,2,3,4)); class(retList())
 [1] "list"
 R> notList <- function() return(c(1,2,3,4)); class(notList())
 [1] "numeric"

2) Names are simply not set:

R> retList <- function() return(list(1,2,3,4)); names(retList())

3) They do not return the same thing. Your example gives

R> x <- list(1,2,3,4)
R> x[1]
[1] 1
R> x[[1]]
[1] 1

where x[1] returns the first element of x -- which is the same as x. Every scalar is a vector of length one. On the other hand x[[1]] returns the first element of the list.

4) Lastly, the two are different between they create, respectively, a list containing four scalars and a list with a single element (that happens to be a vector of four elements).

Embed a PowerPoint presentation into HTML

Another option is to use Apple Keynote on a Mac (Libre Office couldn't event open a pptx I had) to save the presentation to HTML5. It does a pretty good job to produce exactly what it displays in keynote, e.g. it includes animations and video. Compatibility of keynote to powerpoint has it's limits though (independent of the export).

Oracle "Partition By" Keyword

The PARTITION BY clause sets the range of records that will be used for each "GROUP" within the OVER clause.

In your example SQL, DEPT_COUNT will return the number of employees within that department for every employee record. (It is as if you're de-nomalising the emp table; you still return every record in the emp table.)

emp_no  dept_no  DEPT_COUNT
1       10       3
2       10       3
3       10       3 <- three because there are three "dept_no = 10" records
4       20       2
5       20       2 <- two because there are two "dept_no = 20" records

If there was another column (e.g., state) then you could count how many departments in that State.

It is like getting the results of a GROUP BY (SUM, AVG, etc.) without the aggregating the result set (i.e. removing matching records).

It is useful when you use the LAST OVER or MIN OVER functions to get, for example, the lowest and highest salary in the department and then use that in a calculation against this records salary without a sub select, which is much faster.

Read the linked AskTom article for further details.

Convert file to byte array and vice versa

There is no such functionality but you can use a temporary file by File.createTempFile().

File temp = File.createTempFile(prefix, suffix);
// tell system to delete it when vm terminates.

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

inside your onClickListener.onClick, put

getFragmentManager().beginTransaction().replace(, new tasks()).commit();

In another word, in your mycontacts.class

public class mycontacts extends Fragment {

    public mycontacts() {

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        final View v = super.getView(position, convertView, parent);
        ImageView purple = (ImageView) v.findViewById(;
        purple.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub
                        .replace(, new tasks())
        return view;


now, remember is the container (FrameLayout or other layouts) for the activity that calls the fragment

master branch and 'origin/master' have diverged, how to 'undiverge' branches'?

I found myself in this situation when I tried to rebase a branch that was tracking a remote branch, and I was trying to rebase it on master. In this scenario if you try to rebase, you'll most likely find your branch diverged and it can create a mess that isn't for git nubees!

Let's say you are on branch my_remote_tracking_branch, which was branched from master

$ git status

# On branch my_remote_tracking_branch

nothing to commit (working directory clean)

And now you are trying to rebase from master as:

git rebase master

STOP NOW and save yourself some trouble! Instead, use merge as:

git merge master

Yes, you'll end up with extra commits on your branch. But unless you are up for "un-diverging" branches, this will be a much smoother workflow than rebasing. See this blog for a much more detailed explanation.

On the other hand, if your branch is only a local branch (i.e. not yet pushed to any remote) you should definitely do a rebase (and your branch will not diverge in this case).

Now if you are reading this because you already are in a "diverged" scenario due to such rebase, you can get back to the last commit from origin (i.e. in an un-diverged state) by using:

git reset --hard origin/my_remote_tracking_branch

How can I add a Google search box to my website?

Sorry for replying on an older question, but I would like to clarify the last question.

You use a "get" method for your form. When the name of your input-field is "g", it will make a URL like this:[value from input-field]

But when you search with google, you notice the following URL:

Google uses the "q" Querystring variable as it's search-query. Therefor, renaming your field from "g" to "q" solved the problem.

Load local HTML file in a C# WebBrowser

quite late but it's the first hit i found from google

Instead of using the current directory or getting the assembly, just use the Application.ExecutablePath property:

//using System.IO;  
string applicationDirectory = Path.GetDirectoryName(Application.ExecutablePath);
string myFile = Path.Combine(applicationDirectory, "Sample.html");
webMain.Url = new Uri("file:///" + myFile);

Neatest way to remove linebreaks in Perl

Whenever I go through input and want to remove or replace characters I run it through little subroutines like this one.

sub clean {

    my $text = shift;

    $text =~ s/\n//g;
    $text =~ s/\r//g;

    return $text;

It may not be fancy but this method has been working flawless for me for years.

Remove property for all objects in array

To remove some key value pair form object array uses Postgres SQL as database like this example:

This is user function return user details object, we have to remove "api_secret" key from rows :

    function getCurrentUser(req, res, next) { // user function
    var userId = res.locals.userId;
    db.runSQLWithParams("select * from users where id = $1", [userId], function(err, rows) {
      var responseObject = {
        _embedded: rows,
      responseObject._embedded[0].api_secret = undefined
      // console.log(api);
      // console.log(responseObject);

The above function return below object as JSON response before

    "_embedded": [
            "id": "0123abd-345gfhgjf-dajd4456kkdj",
            "secret_key: "secret",
            "email": "[email protected]",
            "created": "2020-08-18T00:13:16.077Z"

After adding this line responseObject._embedded[0].api_secret = undefined It gives below result as JSON response:

        "_embedded": [
                "id": "0123abd-345gfhgjf-dajd4456kkdj",
                "email": "[email protected]",
                "created": "2020-08-18T00:13:16.077Z"

In SQL how to compare date values?

In standard SQL syntax, you would use:

WHERE mydate <= DATE '2008-11-20'

That is, the keyword DATE should precede the string. In some DBMS, however, you don't need to be that explicit; the system will convert the DATE column into a string, or the string into a DATE value, automatically. There are nominally some interesting implications if the DATE is converted into a string - if you happen to have dates in the first millennium (0001-01-01 .. 0999-12-31) and the leading zero(es) are omitted by the formatting system.

What does the 'Z' mean in Unix timestamp '120314170138Z'?

Yes. 'Z' stands for Zulu time, which is also GMT and UTC.


The UTC time zone is sometimes denoted by the letter Z—a reference to the equivalent nautical time zone (GMT), which has been denoted by a Z since about 1950. The letter also refers to the "zone description" of zero hours, which has been used since 1920 (see time zone history). Since the NATO phonetic alphabet and amateur radio word for Z is "Zulu", UTC is sometimes known as Zulu time.

Technically, because the definition of nautical time zones is based on longitudinal position, the Z time is not exactly identical to the actual GMT time 'zone'. However, since it is primarily used as a reference time, it doesn't matter what area of Earth it applies to as long as everyone uses the same reference.

From wikipedia again,

Around 1950, a letter suffix was added to the zone description, assigning Z to the zero zone, and A–M (except J) to the east and N–Y to the west (J may be assigned to local time in non-nautical applications; zones M and Y have the same clock time but differ by 24 hours: a full day). These were to be vocalized using a phonetic alphabet which pronounces the letter Z as Zulu, leading sometimes to the use of the term "Zulu Time". The Greenwich time zone runs from 7.5°W to 7.5°E longitude, while zone A runs from 7.5°E to 22.5°E longitude, etc.

Passing parameter via url to sql server reporting service

Try changing "Reports" to "ReportServer" in your url. For that just access this http://host/ReportServer/ and from there you can go to the report pages. There append your parmaters like this &<parameter>=<value>

For more detailed information:

How to apply a CSS filter to a background image

The following is a simple solution for modern browsers in pure CSS with a 'before' pseudo element, like the solution from Matthew Wilcoxson.

To avoid the need of accessing the pseudo element for changing the image and other attributes in JavaScript, simply use inherit as the value and access them via the parent element (here body).

body::before {
    content: ""; /* Important */
    z-index: -1; /* Important */
    position: inherit;
    left: inherit;
    top: inherit;
    width: inherit;
    height: inherit;
    background-image: inherit;
    background-size: cover;
    filter: blur(8px);

body {
  background-image: url("xyz.jpg");
  background-size: 0 0;  /* Image should not be drawn here */
  width: 100%;
  height: 100%;
  position: fixed; /* Or absolute for scrollable backgrounds */

Get the height and width of the browser viewport without scrollbars using jquery?

As Kyle suggested, you can measure the client browser viewport size without taking into account the size of the scroll bars this way.

Sample (Viewport dimensions WITHOUT scroll bars)

// First you forcibly request the scroll bars to hidden regardless if they will be needed or not.
$('body').css('overflow', 'hidden');

// Take your measures.
// (These measures WILL NOT take into account scroll bars dimensions)
var heightNoScrollBars = $(window).height();
var widthNoScrollBars = $(window).width();

// Set the overflow css property back to it's original value (default is auto)
$('body').css('overflow', 'auto');

Alternatively if you wish to find the dimensions of the client viewport while taking into account the size of the scroll bars, then this sample bellow best suits you.

First don't forget to set you body tag to be 100% width and height just to make sure the measurement is accurate.

body { 
width: 100%; // if you wish to measure the width and take into account the horizontal scroll bar.
height: 100%; // if you wish to measure the height while taking into account the vertical scroll bar.

Sample (Viewport dimensions WITH scroll bars)

// First you forcibly request the scroll bars to be shown regardless if they will be needed or not.
$('body').css('overflow', 'scroll');

// Take your measures.
// (These measures WILL take into account scroll bars dimensions)
var heightWithScrollBars = $(window).height();
var widthWithScrollBars = $(window).width();

// Set the overflow css property back to it's original value (default is auto)
$('body').css('overflow', 'auto');

SQL Server convert string to datetime

For instance you can use

update tablename set datetimefield='19980223 14:23:05'
update tablename set datetimefield='02/23/1998 14:23:05'
update tablename set datetimefield='1998-12-23 14:23:05'
update tablename set datetimefield='23 February 1998 14:23:05'
update tablename set datetimefield='1998-02-23T14:23:05'

You need to be careful of day/month order since this will be language dependent when the year is not specified first. If you specify the year first then there is no problem; date order will always be year-month-day.

Angular checkbox and ng-click

You can use ng-change instead of ng-click:

<!doctype html>
  <script src=""></script>
        var app = angular.module('myapp', []);
        app.controller('mainController', function($scope) {
          $scope.vm = {};
          $scope.vm.myClick = function($event) {
<body ng-app="myapp">
  <div ng-controller="mainController">
    <input type="checkbox" ng-model="vm.myChkModel" ng-change="vm.myClick(vm.myChkModel)">

org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class

Check your dependencies.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns=""


    <!-- DB related dependencies -->
    <!-- SPRING -->
    <!-- Spring Security  -->
    <!-- CGLIB is required to process @Configuration classes -->
    <!-- Servlet API and JSTL -->
    <!-- Test -->

      <name>Spring Maven Milestone Repository</name>


How to use Git?

If you wish to update several git repositories in one command - i suggest that you read a little bit on repo.

About updating the repository, you can do it by:

git fetch
git rebase origin/master


git pull --rebase

For more information about using GIT you can take a look on my GIT beginners guide

"Post Image data using POSTMAN"

Follow the below steps:

  1. No need to give any type of header.
  2. Select body > form-data and do same as shown in the image. 1

  3. Now in your Django

def post(self, request, *args, **kwargs):
    image = request.FILES["image"]
    data = json.loads(['data'])
    return Response(...)
  1. You can access all the keys (id, uid etc..) from the data variable.

Java substring: 'string index out of range'

I would recommend apache commons lang. A one-liner takes care of the problem.

pstmt2.setString(3, StringUtils.defaultIfEmpty(
    StringUtils.subString(itemdescription,0, 38), "_")); 

Only variables should be passed by reference

Php 7 compatible proper usage:

$fileName      = '';
$tmp           = explode('.', $fileName);
$fileExtension = end($tmp);

echo $fileExtension;
// jpg

Plugin with id '' not found

In build.gradle(Module:app) add this code

dependencies {
    compile '’

If you still have a problem after that, then add this code in build.gradle(Module:app)

defaultConfig {
    multiDexEnabled true

dependencies {
    compile ''
    compile ''

Change font-weight of FontAwesome icons?

.star-light::after {
    content: "\f005";
    font-family: "FontAwesome";
    font-size: 3.2rem;
    color: #fff;
    font-weight: 900;
    background-color: red;

How do I iterate through lines in an external file with shell?

One way would be:

while read NAME
    echo "$NAME"
done < names.txt

EDIT: Note that the loop gets executed in a sub-shell, so any modified variables will be local, except if you declare them with declare outside the loop.

Dennis Williamson is right. Sorry, must have used piped constructs too often and got confused.

What's the correct way to communicate between controllers in AngularJS?

Here's the quick and dirty way.

// Add $injector as a parameter for your controller

function myAngularController($scope,$injector){

    $scope.sendorders = function(){

       // now you can use $injector to get the 
       // handle of $rootScope and broadcast to all




Here is an example function to add within any of the sibling controllers:

$scope.$on('sinkallships', function() {

    alert('Sink that ship!');                       


and of course here's your HTML:

<button ngclick="sendorders()">Sink Enemy Ships</button>

How do you create a custom AuthorizeAttribute in ASP.NET Core?

Just adding to the great answer from @Shawn. If you are using dotnet 5 you need to update the class to be:

public abstract class AttributeAuthorizationHandler<TRequirement, TAttribute> : AuthorizationHandler<TRequirement> where TRequirement : IAuthorizationRequirement where TAttribute : Attribute
    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, TRequirement requirement)
        var attributes = new List<TAttribute>();
        if (context.Resource is HttpContext httpContext)
            var endPoint = httpContext.GetEndpoint();

            var action = endPoint?.Metadata.GetMetadata<ControllerActionDescriptor>();

            if(action != null)
        return HandleRequirementAsync(context, requirement, attributes);

    protected abstract Task HandleRequirementAsync(AuthorizationHandlerContext context, TRequirement requirement, IEnumerable<TAttribute> attributes);

    private static IEnumerable<TAttribute> GetAttributes(MemberInfo memberInfo) => memberInfo.GetCustomAttributes(typeof(TAttribute), false).Cast<TAttribute>();

Noting the way getting the ControllerActionDescriptor has changed.

How to print a percentage value in python?

You are dividing integers then converting to float. Divide by floats instead.

As a bonus, use the awesome string formatting methods described here:

To specify a percent conversion and precision.

>>> float(1) / float(3)
[Out] 0.33333333333333331

>>> 1.0/3.0
[Out] 0.33333333333333331

>>> '{0:.0%}'.format(1.0/3.0) # use string formatting to specify precision
[Out] '33%'

>>> '{percent:.2%}'.format(percent=1.0/3.0)
[Out] '33.33%'

A great gem!

Maven package/install without test (skip tests)

Just provide the command mentioned below which will ignore executing the test cases,

mvn package -DskipTests

How to remove close button on the jQuery UI dialog?

Easy way to achieve: (Do this in your Javascript)

    autoOpen: false,
    open: function(event, ui) {   // It'll hide Close button
        $(".ui-dialog-titlebar-close", ui.dialog | ui).hide();
    closeOnEscape: false,        // Do not close dialog on press Esc button
    show: {
        effect: "clip",
        duration: 500
    hide: {
        effect: "blind",
        duration: 200

Mercurial stuck "waiting for lock"

I encountered this problem on Mac OS X 10.7.5 and Mercurial 2.6.2 when trying to push. After upgrading to Mercurial 3.2.1, I got "no changes found" instead of "waiting for lock on repository". I found out that somehow the default path had gotten set to point to the same repository, so it's not too surprising that Mercurial would get confused.

Android widget: How to change the text of a button

I was able to change the button's text like this:

import android.widget.RemoteViews;

//grab the layout, then set the text of the Button called
RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.my_layout);
remoteViews.setTextViewText(, "Set button text here");

How can I simulate an anchor click via jquery?

In Javascript you can do like this

function submitRequest(buttonId) {
    if (document.getElementById(buttonId) == null
            || document.getElementById(buttonId) == undefined) {
    if (document.getElementById(buttonId).dispatchEvent) {
        var e = document.createEvent("MouseEvents");
        e.initEvent("click", true, true);
    } else {

and you can use it like


JavaScript: How to join / combine two arrays to concatenate into one array?

var a = ['a','b','c'];
var b = ['d','e','f'];
var c = a.concat(b); //c is now an an array with: ['a','b','c','d','e','f']
console.log( c[3] ); //c[3] will be 'd'

How do I make CMake output into a 'bin' dir?

As to me I am using cmake 3.5, the below(set variable) does not work:

      ARCHIVE_OUTPUT_DIRECTORY "/home/xy/cmake_practice/lib/"
      LIBRARY_OUTPUT_DIRECTORY "/home/xy/cmake_practice/lib/"
      RUNTIME_OUTPUT_DIRECTORY "/home/xy/cmake_practice/bin/"

but this works(set set_target_properties):

    ARCHIVE_OUTPUT_DIRECTORY "/home/xy/cmake_practice/lib/"
    LIBRARY_OUTPUT_DIRECTORY "/home/xy/cmake_practice/lib/"
    RUNTIME_OUTPUT_DIRECTORY "/home/xy/cmake_practice/bin/"

How to initialize a list of strings (List<string>) with many string values

List<string> mylist = new List<string>(new string[] { "element1", "element2", "element3" });

Create a variable name with "paste" in R?

See ?assign.

> assign(paste("tra.", 1, sep = ""), 5)
> tra.1
  [1] 5

How to get terminal's Character Encoding

To see the current locale information use locale command. Below is an example on RHEL 7.8

[usr@host ~]$ locale

Start systemd service after specific service?

In the .service file under the [Unit] section:

Description=My Website mongodb.service

The important part is the mongodb.service

The manpage describes it however due to formatting it's not as clear on first sight

systemd.unit - well formatted

systemd.unit - not so well formatted

Using .text() to retrieve only text not nested in child tags


Short variant of Stuart answer.

or with get()


Chrome & Safari Error::Not allowed to load local resource: file:///D:/CSS/Style.css

The solution is already answered here above (long ago).

But the implicit question "why does it work in FF and IE but not in Chrome and Safari" is found in the error text "Not allowed to load local resource": Chrome and Safari seem to use a more strict implementation of sandboxing (for security reasons) than the other two (at this time 2011).

This applies for local access. In a (normal) server environment (apache ...) the file would simply not have been found.

How can I loop over entries in JSON?

To decode json, you have to pass the json string. Currently you're trying to pass an object:

>>> response = urlopen(url)
>>> response
<addinfourl at 2146100812 whose fp = <socket._fileobject object at 0x7fe8cc2c>>

You can fetch the data with

What is the difference between char * const and const char *?

To avoid confusion, always append the const qualifier.

int       *      mutable_pointer_to_mutable_int;
int const *      mutable_pointer_to_constant_int;
int       *const constant_pointer_to_mutable_int;
int const *const constant_pointer_to_constant_int;

Mockito: List Matchers with generics

In addition to anyListOf above, you can always specify generics explicitly using this syntax:


Java 8 newly allows type inference based on parameters, so if you're using Java 8, this may work as well:


Remember that neither any() nor anyList() will apply any checks, including type or null checks. In Mockito 2.x, any(Foo.class) was changed to mean "any instanceof Foo", but any() still means "any value including null".

NOTE: The above has switched to ArgumentMatchers in newer versions of Mockito, to avoid a name collision with org.hamcrest.Matchers. Older versions of Mockito will need to keep using org.mockito.Matchers as above.

How to copy to clipboard using Access/VBA?

VB 6 provides a Clipboard object that makes all of this extremely simple and convenient, but unfortunately that's not available from VBA.

If it were me, I'd go the API route. There's no reason to be scared of calling native APIs; the language provides you with the ability to do that for a reason.

However, a simpler alternative is to use the DataObject class, which is part of the Forms library. I would only recommend going this route if you are already using functionality from the Forms library in your app. Adding a reference to this library only to use the clipboard seems a bit silly.

For example, to place some text on the clipboard, you could use the following code:

Dim clipboard As MSForms.DataObject
Set clipboard = New MSForms.DataObject
clipboard.SetText "A string value"

Or, to copy text from the clipboard into a string variable:

Dim clipboard As MSForms.DataObject
Dim strContents As String

Set clipboard = New MSForms.DataObject
strContents = clipboard.GetText

How do I right align div elements?

If you are using bootstrap, then:

<div class="pull-right"></div>

WebAPI to Return XML

If you don't want the controller to decide the return object type, you should set your method return type as System.Net.Http.HttpResponseMessage and use the below code to return the XML.

public HttpResponseMessage Authenticate()
  //process the request 

  string XML="<note><body>Message content</body></note>";
  return new HttpResponseMessage() 
    Content = new StringContent(XML, Encoding.UTF8, "application/xml") 

This is the quickest way to always return XML from Web API.

Declaring abstract method in TypeScript

The name property is marked as protected. This was added in TypeScript 1.3 and is now firmly established.

The makeSound method is marked as abstract, as is the class. You cannot directly instantiate an Animal now, because it is abstract. This is part of TypeScript 1.6, which is now officially live.

abstract class Animal {
    constructor(protected name: string) { }

    abstract makeSound(input : string) : string;

    move(meters) {
        alert( + " moved " + meters + "m.");

class Snake extends Animal {
    constructor(name: string) { super(name); }

    makeSound(input : string) : string {
        return "sssss"+input;

    move() {

The old way of mimicking an abstract method was to throw an error if anyone used it. You shouldn't need to do this any more once TypeScript 1.6 lands in your project:

class Animal {
    constructor(public name) { }
    makeSound(input : string) : string {
        throw new Error('This method is abstract');
    move(meters) {
        alert( + " moved " + meters + "m.");

class Snake extends Animal {
    constructor(name) { super(name); }
    makeSound(input : string) : string {
        return "sssss"+input;
    move() {

Create dataframe from a matrix

melt() from the reshape2 package gets you close ...

(res <- melt(, id="time"))
#   time variable value
# 1  0.0      C_0   0.1
# 2  0.5      C_0   0.2
# 3  1.0      C_0   0.3
# 4  0.0      C_1   0.3
# 5  0.5      C_1   0.4
# 6  1.0      C_1   0.5

... although you may want to post-process its results to get your preferred column names and ordering.

setNames(res[c("variable", "time", "value")], c("name", "time", "val"))
#   name time val
# 1  C_0  0.0 0.1
# 2  C_0  0.5 0.2
# 3  C_0  1.0 0.3
# 4  C_1  0.0 0.3
# 5  C_1  0.5 0.4
# 6  C_1  1.0 0.5

Connecting to SQL Server with Visual Studio Express Editions

My guess is that with VWD your solutions are more likely to be deployed to third party servers, many of which do not allow for a dynamically attached SQL Server database file. Thus the allowing of the other connection type.

This difference in IDE behavior is one of the key reasons for upgrading to a full version.

Volatile vs. Interlocked vs. lock

Either lock or interlocked increment is what you are looking for.

Volatile is definitely not what you're after - it simply tells the compiler to treat the variable as always changing even if the current code path allows the compiler to optimize a read from memory otherwise.


while (m_Var)
{ }

if m_Var is set to false in another thread but it's not declared as volatile, the compiler is free to make it an infinite loop (but doesn't mean it always will) by making it check against a CPU register (e.g. EAX because that was what m_Var was fetched into from the very beginning) instead of issuing another read to the memory location of m_Var (this may be cached - we don't know and don't care and that's the point of cache coherency of x86/x64). All the posts earlier by others who mentioned instruction reordering simply show they don't understand x86/x64 architectures. Volatile does not issue read/write barriers as implied by the earlier posts saying 'it prevents reordering'. In fact, thanks again to MESI protocol, we are guaranteed the result we read is always the same across CPUs regardless of whether the actual results have been retired to physical memory or simply reside in the local CPU's cache. I won't go too far into the details of this but rest assured that if this goes wrong, Intel/AMD would likely issue a processor recall! This also means that we do not have to care about out of order execution etc. Results are always guaranteed to retire in order - otherwise we are stuffed!

With Interlocked Increment, the processor needs to go out, fetch the value from the address given, then increment and write it back -- all that while having exclusive ownership of the entire cache line (lock xadd) to make sure no other processors can modify its value.

With volatile, you'll still end up with just 1 instruction (assuming the JIT is efficient as it should) - inc dword ptr [m_Var]. However, the processor (cpuA) doesn't ask for exclusive ownership of the cache line while doing all it did with the interlocked version. As you can imagine, this means other processors could write an updated value back to m_Var after it's been read by cpuA. So instead of now having incremented the value twice, you end up with just once.

Hope this clears up the issue.

For more info, see 'Understand the Impact of Low-Lock Techniques in Multithreaded Apps' -

p.s. What prompted this very late reply? All the replies were so blatantly incorrect (especially the one marked as answer) in their explanation I just had to clear it up for anyone else reading this. shrugs

p.p.s. I'm assuming that the target is x86/x64 and not IA64 (it has a different memory model). Note that Microsoft's ECMA specs is screwed up in that it specifies the weakest memory model instead of the strongest one (it's always better to specify against the strongest memory model so it is consistent across platforms - otherwise code that would run 24-7 on x86/x64 may not run at all on IA64 although Intel has implemented similarly strong memory model for IA64) - Microsoft admitted this themselves -

Empty or Null value display in SSRS text boxes

I couldn't get IsNothing() to behave and I didn't want to create dummy rows in my dataset (e.g. for a given list of customers create a dummy order per month displayed) and noticed that null values were displaying as -247192.

Lo and behold using that worked to suppress it (at least until MSFT changes SSRS for the better from 08R2) so forgive me but:

=iif(Fields!Sales_Diff.Value = -247192,"",Fields!Sales_Diff.Value)

How to handle-escape both single and double quotes in an SQL-Update statement

When SET QUOTED_IDENTIFIER is OFF, literal strings in expressions can be delimited by single or double quotation marks.

If a literal string is delimited by double quotation marks, the string can contain embedded single quotation marks, such as apostrophes.

How to use sha256 in php5.3.0

A way better solution is to just use the excelent compatibility script from Anthony Ferrara:

Please, and also, when checking the password, always add a way (preferibly async, so it doesn't impact the check process for timming attacks) to update the hash if needed.

Jquery in React is not defined

I just want to receive ajax request, but the problem is that jQuery is not defined in React.

Then don't use it. Use Fetch and have a look at Fetch polyfill in React not completely working in IE 11 to see example of alternative ways to get it running

Something like this

const that = this; 
  .then(function(response) { return response.json(); }) 
  .then(function(myJson) { 
     that.setState({data: myJson}); // for example

Set the value of an input field

The answer is really simple

// Your HTML text field

<input type="text" name="name" id="txt">

//Your javascript

<script type="text/javascript"> 
document.getElementById("txt").value = "My default value";

Or if you want to avoid JavaScript entirely: You can define it just using HTML

<input type="text" name="name" id="txt" value="My default value">

Where can I download mysql jdbc jar from?

Here's a one-liner using Maven:

mvn dependency:get -Dartifact=mysql:mysql-connector-java:5.1.38

Then, with default settings, it's available in:


Just replace the version number if you need a different one.

Why won't bundler install JSON gem?

To solve this problem, simply run:

bundle update

It will update the version of your bundler. Then run:

bundle install

Your problem will get solve. Solution is well explained here.

How to add 20 minutes to a current date?

Just get the millisecond timestamp and add 20 minutes to it:

twentyMinutesLater = new Date(currentDate.getTime() + (20*60*1000))

Complex nesting of partials and templates

I too was struggling with nested views in Angular.

Once I got a hold of ui-router I knew I was never going back to angular default routing functionality.

Here is an example application that uses multiple levels of views nesting

app.config(function ($stateProvider, $urlRouterProvider,$httpProvider) {
// navigate to view1 view by default

    .state('view1', {
        url: '/view1',
        templateUrl: 'partials/view1.html',
        controller: 'view1.MainController'
    .state('view1.nestedViews', {
        url: '/view1',
        views: {
            'childView1': { templateUrl: 'partials/view1.childView1.html' , controller: 'childView1Ctrl'},
            'childView2': { templateUrl: 'partials/view1.childView2.html', controller: 'childView2Ctrl' },
            'childView3': { templateUrl: 'partials/view1.childView3.html', controller: 'childView3Ctrl' }

    .state('view2', {
        url: '/view2',

    .state('view3', {
        url: '/view3',

    .state('view4', {
        url: '/view4',

As it can be seen there are 4 main views (view1,view2,view3,view4) and view1 has 3 child views.

How to auto generate migrations with Sequelize CLI from Sequelize models?

You cannot create migration scripts for existing models.


If going the classic way, you'll have to recreate the models via the CLI:

sequelize model:create --name MyUser --attributes first_name:string,last_name:string,bio:text

It will generate these files:


"use strict";_x000D_
module.exports = function(sequelize, DataTypes) {_x000D_
  var MyUser = sequelize.define("MyUser", {_x000D_
    first_name: DataTypes.STRING,_x000D_
    last_name: DataTypes.STRING,_x000D_
    bio: DataTypes.TEXT_x000D_
  }, {_x000D_
    classMethods: {_x000D_
      associate: function(models) {_x000D_
        // associations can be defined here_x000D_
  return MyUser;_x000D_


"use strict";_x000D_
module.exports = {_x000D_
  up: function(migration, DataTypes, done) {_x000D_
    migration.createTable("MyUsers", {_x000D_
      id: {_x000D_
        allowNull: false,_x000D_
        autoIncrement: true,_x000D_
        primaryKey: true,_x000D_
        type: DataTypes.INTEGER_x000D_
      first_name: {_x000D_
        type: DataTypes.STRING_x000D_
      last_name: {_x000D_
        type: DataTypes.STRING_x000D_
      bio: {_x000D_
        type: DataTypes.TEXT_x000D_
      createdAt: {_x000D_
        allowNull: false,_x000D_
        type: DataTypes.DATE_x000D_
      updatedAt: {_x000D_
        allowNull: false,_x000D_
        type: DataTypes.DATE_x000D_
  down: function(migration, DataTypes, done) {_x000D_

String.Format alternative in C++

As already mentioned the C++ way is using stringstreams.

#include <sstream>

string a = "test";
string b = "text.txt";
string c = "text1.txt";

std::stringstream ostr;
ostr << a << " " << b << " > " << c;

Note that you can get the C string from the string stream object like so.

std::string formatted_string = ostr.str();
const char* c_str = formatted_string.c_str();

Subtracting 1 day from a timestamp date

Use the INTERVAL type to it. E.g:


--Unrelated to the question, but PostgreSQL also supports some shortcuts:
SELECT 'yesterday'::TIMESTAMP, 'tomorrow'::TIMESTAMP, 'allballs'::TIME;

Then you can do the following on your query:

    count(accounts) AS COUNT,
    ((date_at) - INTERVAL '1 DAY') AS dateat
    date_at <= now() - INTERVAL '130 DAYS'


Tip 1

You can append multiple operands. E.g.: how to get last day of current month?


Tip 2

You can also create an interval using make_interval function, useful when you need to create it at runtime (not using literals):

SELECT make_interval(days => 10 + 2);
SELECT make_interval(days => 1, hours => 2);
SELECT make_interval(0, 1, 0, 5, 0, 0, 0.0);

More info:

Date/Time Functions and Operators

datatype-datetime (Especial values).

How to use the PI constant in C++

You can use that:

#define _USE_MATH_DEFINES // for C++
#include <cmath>

#define _USE_MATH_DEFINES // for C
#include <math.h>

Math Constants are not defined in Standard C/C++. To use them, you must first define _USE_MATH_DEFINES and then include cmath or math.h.

What is Android keystore file, and what is it used for?

The answer I would provide is that a keystore file is to authenticate yourself to anyone who is asking. It isn't restricted to just signing .apk files, you can use it to store personal certificates, sign data to be transmitted and a whole variety of authentication.

In terms of what you do with it for Android and probably what you're looking for since you mention signing apk's, it is your certificate. You are branding your application with your credentials. You can brand multiple applications with the same key, in fact, it is recommended that you use one certificate to brand multiple applications that you write. It easier to keep track of what applications belong to you.

I'm not sure what you mean by implications. I suppose it means that no one but the holder of your certificate can update your application. That means that if you release it into the wild, lose the cert you used to sign the application, then you cannot release updates so keep that cert safe and backed up if need be.

But apart from signing apks to release into the wild, you can use it to authenticate your device to a server over SSL if you so desire, (also Android related) among other functions.

What is trunk, branch and tag in Subversion?

If you're new to Subversion you may want to check out this post on, appropriately titled Ultimate Round-Up for Version Control with SubVersion.

It covers getting started with SubVersion with links to tutorials, reference materials, & book suggestions.

It covers tools (many are compatible windows), and it mentions AnkhSVN as a Visual Studio compatible plugin. The comments also mention VisualSVN as an alternative.

What is Android's file system?

Depends on what hardware/platform you use.

Since Android uses the Linux-kernel at this level, it is more or less possible to use whatever filesystem the Linux-kernel supports.

But since most phones use some kind of nand flash, it is safe to assume that they use YAFFS.

But please note that if some vendor wants to sell a Android netbook (with a harddrive), they could use ext3 or something like that.

How to fix the height of a <div> element?

change the div to display block


i made a jsfiddle example here please check

How can one check to see if a remote file exists using PHP?

You could use the following:

$file = '';
$file_exists = (@fopen($file, "r")) ? true : false;

Worked for me when trying to check if an image exists on the URL

how to check the jdk version used to compile a .class file

You can try jclasslib:

It's nice that it can associate itself with *.class extension.

Delete last commit in bitbucket

If you are not working with others (or are happy to cause them significant annoyance), then it is possible to remove commits from bitbucket branches.

If you're trying to change a non-master branch:

git reset HEAD^               # remove the last commit from the branch history
git push origin :branch_name  # delete the branch from bitbucket
git push origin branch_name   # push the branch back up again, without the last commit

if you're trying to change the master branch

In git generally, the master branch is not special - it's just a convention. However, bitbucket and github and similar sites usually require there to be a main branch (presumably because it's easier than writing more code to handle the event that a repository has no branches - not sure). So you need to create a new branch, and make that the main branch:

# on master:
git checkout -b master_temp  
git reset HEAD^              # undo the bad commit on master_temp
git push origin master_temp  # push the new master to Bitbucket

On Bitbucket, go to the repository settings, and change the "Main branch" to master_temp (on Github, change the "Default branch").

git push origin :master     # delete the original master branch from Bitbucket
git checkout master
git reset master_temp       # reset master to master_temp (removing the bad commit)
git push origin master      # re-upload master to bitbucket

Now go to Bitbucket, and you should see the history that you want. You can now go to the settings page and change the Main branch back to master.

This process will also work with any other history changes (e.g. git filter-branch). You just have to make sure to reset to appropriate commits, before the new history split off from the old.

edit: apparently you don't need to go to all this hassle on github, as you can force-push a reset branch.

Dealing with annoyed collaborators

Next time anyone tries to pull from your repository, (if they've already pulled the bad commit), the pull will fail. They will manually have to reset to a commit before the changed history, and then pull again.

git reset HEAD^
git pull

If they have pulled the bad commit, and committed on top of it, then they will have to reset, and then git cherry-pick the good commits that they want to create, effectively re-creating the whole branch without the bad commit.

If they never pulled the bad commit, then this whole process won't affect them, and they can pull as normal.

ImportError: Couldn't import Django

Looks like you have not activated your virtualenv when using the runserver command.

Windows: <virtualenv dir>\Scripts\activate.bat

Linux: source <virtualenv dir>\bin\activate

You should see (name of virtualenv) as a prefix to your current directory:

(virtualenv) E:\video course\Python\code\web_worker\MxOnline>python runserver

Intercept a form submit in JavaScript and prevent normal submission

Use @Kristian Antonsen's answer, or you can use:

$('button').click(function() {

JUnit: how to avoid "no runnable methods" in test utils classes

Ant now comes with the skipNonTests attribute which was designed to do exactly what you seem to be looking for. No need to change your base classes to abstract or add annotations to them.

Turn off deprecated errors in PHP 5.3

You have to edit the PHP configuration file. Find the line

error_reporting = E_ALL

and replace it with:

error_reporting = E_ALL ^ E_DEPRECATED

If you don't have access to the configuration file you can add this line to the PHP WordPress file (maybe headers.php):

error_reporting(E_ALL ^ E_DEPRECATED);

Oracle: How to filter by date and time in a where clause

In the example that you have provided there is nothing that would throw a SQL command not properly formed error. How are you executing this query? What are you not showing us?

This example script works fine:

create table tableName
(session_start_date_time DATE);

insert into tableName (session_start_date_time) 
values (sysdate+1);

select * from tableName
where session_start_date_time > to_date('12-Jan-2012 16:00', 'DD-MON-YYYY hh24:mi');

As does this example:

create table tableName2
(session_start_date_time TIMESTAMP);

insert into tableName2 (session_start_date_time) 
values (to_timestamp('01/12/2012 16:01:02.345678','mm/dd/yyyy hh24:mi:ss.ff'));

select * from tableName2
where session_start_date_time > to_date('12-Jan-2012 16:00', 'DD-MON-YYYY hh24:mi');

select * from tableName2
where session_start_date_time > to_timestamp('01/12/2012 14:01:02.345678','mm/dd/yyyy hh24:mi:ss.ff');

So there must be something else that is wrong.

Creating Scheduled Tasks

This works for me

It is nicely designed Fluent API.

//This will create Daily trigger to run every 10 minutes for a duration of 18 hours
SchedulerResponse response = WindowTaskScheduler
    .CreateTask("TaskName", "C:\\Test.bat")
    .RunDurationFor(new TimeSpan(18, 0, 0))
    .SetStartDate(new DateTime(2015, 8, 8))
    .SetStartTime(new TimeSpan(8, 0, 0))

Pandas left outer join multiple dataframes on multiple columns

One can also do this with a compact version of @TomAugspurger's answer, like so:

df = df1.merge(df2, how='left', on=['Year', 'Week', 'Colour']).merge(df3[['Week', 'Colour', 'Val3']], how='left', on=['Week', 'Colour'])

Numbering rows within groups in a data frame

Using the rowid() function in data.table:

> set.seed(100)  
> df <- data.frame(cat = c(rep("aaa", 5), rep("bbb", 5), rep("ccc", 5)), val = runif(15))
> df <- df[order(df$cat, df$val), ]  
> df$num <- data.table::rowid(df$cat)
> df
   cat        val num
4  aaa 0.05638315   1
2  aaa 0.25767250   2
1  aaa 0.30776611   3
5  aaa 0.46854928   4
3  aaa 0.55232243   5
10 bbb 0.17026205   1
8  bbb 0.37032054   2
6  bbb 0.48377074   3
9  bbb 0.54655860   4
7  bbb 0.81240262   5
13 ccc 0.28035384   1
14 ccc 0.39848790   2
11 ccc 0.62499648   3
15 ccc 0.76255108   4
12 ccc 0.88216552   5

Failed to Connect to MySQL at localhost:3306 with user root

MySQL default port is 3306 but it may be unavailable for some reasons, try to restart your machine. Also sesrch for your MySQL configuration file (should be called "my.cnf") and check if the used port is 3306 or 3307, if is 3307 you can change it to 3306 and then reboot your MySQL server.

MySQL: #126 - Incorrect key file for table

I got this message when writing to a table after reducing the ft_min_word_len (full text min word length). To solve it, re-create the index by repairing the table.

Warning: #1265 Data truncated for column 'pdd' at row 1

As the message error says, you need to Increase the length of your column to fit the length of the data you are trying to insert (0000-00-00)


Following your comment, I run a test table:

mysql> create table testDate(id int(2) not null auto_increment, pdd date default null, primary key(id));
Query OK, 0 rows affected (0.20 sec)


mysql> insert into testDate values(1,'0000-00-00');
Query OK, 1 row affected (0.06 sec)


So, aparently you want to insert a NULL value to pdd field as your comment states ? You can do that in 2 ways like this:

Method 1:

mysql> insert into testDate values(2,'');
Query OK, 1 row affected, 1 warning (0.06 sec)

Method 2:

mysql> insert into testDate values(3,NULL);
Query OK, 1 row affected (0.07 sec)


You failed to change the default value of pdd field. Here is the syntax how to do it (in my case, I set it to NULL in the start, now I will change it to NOT NULL)

mysql> alter table testDate modify pdd date not null;
Query OK, 3 rows affected, 1 warning (0.60 sec)
Records: 3  Duplicates: 0  Warnings: 1

How do I decompile a .NET EXE into readable C# source code?

When Red Gate said there would no longer be a free version of .Net Reflector, I started using ILSpy and Telerik's JustDecompile. I have found ILSpy to decompile more accurately than JustDecompile (which is still in Beta). Red Gate has changed their decision and still have a free version of .Net Reflector, but now I like ILSpy.

From the ILSpy website (

ILSpy is the open-source .NET assembly browser and decompiler.

ILSpy Features

  • Assembly browsing
  • IL Disassembly
  • Decompilation to C#
  • Supports lambdas and 'yield return'
  • Shows XML documentation
  • Saving of resources
  • Search for types/methods/properties (substring)
  • Hyperlink-based type/method/property navigation
  • Base/Derived types navigation
  • Navigation history
  • BAML to XAML decompiler
  • Save Assembly as C# Project
  • Find usage of field/method
  • Extensible via plugins (MEF)


April 15, 2012, ILSpy 2.0 was released. New features compared with version 1.0:

  • Assembly Lists
  • Support for decompiling Expression trees
  • Support for lifted operatores on nullables
  • Decompile to Visual Basic
  • Search for multiple strings separated by space (searching for "Assembly manager" in ILSpy.exe would find AssemblyListManager)
  • Clicking on a local variable will highlight all other occurrences of that variable
  • Ctrl+F can be used to search within the decompiled code view


  • ILSpy 2.1 supports async/await decompilation

Change UITextField and UITextView Cursor / Caret Color

It is only possible by accessing a private property and therefore may cause an Apple AppStore app rejection.

take a look at this Stackoverflow question

How to run Spring Boot web application in Eclipse itself?

Steps: 1. go to Run->Run configuration -> Maven Build -> New configuration
2. set base directory of you project ie.${workspace_loc:/shc-be-war}
3. set goal spring-boot:run
4. Run project from Run->New_Configuration

enter image description here

Correct MIME Type for favicon.ico?

I think the root for this confusion is well explained in this wikipedia article.

While the IANA-registered MIME type for ICO files is image/, it was submitted to IANA in 2003 by a third party and is not recognised by Microsoft software, which uses image/x-icon instead.

If even the inventor of the ICO format does not use the official MIME type, I will use image/x-icon, too.

How to calculate mean, median, mode and range from a set of numbers

As already pointed out by Nico Huysamen, finding multiple mode in Java 1.8 can be done alternatively as below.

import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.Map;

public static void mode(List<Integer> numArr) {
    Map<Integer, Integer> freq = new HashMap<Integer, Integer>();;
    Map<Integer, List<Integer>> mode = new HashMap<Integer, List<Integer>>();

    int modeFreq = 1; //record the highest frequence
    for(int x=0; x<numArr.size(); x++) { //1st for loop to record mode
        Integer curr = numArr.get(x); //O(1)
        freq.merge(curr, 1, (a, b) -> a + b); //increment the frequency for existing element, O(1)
        int currFreq = freq.get(curr); //get frequency for current element, O(1)

        //lazy instantiate a list if no existing list, then
        //record mapping of frequency to element (frequency, element), overall O(1)
        mode.computeIfAbsent(currFreq, k -> new ArrayList<>()).add(curr);

        if(modeFreq < currFreq) modeFreq = currFreq; //update highest frequency
    mode.get(modeFreq).forEach(x -> System.out.println("Mode = " + x)); //pretty print the result //another for loop to return result

Happy coding!

How do I get the "id" after INSERT into MySQL database with Python?



SELECT last_insert_id();

Any tools to generate an XSD schema from an XML instance document?

Altova XmlSpy does this well - you can find an overview here

How do I bind a List<CustomObject> to a WPF DataGrid?

Actually, to properly support sorting, filtering, etc. a CollectionViewSource should be used as a link between the DataGrid and the list, like this:

  <CollectionViewSource x:Key="ItemCollectionViewSource" CollectionViewType="ListCollectionView"/>

The DataGrid line looks like this:

  DataContext="{StaticResource ItemCollectionViewSource}"

In the code behind, you link CollectionViewSource with your link.

CollectionViewSource itemCollectionViewSource;
itemCollectionViewSource = (CollectionViewSource)(FindResource("ItemCollectionViewSource"));
itemCollectionViewSource.Source = itemList;

For detailed example see my article on CoedProject:

How do I change the select box arrow

You can skip the container or background image with pure css arrow:

select {

  /* make arrow and background */

    linear-gradient(45deg, transparent 50%, blue 50%),
    linear-gradient(135deg, blue 50%, transparent 50%),
    linear-gradient(to right, skyblue, skyblue);
    calc(100% - 21px) calc(1em + 2px),
    calc(100% - 16px) calc(1em + 2px),
    100% 0;
    5px 5px,
    5px 5px,
    2.5em 2.5em;
  background-repeat: no-repeat;

  /* styling and reset */

  border: thin solid blue;
  font: 300 1em/100% "Helvetica Neue", Arial, sans-serif;
  line-height: 1.5em;
  padding: 0.5em 3.5em 0.5em 1em;

  /* reset */

  border-radius: 0;
  margin: 0;      
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;

Sample here

COPYing a file in a Dockerfile, no such file or directory?

File not found error with Docker put_archive. I am using the Python API for docker. Docker version 1.12.5, build 7392c3b

docker.errors.NotFound: 404 Client Error: Not Found ("lstat /var/lib/docker/aufs/mnt/39d58e00519ba4171815ee4444f3c43d2c6a7e285102747398f6788e39ee0e87/var/lib/neo4j/certificates: no such file or directory")

I am unable to copy files to a created docker container.

con = cli.create_container(...)

If I change the order of operation there is no error and the files are copied exactly to were I want them. So I know my code is working and doing what I want it to do. But its important to copy configuration files to a container before it is started. Coping the files after the start cuases the container to start with a default configuration and not the custom configuration which needs to be copied into place before the container is started. Docker claims that this issue is closed but it is still affecting my application.

This works; Same code different execution order.

con = cli.create_container(...)

How to return a PNG image from Jersey REST service method to the browser

If you have a number of image resource methods, it is well worth creating a MessageBodyWriter to output the BufferedImage:

@Produces({ "image/png", "image/jpg" })
public class BufferedImageBodyWriter implements MessageBodyWriter<BufferedImage>  {
  public boolean isWriteable(Class<?> type, Type type1, Annotation[] antns, MediaType mt) {
    return type == BufferedImage.class;

  public long getSize(BufferedImage t, Class<?> type, Type type1, Annotation[] antns, MediaType mt) {
    return -1; // not used in JAX-RS 2

  public void writeTo(BufferedImage image, Class<?> type, Type type1, Annotation[] antns, MediaType mt, MultivaluedMap<String, Object> mm, OutputStream out) throws IOException, WebApplicationException {
    ImageIO.write(image, mt.getSubtype(), out);

This MessageBodyWriter will be used automatically if auto-discovery is enabled for Jersey, otherwise it needs to be returned by a custom Application sub-class. See JAX-RS Entity Providers for more info.

Once this is set up, simply return a BufferedImage from a resource method and it will be be output as image file data:

@Produces({"image/png", "image/jpg"})
public Response getFullImage(...) {
  BufferedImage image = ...;
  return Response.ok(image).build();

A couple of advantages to this approach:

  • It writes to the response OutputSteam rather than an intermediary BufferedOutputStream
  • It supports both png and jpg output (depending on the media types allowed by the resource method)

Each GROUP BY expression must contain at least one column that is not an outer reference

When you're using GROUP BY, you need to also use aggregate functions for the columns not inside your group by clause.

I don't know exactly what you're trying to do, but I guess this would work:

    LEFT(SUBSTRING(batchinfo.datapath, PATINDEX('%[0-9][0-9][0-9]%', batchinfo.datapath), 8000),
    PATINDEX('%[^0-9]%', SUBSTRING(batchinfo.datapath, PATINDEX('%[0-9][0-9][0-9]%', batchinfo.datapath), 8000))-1),,
    batchinfo join qvalues on batchinfo.rowid=qvalues.rowid
group by
    LEFT(SUBSTRING(batchinfo.datapath, PATINDEX('%[0-9][0-9][0-9]%', batchinfo.datapath), 8000),
    PATINDEX('%[^0-9]%', SUBSTRING(batchinfo.datapath, PATINDEX('%[0-9][0-9][0-9]%', batchinfo.datapath), 8000))-1),,

Edit: What I'm trying to do here is a group by with all fields but rid. If that's not what you want, what you need to do in order to have a valid SQL statement is adding an aggregate function call for each removed group by field...

jQuery: Can I call delay() between addClass() and such?

AFAIK the delay method only works for numeric CSS modifications.

For other purposes JavaScript comes with a setTimeout method:

window.setTimeout(function(){$("#div").removeClass("error");}, 1000);

Remove duplicates in the list using linq

An universal extension method:

public static class EnumerableExtensions
    public static IEnumerable<T> DistinctBy<T, TKey>(this IEnumerable<T> enumerable, Func<T, TKey> keySelector)
        return enumerable.GroupBy(keySelector).Select(grp => grp.First());

Example of usage:

var lstDst = lst.DistinctBy(item => item.Key);

How to open the Google Play Store directly from my Android application?



fun Activity.openAppInGooglePlay(){

val appId = BuildConfig.APPLICATION_ID
try {
    this.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=$appId")))
} catch (anfe: ActivityNotFoundException) {


    fun openAppInGooglePlay(activity:Activity){

        val appId = BuildConfig.APPLICATION_ID
        try {
            activity.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=$appId")))
        } catch (anfe: ActivityNotFoundException) {

How do I make an input field accept only letters in javaScript?

Try this:

var alphaExp = /^[a-zA-Z]+$/;
                //Your logice will be here.
                alert("Please enter only alphabets");


Setting the correct encoding when piping stdout in Python

I could "automate" it with a call to:

def __fix_io_encoding(last_resort_default='UTF-8'):
  import sys
  if [x for x in (sys.stdin,sys.stdout,sys.stderr) if x.encoding is None] :
      import os
      defEnc = None
      if defEnc is None :
          import locale
          defEnc = locale.getpreferredencoding()
        except: pass
      if defEnc is None :
        try: defEnc = sys.getfilesystemencoding()
        except: pass
      if defEnc is None :
        try: defEnc = sys.stdin.encoding
        except: pass
      if defEnc is None :
        defEnc = last_resort_default
      os.environ['PYTHONIOENCODING'] = os.environ.get("PYTHONIOENCODING",defEnc)
__fix_io_encoding() ; del __fix_io_encoding

Yes, it's possible to get an infinite loop here if this "setenv" fails.

Best XML parser for Java

If you care less about performance, I'm a big fan of Apache Digester, since it essentially lets you map directly from XML to Java Beans.

Otherwise, you have to first parse, and then construct your objects.

Can I have an IF block in DOS batch file?

I ran across this article in the results returned by a search related to the IF command in a batch file, and I couldn't resist the opportunity to correct the misconception that IF blocks are limited to single commands. Following is a portion of a production Windows NT command script that runs daily on the machine on which I am composing this reply.

    if "%COPYTOOL%" equ "R" (
    WWLOGGER.exe "%APPDATA%\WizardWrx\%~n0.LOG" "Using RoboCopy to make a backup of %USERPROFILE%\My Documents\Outlook Files\*"
    %TOOLPATH% %SRCEPATH% %DESTPATH% /copyall %RCLOGSTR% /m /np /r:0 /tee
    C:\BIN\ExitCodeMapper.exe C:\BIN\ExitCodeMapper.INI[Robocopy] %TEMP%\%~n0.TMP %ERRORLEVEL%
) else (
    WWLOGGER.exe "%APPDATA%\WizardWrx\%~n0.LOG" "Using XCopy to make a backup of %USERPROFILE%\My Documents\Outlook Files\*"
    call %TOOLPATH%  "%USERPROFILE%\My Documents\Outlook Files\*" "%USERPROFILE%\My Documents\Outlook Files\_backups" /f /m /v /y
    C:\BIN\ExitCodeMapper.exe C:\BIN\ExitCodeMapper.INI[Xcopy] %TEMP%\%~n0.TMP %ERRORLEVEL%

Perhaps blocks of two or more lines applies exclusively to Windows NT command scripts (.CMD files), because a search of the production scripts directory of an application that is restricted to old school batch (.BAT) files, revealed only one-command blocks. Since the application has gone into extended maintenance (meaning that I am not actively involved in supporting it), I can't say whether that is because I didn't need more than one line, or that I couldn't make them work.

Regardless, if the latter is true, there is a simple workaround; move the multiple lines into either a separate batch file or a batch file subroutine. I know that the latter works in both kinds of scripts.

SDK location not found. Define location with sdk.dir in the file or with an ANDROID_HOME environment variable

Please follow bellow points it work's for me:

  1. Go to your Project -> Android
  2. Create a file
  3. Open the file
  4. Paste your Android SDK path depending on the operating system:

    4.a Windows

    sdk.dir = C:/Users/USERNAME/AppData/Local/Android/sdk

    4.b Linux or MacOS

    sdk.dir = /home/USERNAME/Android/sdk

    Replace USERNAME with your user name

What is a JavaBean exactly?

Spring @Bean annotation indicates that a method produces a bean to be managed by the Spring container.

More reference:

Jquery split function

Try this. It uses the split function which is a core part of javascript, nothing to do with jQuery.

var parts = html.split(":-"),
    i, l
for (i = 0, l = parts.length; i < l; i += 2) {
    $("#" + parts[i]).text(parts[i + 1]);

How can I set the initial value of Select2 when using AJAX?

You are doing most things correctly, it looks like the only problem you are hitting is that you are not triggering the change method after you are setting the new value. Without a change event, Select2 cannot know that the underlying value has changed so it will only display the placeholder. Changing your last part to


Should fix your issue, and you should see the UI update right away.

This is assuming that you have an <option> already that has a value of initial_creditor_id. If you do not Select2, and the browser, will not actually be able to change the value, as there is no option to switch to, and Select2 will not detect the new value. I noticed that your <select> only contains a single option, the one for the placeholder, which means that you will need to create the new <option> manually.

var $option = $("<option selected></option>").val(initial_creditor_id).text("Whatever Select2 should display");

And then append it to the <select> that you initialized Select2 on. You may need to get the text from an external source, which is where initSelection used to come into play, which is still possible with Select2 4.0.0. Like a standard select, this means you are going to have to make the AJAX request to retrieve the value and then set the <option> text on the fly to adjust.

var $select = $('.creditor_select2');

$select.select2(/* ... */); // initialize Select2 and any events

var $option = $('<option selected>Loading...</option>').val(initial_creditor_id);

$select.append($option).trigger('change'); // append the option and update Select2

$.ajax({ // make the request for the selected data object
  type: 'GET',
  url: '/api/for/single/creditor/' + initial_creditor_id,
  dataType: 'json'
}).then(function (data) {
  // Here we should have the data object
  $option.text(data.text).val(; // update the text that is displayed (and maybe even the value)
  $option.removeData(); // remove any caching data that might be associated
  $select.trigger('change'); // notify JavaScript components of possible changes

While this may look like a lot of code, this is exactly how you would do it for non-Select2 select boxes to ensure that all changes were made.

.trim() in JavaScript not working in IE

Unfortunately there is not cross browser JavaScript support for trim().

If you aren't using jQuery (which has a .trim() method) you can use the following methods to add trim support to strings:

String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g,"");
String.prototype.ltrim = function() {
    return this.replace(/^\s+/,"");
String.prototype.rtrim = function() {
    return this.replace(/\s+$/,"");

Easy way to concatenate two byte arrays

If you prefer ByteBuffer like @kalefranz, there is always the posibility to concatenate two byte[] (or even more) in one line, like this:

byte[] c = ByteBuffer.allocate(a.length+b.length).put(a).put(b).array();

JQuery Redirect to URL after specified time

$(document).ready(function() {
    window.setInterval(function() {
    var timeLeft    = $("#timeLeft").html();
        if(eval(timeLeft) == 0) {
                window.location= ("");
        } else {
            $("#timeLeft").html(eval(timeLeft)- eval(1));
    }, 1000);

I have filtered my Excel data and now I want to number the rows. How do I do that?

I had the same problem. I'm no expert but this is the solution we used: Before you filter your data, first create a temporary column to populate your entire data set with your original sort order. Auto number the temporary "original sort order" column. Now filter your data. Copy and paste the filtered data into a new worksheet. This will move only the filtered data to the new sheet so that your row numbers will become consecutive. Now auto number your desired field. Go back to your original worksheet and delete the filtered rows. Copy and paste the newly numbered data from the secondary sheet onto the bottom of your original worksheet. Then clear your filter and sort the worksheet by the temporary "original sort order" column. This will put your newly numbered data back into its original order and you can then delete the temporary column.

How to validate domain credentials?

Here's how to determine a local user:

    public bool IsLocalUser()
        return windowsIdentity.AuthenticationType == "NTLM";

Edit by Ian Boyd

You should not use NTLM anymore at all. It is so old, and so bad, that Microsoft's Application Verifier (which is used to catch common programming mistakes) will throw a warning if it detects you using NTLM.

Here's a chapter from the Application Verifier documentation about why they have a test if someone is mistakenly using NTLM:

Why the NTLM Plug-in is Needed

NTLM is an outdated authentication protocol with flaws that potentially compromise the security of applications and the operating system. The most important shortcoming is the lack of server authentication, which could allow an attacker to trick users into connecting to a spoofed server. As a corollary of missing server authentication, applications using NTLM can also be vulnerable to a type of attack known as a “reflection” attack. This latter allows an attacker to hijack a user’s authentication conversation to a legitimate server and use it to authenticate the attacker to the user’s computer. NTLM’s vulnerabilities and ways of exploiting them are the target of increasing research activity in the security community.

Although Kerberos has been available for many years many applications are still written to use NTLM only. This needlessly reduces the security of applications. Kerberos cannot however replace NTLM in all scenarios – principally those where a client needs to authenticate to systems that are not joined to a domain (a home network perhaps being the most common of these). The Negotiate security package allows a backwards-compatible compromise that uses Kerberos whenever possible and only reverts to NTLM when there is no other option. Switching code to use Negotiate instead of NTLM will significantly increase the security for our customers while introducing few or no application compatibilities. Negotiate by itself is not a silver bullet – there are cases where an attacker can force downgrade to NTLM but these are significantly more difficult to exploit. However, one immediate improvement is that applications written to use Negotiate correctly are automatically immune to NTLM reflection attacks.

By way of a final word of caution against use of NTLM: in future versions of Windows it will be possible to disable the use of NTLM at the operating system. If applications have a hard dependency on NTLM they will simply fail to authenticate when NTLM is disabled.

How the Plug-in Works

The Verifier plug detects the following errors:

  • The NTLM package is directly specified in the call to AcquireCredentialsHandle (or higher level wrapper API).

  • The target name in the call to InitializeSecurityContext is NULL.

  • The target name in the call to InitializeSecurityContext is not a properly-formed SPN, UPN or NetBIOS-style domain name.

The latter two cases will force Negotiate to fall back to NTLM either directly (the first case) or indirectly (the domain controller will return a “principal not found” error in the second case causing Negotiate to fall back).

The plug-in also logs warnings when it detects downgrades to NTLM; for example, when an SPN is not found by the Domain Controller. These are only logged as warnings since they are often legitimate cases – for example, when authenticating to a system that is not domain-joined.

NTLM Stops

5000 – Application Has Explicitly Selected NTLM Package

Severity – Error

The application or subsystem explicitly selects NTLM instead of Negotiate in the call to AcquireCredentialsHandle. Even though it may be possible for the client and server to authenticate using Kerberos this is prevented by the explicit selection of NTLM.

How to Fix this Error

The fix for this error is to select the Negotiate package in place of NTLM. How this is done will depend on the particular Network subsystem being used by the client or server. Some examples are given below. You should consult the documentation on the particular library or API set that you are using.

APIs(parameter) Used by Application    Incorrect Value  Correct Value  
=====================================  ===============  ========================
AcquireCredentialsHandle (pszPackage)  “NTLM”           NEGOSSP_NAME “Negotiate”

How to execute the start script with Nodemon

First change your package.json file,

        "start": "node ./bin/www",
        "start-dev": "nodemon ./app.js"

After that, execute command

npm run start-dev

Deleting rows with Python in a CSV file

You should have if row[2] != "0". Otherwise it's not checking to see if the string value is equal to 0.

OWIN Startup Class Missing

It is also possible to get this exception (even when you have a correctly configured startup class) if running through IIS Express and your virtual directory is not configured correctly.

When I encountered this issue, the resolution was simply to press the 'Create Virtual Directory' button in the 'Web' tab of project properties (Using Visual Studio 2013)

How to choose the right bean scope?

Since JSF 2.3 all the bean scopes defined in package javax.faces.bean package have been deprecated to align the scopes with CDI. Moreover they're only applicable if your bean is using @ManagedBean annotation. If you are using JSF versions below 2.3 refer to the legacy answer at the end.

From JSF 2.3 here are scopes that can be used on JSF Backing Beans:

1. @javax.enterprise.context.ApplicationScoped: The application scope persists for the entire duration of the web application. That scope is shared among all requests and all sessions. This is useful when you have data for whole application.

2. @javax.enterprise.context.SessionScoped: The session scope persists from the time that a session is established until session termination. The session context is shared between all requests that occur in the same HTTP session. This is useful when you wont to save data for a specific client for a particular session.

3. @javax.enterprise.context.ConversationScoped: The conversation scope persists as log as the bean lives. The scope provides 2 methods: Conversation.begin() and Conversation.end(). These methods should called explicitly, either to start or end the life of a bean.

4. @javax.enterprise.context.RequestScoped: The request scope is short-lived. It starts when an HTTP request is submitted and ends after the response is sent back to the client. If you place a managed bean into request scope, a new instance is created with each request. It is worth considering request scope if you are concerned about the cost of session scope storage.

5. @javax.faces.flow.FlowScoped: The Flow scope persists as long as the Flow lives. A flow may be defined as a contained set of pages (or views) that define a unit of work. Flow scoped been is active as long as user navigates with in the Flow.

6. @javax.faces.view.ViewScoped: A bean in view scope persists while the same JSF page is redisplayed. As soon as the user navigates to a different page, the bean goes out of scope.

The following legacy answer applies JSF version before 2.3

As of JSF 2.x there are 4 Bean Scopes:

  • @SessionScoped
  • @RequestScoped
  • @ApplicationScoped
  • @ViewScoped

Session Scope: The session scope persists from the time that a session is established until session termination. A session terminates if the web application invokes the invalidate method on the HttpSession object, or if it times out.

RequestScope: The request scope is short-lived. It starts when an HTTP request is submitted and ends after the response is sent back to the client. If you place a managed bean into request scope, a new instance is created with each request. It is worth considering request scope if you are concerned about the cost of session scope storage.

ApplicationScope: The application scope persists for the entire duration of the web application. That scope is shared among all requests and all sessions. You place managed beans into the application scope if a single bean should be shared among all instances of a web application. The bean is constructed when it is first requested by any user of the application, and it stays alive until the web application is removed from the application server.

ViewScope: View scope was added in JSF 2.0. A bean in view scope persists while the same JSF page is redisplayed. (The JSF specification uses the term view for a JSF page.) As soon as the user navigates to a different page, the bean goes out of scope.

Choose the scope you based on your requirement.

Source: Core Java Server Faces 3rd Edition by David Geary & Cay Horstmann [Page no. 51 - 54] enter image description here

Jinja2 template not rendering if-elif-else statement properly

You are testing if the values of the variables error and Already are present in RepoOutput[RepoName.index(repo)]. If these variables don't exist then an undefined object is used.

Both of your if and elif tests therefore are false; there is no undefined object in the value of RepoOutput[RepoName.index(repo)].

I think you wanted to test if certain strings are in the value instead:

{% if "error" in RepoOutput[RepoName.index(repo)] %}
    <td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% elif "Already" in RepoOutput[RepoName.index(repo) %}
    <td id="good"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% else %}
    <td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% endif %}

Other corrections I made:

  • Used {% elif ... %} instead of {$ elif ... %}.
  • moved the </tr> tag out of the if conditional structure, it needs to be there always.
  • put quotes around the id attribute

Note that most likely you want to use a class attribute instead here, not an id, the latter must have a value that must be unique across your HTML document.

Personally, I'd set the class value here and reduce the duplication a little:

{% if "Already" in RepoOutput[RepoName.index(repo)] %}
    {% set row_class = "good" %}
{% else %}
    {% set row_class = "error" %}
{% endif %}
<td class="{{ row_class }}"> {{ RepoOutput[RepoName.index(repo)] }} </td>

Use <Image> with a local file

Using React Native 0.41 (in March 2017), targeting iOS, I just found it as easy as:

<Image source={require('./myimage.png')} />

The image file must exist in the same folder as the .js file requiring it.

I didn't have to change anything in the XCode project. It just worked. Maybe things have changed a lot in 2 years!

Note that if the filename has anything other than lower-case letters, or the path is anything more than "./", then for me, it started failing. Not sure what the restrictions are, but start simple and work forward.

Hope this helps someone, as many other answers here seem overly complex and full of (naughty) off-site links.

UPDATE: BTW - The official documentation for this is here:

Calling the base constructor in C#

public class Car
     public Car(string model)

public class Mercedes : Car
     public Mercedes(string model): base(model)



Mercedes mercedes = new Mercedes("CLA Shooting Brake");

Output: CLA Shooting Brake

Xcode - ld: library not found for -lPods

i have same issue with react-native library called linear-gradient, but i think the problem caused by adding blank space between -L -L... here the screen of error enter image description here

im trying all solution in this page, thank you for help

How to find count of Null and Nan values for each column in a PySpark dataframe efficiently?

For null values in the dataframe of pyspark

Dict_Null = {col:df.filter(df[col].isNull()).count() for col in df.columns}

# The output in dict where key is column name and value is null values in that column

{'#': 0,
 'Name': 0,
 'Type 1': 0,
 'Type 2': 386,
 'Total': 0,
 'HP': 0,
 'Attack': 0,
 'Defense': 0,
 'Sp_Atk': 0,
 'Sp_Def': 0,
 'Speed': 0,
 'Generation': 0,
 'Legendary': 0}

How to get an object's methods?

var methods = [];
for (var key in foo.prototype) {
    if (typeof foo.prototype[key] === "function") {

You can simply loop over the prototype of a constructor and extract all methods.

Class method differences in Python: bound, unbound and static

>>> class Class(object):
...     def __init__(self):
...         self.i = 0
...     def instance_method(self):
...         self.i += 1
...         print self.i
...     c = 0
...     @classmethod
...     def class_method(cls):
...         cls.c += 1
...         print cls.c
...     @staticmethod
...     def static_method(s):
...         s += 1
...         print s
>>> a = Class()
>>> a.class_method()
>>> Class.class_method()    # The class shares this value across instances
>>> a.instance_method()
>>> Class.instance_method() # The class cannot use an instance method
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unbound method instance_method() must be called with Class instance as first argument (got nothing instead)
>>> Class.instance_method(a)
>>> b = 0
>>> a.static_method(b)
>>> a.static_method(a.c) # Static method does not have direct access to 
>>>                      # class or instance properties.
>>> Class.c        # a.c above was passed by value and not by reference.
>>> a.c
>>> a.c = 5        # The connection between the instance
>>> Class.c        # and its class is weak as seen here.
>>> Class.class_method()
>>> a.c

FIFO based Queue implementations?

Yeah. Queue

LinkedList being the most trivial concrete implementation.

Generate PDF from HTML using pdfMake in Angularjs

was implemented that in service-now platform. No need to use other library - makepdf have all you need!

that my html part (include preloder gif):

   <div class="pdf-preview" ng-init="generatePDF(true)">
    <object data="{{c.content}}" type="application/pdf" style="width:58vh;height:88vh;" ng-if="c.content" ></object>
    <div ng-if="!c.content">
      <img src="" width="50" height="50">

this is client script (js part)

$scope.generatePDF = function (preview) {
    docDefinition = {} //you rootine to generate pdf content
    if (preview) {
        pdfMake.createPdf(docDefinition).getDataUrl(function(dataURL) {
            c.content = dataURL;

So on page load I fire init function that generate pdf content and if required preview (set as true) result will be assigned to c.content variable. On html side object will be not shown until c.content will got a value, so that will show loading gif.

Creating an Instance of a Class with a variable in Python

You can create variable like this:

x = 10 

Or this:

globals()['y'] = 100

Lets create a new class:

class Foo(object):
    def __init__(self): = 'John'

You can create class instance this way:

instance_name_1 = Foo()

Or this way:

globals()['instance_name_2'] = Foo()

Lets create a function:

def create_new_instance(class_name,instance_name):
    globals()[instance_name] = class_name()
    print('Class instance '{}' created!'.format(instance_name))

Call a function:

create_new_instance(Foo,'new_instance') #Class instance 'new_instance' created!
print( #John

Also we can write generator function:

def create_instance(class_name,instance_name):
    count = 0
    while True:
        name = instance_name + str(count)
        globals()[name] = class_name()
        count += 1
        print('Class instance: {}'.format(name))
        yield True

generator_instance = create_instance(Foo,'instance_') 

for i in range(5):

#Class instance: instance_0
#Class instance: instance_1
#Class instance: instance_2
#Class instance: instance_3
#Class instance: instance_4

print( #john
print( #john
print( #john
print( #john
print( #john

#print( #error.. we only created 5 instances.. 

next(generator_instance) #Class instance: instance_5
print( #John  Now it works.. 

How do I convert strings between uppercase and lowercase in Java?

Assuming that all characters are alphabetic, you can do this:

From lowercase to uppercase:

// Uppercase letters. 
class UpperCase {  
  public static void main(String args[]) { 
    char ch;
    for(int i=0; i < 10; i++) { 
      ch = (char) ('a' + i);

      // This statement turns off the 6th bit.   
      ch = (char) ((int) ch & 65503); // ch is now uppercase
      System.out.print(ch + " ");  

From uppercase to lowercase:

// Lowercase letters. 
class LowerCase {  
  public static void main(String args[]) { 
    char ch;
    for(int i=0; i < 10; i++) { 
      ch = (char) ('A' + i);
      ch = (char) ((int) ch | 32); // ch is now uppercase
      System.out.print(ch + " ");  

How to set order of repositories in Maven settings.xml

None of these answers were correct in my case.. the order seems dependent on the alphabetical ordering of the <id> tag, which is an arbitrary string. Hence this forced repo search order:

                <releases>  <enabled>true</enabled>  </releases>
                <snapshots> <enabled>true</enabled> </snapshots>

                <releases>  <enabled>true</enabled>  </releases>
                <snapshots> <enabled>false</enabled> </snapshots>

Delete multiple rows by selecting checkboxes using PHP

Use array notation like name="checkbox[]" in your input element. This will give you $_POST['checkbox'] as array. In the query you can utilize it as

$sql = "DELETE FROM links WHERE link_id in ";
$sql.= "('".implode("','",array_values($_POST['checkbox']))."')";

Thats one single query to delete them all.

Note: You need to escape the values passed in $_POST['checkbox'] with mysql_real_escape_string or similar to prevent SQL Injection.

Can I make a function available in every controller in angular?

I'm a bit newer to Angular but what I found useful to do (and pretty simple) is I made a global script that I load onto my page before the local script with global variables that I need to access on all pages anyway. In that script, I created an object called "globalFunctions" and added the functions that I need to access globally as properties. e.g. = myFunc();. Then, in each local script, I wrote $scope.globalFunctions = globalFunctions; and I instantly have access to any function I added to the globalFunctions object in the global script.

This is a bit of a workaround and I'm not sure it helps you but it definitely helped me as I had many functions and it was a pain adding all of them to each page.

Strangest language feature

Don't know if it is a feature or not. For some, yes, but for others it might be an annoying behavior. Anyway, I think it's worth mentioning.

In Python, the builtin function round() behaves a bit differently between Python 2x and Python 3x.

For Py 2x,

>>> round(0.4)
>>> round(0.5)
>>> round(0.51)
>>> round(1.5)

For Py 3x,

>>> round(0.4)
>>> round(0.5)
>>> round(0.51)
>>> round(1.5)

I'm just not familiar with the way round() in Py 3x works with 0.

Docs for round() in Py 2x and Py 3x.

How do I use the built in password reset/change views with my own templates

You can do the following:

  1. add to your urlpatterns (r'^/accounts/password/reset/$', password_reset)
  2. put your template in '/templates/registration/password_reset_form.html'
  3. make your app come before 'django.contrib.auth' in INSTALLED_APPS


When the templates are loaded, they are searched in your INSTALLED_APPS variable in . The order is dictated by the definition's rank in INSTALLED_APPS, so since your app come before 'django.contrib.auth' your template were loaded (reference:

Motivation of approach:

  1. I want be more dry and don't repeat for any view(defined by django) the template name (they are already defined in django)
  2. I want a smallest

Why are elementwise additions much faster in separate loops than in a combined loop?

Imagine you are working on a machine where n was just the right value for it only to be possible to hold two of your arrays in memory at one time, but the total memory available, via disk caching, was still sufficient to hold all four.

Assuming a simple LIFO caching policy, this code:

for(int j=0;j<n;j++){
    a[j] += b[j];
for(int j=0;j<n;j++){
    c[j] += d[j];

would first cause a and b to be loaded into RAM and then be worked on entirely in RAM. When the second loop starts, c and d would then be loaded from disk into RAM and operated on.

the other loop

for(int j=0;j<n;j++){
    a[j] += b[j];
    c[j] += d[j];

will page out two arrays and page in the other two every time around the loop. This would obviously be much slower.

You are probably not seeing disk caching in your tests but you are probably seeing the side effects of some other form of caching.

There seems to be a little confusion/misunderstanding here so I will try to elaborate a little using an example.

Say n = 2 and we are working with bytes. In my scenario we thus have just 4 bytes of RAM and the rest of our memory is significantly slower (say 100 times longer access).

Assuming a fairly dumb caching policy of if the byte is not in the cache, put it there and get the following byte too while we are at it you will get a scenario something like this:

  • With

    for(int j=0;j<n;j++){
     a[j] += b[j];
    for(int j=0;j<n;j++){
     c[j] += d[j];
  • cache a[0] and a[1] then b[0] and b[1] and set a[0] = a[0] + b[0] in cache - there are now four bytes in cache, a[0], a[1] and b[0], b[1]. Cost = 100 + 100.

  • set a[1] = a[1] + b[1] in cache. Cost = 1 + 1.
  • Repeat for c and d.
  • Total cost = (100 + 100 + 1 + 1) * 2 = 404

  • With

    for(int j=0;j<n;j++){
     a[j] += b[j];
     c[j] += d[j];
  • cache a[0] and a[1] then b[0] and b[1] and set a[0] = a[0] + b[0] in cache - there are now four bytes in cache, a[0], a[1] and b[0], b[1]. Cost = 100 + 100.

  • eject a[0], a[1], b[0], b[1] from cache and cache c[0] and c[1] then d[0] and d[1] and set c[0] = c[0] + d[0] in cache. Cost = 100 + 100.
  • I suspect you are beginning to see where I am going.
  • Total cost = (100 + 100 + 100 + 100) * 2 = 800

This is a classic cache thrash scenario.

How do I execute a program using Maven?

With the global configuration that you have defined for the exec-maven-plugin:


invoking mvn exec:java on the command line will invoke the plugin which is configured to execute the class org.dhappy.test.NeoTraverse.

So, to trigger the plugin from the command line, just run:

mvn exec:java

Now, if you want to execute the exec:java goal as part of your standard build, you'll need to bind the goal to a particular phase of the default lifecycle. To do this, declare the phase to which you want to bind the goal in the execution element:


With this example, your class would be executed during the package phase. This is just an example, adapt it to suit your needs. Works also with plugin version 1.1.

Stick button to right side of div

div {
 display: flex;
 flex-direction: row-reverse;

JavaScript: how to change form action attribute value based on selection?

If you only want to change form's action, I prefer changing action on-form-submit, rather than on-input-change. It fires only once.

  var formAction = $("#selectsearch").val() == "people" ? "user" : "content";
  $("#search-form").attr("action", "/search/" + formAction);

is python capable of running on multiple cores?

The answer is "Yes, But..."

But cPython cannot when you are using regular threads for concurrency.

You can either use something like multiprocessing, celery or mpi4py to split the parallel work into another process;

Or you can use something like Jython or IronPython to use an alternative interpreter that doesn't have a GIL.

A softer solution is to use libraries that don't run afoul of the GIL for heavy CPU tasks, for instance numpy can do the heavy lifting while not retaining the GIL, so other python threads can proceed. You can also use the ctypes library in this way.

If you are not doing CPU bound work, you can ignore the GIL issue entirely (kind of) since python won't aquire the GIL while it's waiting for IO.

Convert an integer to an array of digits

public static void main(String k[])
    System.out.println ("NUMBER OF VALUES ="+k.length);
    int arrymy[]=new int[k.length];
    for (int i = 0; i < k.length; i++)
        int newGues = Integer.parseInt(k[i]);
        arrymy[i] = newGues;

How to format number of decimal places in wpf using style/template?

You should use the StringFormat on the Binding. You can use either standard string formats, or custom string formats:

<TextBox Text="{Binding Value, StringFormat=N2}" />
<TextBox Text="{Binding Value, StringFormat={}{0:#,#.00}}" />

Note that the StringFormat only works when the target property is of type string. If you are trying to set something like a Content property (typeof(object)), you will need to use a custom StringFormatConverter (like here), and pass your format string as the ConverterParameter.

Edit for updated question

So, if your ViewModel defines the precision, I'd recommend doing this as a MultiBinding, and creating your own IMultiValueConverter. This is pretty annoying in practice, to go from a simple binding to one that needs to be expanded out to a MultiBinding, but if the precision isn't known at compile time, this is pretty much all you can do. Your IMultiValueConverter would need to take the value, and the precision, and output the formatted string. You'd be able to do this using String.Format.

However, for things like a ContentControl, you can much more easily do this with a Style:

<Style TargetType="{x:Type ContentControl}">
    <Setter Property="ContentStringFormat" 
            Value="{Binding Resolution, StringFormat=N{0}}" />

Any control that exposes a ContentStringFormat can be used like this. Unfortunately, TextBox doesn't have anything like that.

Check element exists in array

Look before you leap (LBYL):

if idx < len(array):
    # handle this

Easier to ask forgiveness than permission (EAFP):

except IndexError:
    # handle this

In Python, EAFP seems to be the popular and preferred style. It is generally more reliable, and avoids an entire class of bugs (time of check vs. time of use). All other things being equal, the try/except version is recommended - don't see it as a "last resort".

This excerpt is from the official docs linked above, endorsing using try/except for flow control:

This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statements.

Maven and adding JARs to system scope

Use a repository manager and install this kind of jars into it. That solves your problems at all and for all computers in your network.

How to let PHP to create subdomain automatically for each user?

The feature you are after is called Wildcard Subdomains. It allows you not have to setup DNS for each subdomain, and instead use apache rewrites for the redirection. You can find a nice tutorial here, but there are thousands of tutorials out there. Here is the necessary code from that tutorial:

    DocumentRoot /www/subdomain
    ServerName www.domain.tld
    ServerAlias *.domain.tld

However as it required the use of VirtualHosts it must be set in the server's httpd.conf file, instead of a local .htaccess.

What is Node.js?

Q: The programming model is event driven, especially the way it handles I/O.

Correct. It uses call-backs, so any request to access the file system would cause a request to be sent to the file system and then Node.js would start processing its next request. It would only worry about the I/O request once it gets a response back from the file system, at which time it will run the callback code. However, it is possible to make synchronous I/O requests (that is, blocking requests). It is up to the developer to choose between asynchronous (callbacks) or synchronous (waiting).

Q: It uses JavaScript and the parser is V8.


Q: It can be easily used to create concurrent server applications.

Yes, although you'd need to hand-code quite a lot of JavaScript. It might be better to look at a framework, such as - which comes with full online documentation and a sample application.

How do you rename a MongoDB database?

In the case you put all your data in the admin database (you shouldn't), you'll notice db.copyDatabase() won't work because your user requires a lot of privileges you probably don't want to give it. Here is a script to copy the database manually:

use old_db
db.getCollectionNames().forEach(function(collName) {

The project cannot be built until the build path errors are resolved.

This what fixed it for me...

I was having an issue with my spring-core.jar. I deleted the entire release directory located here. (I'm on win 10).


I right clicked on the project > Maven > Update project and my exclamation mark disappeared. No problems any more.

Here is the source where I found the information:

Should I learn C before learning C++?

In the process of learning C++ you will learn most of C as well. But keep in mind a lot of C++ code is not valid C. C++ was designed to be compatible with C code, so i'd say learn C++ first. Brian wrote a great answer regarding this.

Output array to CSV in Ruby

Struggling with this myself. This is my take:

require 'csv'

class CSV
  def CSV.unparse array
    CSV.generate do |csv|
      array.each { |i| csv << i }

CSV.unparse [ %w(your array), %w(goes here) ]

What is difference between MVC, MVP & MVVM design pattern in terms of coding c#

Some basic differences can be written in short:


Traditional MVC is where there is a

  1. Model: Acts as the model for data
  2. View : Deals with the view to the user which can be the UI
  3. Controller: Controls the interaction between Model and View, where view calls the controller to update model. View can call multiple controllers if needed.


Similar to traditional MVC but Controller is replaced by Presenter. But the Presenter, unlike Controller is responsible for changing the view as well. The view usually does not call the presenter.


The difference here is the presence of View Model. It is kind of an implementation of Observer Design Pattern, where changes in the model are represented in the view as well, by the VM. Eg: If a slider is changed, not only the model is updated but the data which may be a text, that is displayed in the view is updated as well. So there is a two-way data binding.