Programs & Examples On #Javascriptmvc

JavaScriptMVC is an open source jQuery-based JavaScript framework for developing JavaScript application using traditional MVC architecture.

Difference between SelectedItem, SelectedValue and SelectedValuePath

SelectedItem is an object. SelectedValue and SelectedValuePath are strings.

for example using the ListBox:

if you say give me listbox1.SelectedValue it will return the text of the currently selected item.

string value = listbox1.SelectedValue;

if you say give me listbox1.SelectedItem it will give you the entire object.

ListItem item = listbox1.SelectedItem;
string value = item.value;

How to convert uint8 Array to base64 Encoded String?

To base64-encode a UInt8Array with arbitrary data (not necessarily UTF-8) using native browser functionality:

const base64_arraybuffer = async (data) => {
    // Use a FileReader to generate a base64 data URI
    const base64url = await new Promise((r) => {
        const reader = new FileReader()
        reader.onload = () => r(reader.result)
        reader.readAsDataURL(new Blob([data]))

    The result looks like 
    "data:application/octet-stream;base64,<your base64 data>", 
    so we split off the beginning:
    return base64url.split(",", 2)[1]

// example use:
await base64_arraybuffer(new UInt8Array([1,2,3,100,200]))

Programmatically set image to UIImageView with Xcode 6.1/Swift

You just need to drag and drop an ImageView, create the outlet action, link it, and provide an image (Xcode is going to look in your assets folder for the name you provided (here: "toronto"))

In yourProject/ViewController.swift

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var imgView: UIImageView!

    override func viewDidLoad() {

        imgView.image = UIImage(named: "toronto")

"android.view.WindowManager$BadTokenException: Unable to add window" on

I got this error, but mine was coming from the Toasts, not a Dialog.

I have Activity and Fragments in my layout. Code for the Toast was in the Activity class. Fragments gets loaded before the Activity.

I think the Toast code was hit before the Context/Activity finished initializing. I think it was the getApplicationContext() in the command Toast.makeText(getApplicationContext(), "onMenutItemActionCollapse called", Toast.LENGTH_SHORT).show();

NodeJS - Error installing with NPM

Setup JavaScript Environment

1. Install Node.js

Download installer at NodeJs website. You can download the latest V6

2. Update Npm

Npm is installed together with Node.js. So don't worry.

3. Install Anaconda

Anaconda is the leading open data science platform powered by Python. The open source version of Anaconda is a high performance distribution of Python. It can help you to manage your python dependency. You can use it to create different python environment in the futher if you want to touch with it.

Node-gyp only support >= Python 2.7 and < Python 3.0

So just install the 2.7 version

4. Install Node-gyp

You can install with npm:

$ npm install -g node-gyp

You will also need to install:

  • On Windows:

    • Option 1: Install all the required tools and configurations using Microsoft's windows-build-tools using npm install --global --production windows-build-tools from an elevated PowerShell or CMD.exe (run as Administrator).

    • Option 2: Install tools and configuration manually:

    • Visual C++ Build Environment:

      • Option 1: Install Visual C++ Build Tools using the Default Install option.
      • Option 2: Install Visual Studio 2015 (or modify an existing installation) and select Common Tools for Visual C++ during setup. This also works with the free Community and Express for Desktop editions.

       [Windows Vista / 7 only] requires .NET Framework 4.5.1

    • Launch cmd, npm config set msvs_version 2015

    If the above steps didn't work for you, please visit Microsoft's Node.js Guidelines for Windows for additional tips.

If you have multiple Python versions installed, you can identify which Python version node-gyp uses by setting the '--python' variable:

$ node-gyp --python C:/Anaconda2/python.exe

If node-gyp is called by way of npm and you have multiple versions of Python installed, then you can set npm's 'python' config key to the appropriate value:

$ npm config set python C:/Anaconda2/python.exe

Future update for Node.js and npm

Download installer from their official website and direct install it. The installer will automatic help you to remove old files.

npm update npm

Future update for Python

conda update --all

How to export SQL Server database to MySQL?

You can do this easily by using Data Loader tool. I have already done this before using this tool and found it good.

Checking session if empty or not

if (HttpContext.Current.Session["emp_num"] != null)
     // code if session is not null
  • if at all above fails.

Doctrine findBy 'does not equal'

I solved this rather easily (without adding a method) so i'll share:

use Doctrine\Common\Collections\Criteria;

$repository->matching( Criteria::create()->where( Criteria::expr()->neq('id', 1) ) );

By the way, i'm using the Doctrine ORM module from within Zend Framework 2 and i'm not sure whether this would be compatible in any other case.

In my case, i was using a form element configuration like this: to show all roles except "guest" in a radio button array.

    'type' => 'DoctrineModule\Form\Element\ObjectRadio',
        'name' => 'roles',
        'options' => array(
            'label' => _('Roles'),
            'object_manager' => $this->getEntityManager(),
            'target_class'   => 'Application\Entity\Role',
            'property' => 'roleId',
            'find_method'    => array(
                'name'   => 'matching',
                'params' => array(
                    'criteria' => Criteria::create()->where(
                        Criteria::expr()->neq('roleId', 'guest')

How to filter specific apps for ACTION_SEND intent (and set a different text for each app)

If you want a customized option then you should not rely on the default dialog provided by android for this action.

What you need to do instead is roll out your own. You will need to query the PackageManager on which packages handle the action you require and then based on the reply, you apply filtering and customized text.

Specifically, take a look at the method queryIntentActivities of the PackageManager class. You build the intent that would launch the default dialog (the ACTION_SEND intent), pass that to this method and you will receive a list of objects that contain info on the activities that can handle that intent. Using that, you can choose the ones you want.

Once you build your list of packages you want to present, you need to build your own list dialog (preferably an activity with the dialog theme) which will display that list.

One thing to note though is that it's very hard to make that custom dialog look like the default one. The problem is that the theme used in that dialog is an internal theme and cannot be used by your application. You can either try to make it as similar to the native one as you want or go for a completely custom look (many apps do that like the gallery app etc)

SSRS Expression for IF, THEN ELSE

You should be able to use

IIF(Fields!ExitReason.Value = 7, 1, 0)

IF - ELSE IF - ELSE Structure in Excel

When FIND returns #VALUE!, it is an error, not a string, so you can't compare FIND(...) with "#VALUE!", you need to check if FIND returns an error with ISERROR. Also FIND can work on multiple characters.

So a simplified and working version of your formula would be:

=IF(ISERROR(FIND("abc",A1))=FALSE, "Green", IF(ISERROR(FIND("xyz",A1))=FALSE, "Yellow", "Red"))

Or, to remove the double negations:

=IF(ISERROR(FIND("abc",A1)), IF(ISERROR(FIND("xyz",A1)), "Red", "Yellow"),"Green")

How to import XML file into MySQL database table using XML_LOAD(); function

Since ID is auto increment, you can also specify ID=NULL as,

LOAD XML LOCAL INFILE '/pathtofile/file.xml' INTO TABLE my_tablename SET ID=NULL;

Calling a JSON API with Node.js

I'm using get-json very simple to use:

$ npm install get-json --save

Import get-json

var getJSON = require('get-json')

To do a GET request you would do something like:

getJSON('', function(error, response){

Adding a new entry to the PATH variable in ZSH

one liner, without opening ~/.zshrc file

echo -n 'export PATH=~/bin:$PATH' >> ~/.zshrc


echo -n 'export PATH=$HOME/bin:$PATH' >> ~/.zshrc

To see the effect, do source ~/.zshrc in the same tab or open a new tab

How to set environment variables in PyCharm?

You can set environmental variables in Pycharm's run configurations menu.

  1. Open the Run Configuration selector in the top-right and cick Edit Configurations...

    Edit Configurations...

  2. Find Environmental variables and click ...

    Environmental variables

  3. Add or change variables, then click OK

    Editing environmental variables

You can access your environmental variables with os.environ

import os

What's the advantage of a Java enum versus a class with public static final fields?

enum Benefits:

  1. Enums are type-safe, static fields are not
  2. There is a finite number of values (it is not possible to pass non-existing enum value. If you have static class fields, you can make that mistake)
  3. Each enum can have multiple properties (fields/getters) assigned - encapsulation. Also some simple methods: YEAR.toSeconds() or similar. Compare: Colors.RED.getHex() with Colors.toHex(Colors.RED)

"such as the ability to easily assign an enum element a certain value"

enum EnumX{
  public final int certainValue;
  private X(int certainValue){this.certainValue = certainValue;}

"and consequently the ability to convert an integer to an enum without a decent amount of effort" Add a method converting int to enum which does that. Just add static HashMap<Integer, EnumX> containing the mapping java enum.

If you really want to convert ord=VAL_200.ordinal() back to val_200 just use: EnumX.values()[ord]

Get image data url in JavaScript?

shiv / shim / sham

If your image(s) are already loaded (or not), this "tool" may come in handy:

        let c=document.createElement('canvas');
        c.width=this.naturalWidth; c.height=this.naturalHeight;
        c.getContext('2d').drawImage(this,0,0); return c.toDataURL(m,q);

.. but why?

This has the advantage of using the "already loaded" image data, so no extra request in needed. Aditionally it lets the end-user (programmer like you) decide the CORS and/or mime-type and quality -OR- you can leave out these arguments/parameters as described in the MDN specification here.

If you have this JS loaded (prior to when it's needed), then converting to dataURL is as simple as:


<img src="/yo.jpg" onload="console.log(this.toDataURL('image/jpeg'))">

GPU fingerprinting

If you are concerned about the "preciseness" of the bits then you can alter this tool to suit your needs as provided by @Kaiido's answer.

Python Database connection Close

You might try turning off pooling, which is enabled by default. See this discussion for more information.

import pyodbc
pyodbc.pooling = False
conn = pyodbc.connect('DRIVER=MySQL ODBC 5.1 driver;SERVER=localhost;DATABASE=spt;UID=who;PWD=testest') 

csr = conn.cursor()  
del csr

Get Environment Variable from Docker Container

The proper way to run echo "$ENV_VAR" inside the container so that the variable substitution happens in the container is:

docker exec <container_id> bash -c 'echo "$ENV_VAR"'

Remove CSS from a Div using JQuery

    removeCss: function(cssName) {
        return this.each(function() {
            var curDom = $(this);
                    function(cssToBeRemoved) {
                        curDom.css(cssToBeRemoved, '');
            return curDom;

/*example code: I prefer JQuery extend so I can use it anywhere I want to use.

$('#searchJqueryObject').removeCss('background-color,height,width'); //supports comma separated css names.



//this parse style & remove style & rebuild style. I like the first one.. but anyway exploring..
    removeCSS: function(cssName) {
        return this.each(function() {

            return $(this).attr('style',

                    function(curCssName) {
                        if (curCssName.toUpperCase().indexOf(cssName.toUpperCase() + ':') <= 0)
                            return curCssName;

int value under 10 convert to string two digit number

I will start my answer saying that most of previous answers were perfectly good answers at the time of writing them. So, thank you to them who wrote them.

Now, you can also use String Interpolation for same solution.

Edit: Adding this explanation after receiving a perfectively valid constructive comment from Heretic Monkey. I have preferred to use .ToString whenever I had need to convert an integer to string and not add the result to any other string. And, I have preferred to use interpolation whenever I had need to combine string(s) and an integer, like in below examples.

String Interpolation







Why doesn't git recognize that my file has been changed, therefore git add not working

I had a similar issue when I created a patch file in server with vi editor. It seems the issue was with spacing. When I pushed the patch from local, deployment was proper.

How to make a JSONP request from Javascript without JQuery?

Please find below JavaScript example to make a JSONP call without JQuery:

Also, you can refer my GitHub repository for reference.

window.onload = function(){_x000D_
    var callbackMethod = 'callback_' + new Date().getTime();_x000D_
    var script = document.createElement('script');_x000D_
    script.src = ''+callbackMethod;_x000D_
    window[callbackMethod] = function(data){_x000D_
        delete window[callbackMethod];_x000D_

Can .NET load and parse a properties file equivalent to Java Properties class?

No there is no built-in support for this.

You have to make your own "INIFileReader". Maybe something like this?

var data = new Dictionary<string, string>();
foreach (var row in File.ReadAllLines(PATH_TO_FILE))
  data.Add(row.Split('=')[0], string.Join("=",row.Split('=').Skip(1).ToArray()));


Edit: Updated to reflect Paul's comment.

byte array to pdf

You shouldn't be using the BinaryFormatter for this - that's for serializing .Net types to a binary file so they can be read back again as .Net types.

If it's stored in the database, hopefully, as a varbinary - then all you need to do is get the byte array from that (that will depend on your data access technology - EF and Linq to Sql, for example, will create a mapping that makes it trivial to get a byte array) and then write it to the file as you do in your last line of code.

With any luck - I'm hoping that fileContent here is the byte array? In which case you can just do

System.IO.File.WriteAllBytes("hello.pdf", fileContent);

Initialize class fields in constructor or at declaration?

What if I told you, it depends?

I in general initialize everything and do it in a consistent way. Yes it's overly explicit but it's also a little easier to maintain.

If we are worried about performance, well then I initialize only what has to be done and place it in the areas it gives the most bang for the buck.

In a real time system, I question if I even need the variable or constant at all.

And in C++ I often do next to no initialization in either place and move it into an Init() function. Why? Well, in C++ if you're initializing something that can throw an exception during object construction you open yourself to memory leaks.

Set "Homepage" in Asp.Net MVC

Attribute Routing in MVC 5

Before MVC 5 you could map URLs to specific actions and controllers by calling routes.MapRoute(...) in the RouteConfig.cs file. This is where the url for the homepage is stored (Home/Index). However if you modify the default route as shown below,

    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }

keep in mind that this will affect the URLs of other actions and controllers. For example, if you had a controller class named ExampleController and an action method inside of it called DoSomething, then the expected default url ExampleController/DoSomething will no longer work because the default route was changed.

A workaround for this is to not mess with the default route and create new routes in the RouteConfig.cs file for other actions and controllers like so,

    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    name: "Example",
    url: "hey/now",
    defaults: new { controller = "Example", action = "DoSomething", id = UrlParameter.Optional }

Now the DoSomething action of the ExampleController class will be mapped to the url hey/now. But this can get tedious to do for every time you want to define routes for different actions. So in MVC 5 you can now add attributes to match urls to actions like so,

public class HomeController : Controller
    // url is now 'index/' instead of 'home/index'
    public ActionResult Index()
        return View();
    // url is now 'create/new' instead of 'home/create'
    public ActionResult Create()
        return View();

iFrame src change event detection?

Answer based on JQuery < 3

    alert('frame has (re)loaded');

As mentioned by subharb, as from JQuery 3.0 this needs to be changed to:

$('#iframe').on('load', function() {
    alert('frame has (re)loaded ');

node.js require all files in a folder?

Can use :

  • Require selected files with name only or all files.
  • No need of absoulute path.
  • Easy to understand and use.

How to find the process id of a running Java process on Windows? And how to kill the process alone?

  1. Open Git Bash
  2. Type ps -ef | grep java
  3. Find the pid of running jdk
  4. kill -9 [pid]

how to prevent css inherit

The short story is that it's not possible to do what you want here. There's no CSS rule which is to "ignore some other rule". The only way around it is to write a more-specific CSS rule for the inner elements which reverts it to how it was before, which is a pain in the butt.

Take the example below:

<div class="red"> <!-- ignore the semantics, it's an example, yo! -->
    <p class="blue">
        Blue text blue text!
        <span class="notBlue">this shouldn't be blue</span>
<div class="green">
    <p class="blue">
        Blue text!
        <span class="notBlue">blah</span>

There's no way to make the .notBlue class revert to the parent styling. The best you can do is this:

.red, .red .notBlue {
    color: red;
.green, .green .notBlue {
    color: green;

Adding to the classpath on OSX

To specify a classpath for a single Java process, you can add a classpath option when you run the Java command.

In you command line. Use java -cp "path/to/your/jar:." main rather than just java main

The option tells Java where to search for libraries.

How to detect running app using ADB command

If you want to directly get the package name of the current app in focus, use this adb command -

adb shell dumpsys window windows | grep -E 'mFocusedApp'| cut -d / -f 1 | cut -d " " -f 7

Extra info from the result of the adb command is removed using the cut command. Original solution from here.

Go to particular revision

You can get a graphical view of the project history with tools like gitk. Just run:

gitk --all

If you want to checkout a specific branch:

git checkout <branch name>

For a specific commit, use the SHA1 hash instead of the branch name. (See Treeishes in the Git Community Book, which is a good read, to see other options for navigating your tree.)

git log has a whole set of options to display detailed or summary history too.

I don't know of an easy way to move forward in a commit history. Projects with a linear history are probably not all that common. The idea of a "revision" like you'd have with SVN or CVS doesn't map all that well in Git.

Response to preflight request doesn't pass access control check

It's easy to solve this issue just with few steps easily,without worrying about anything. Kindly,Follow the steps to solve it .

  1. open (
  2. go to installation and copy the command npm install cors to install via node terminal
  3. go to Simple Usage (Enable All CORS Requests) by scrolling.then copy and paste the complete declartion in ur project and run it...that will work for sure.. copy the comment code and paste in ur app.js or any other project and give a try ..this will work.this will unlock every cross origin resource we can switch between serves for your use

How to select specific columns in laravel eloquent

use App\Table;
// ...

if no where


Regex - Does not contain certain Characters


The caret in the character class ([^) means match anything but, so this means, beginning of string, then one or more of anything except < and >, then the end of the string.

Apply function to each column in a data frame observing each columns existing data type

The reason that max works with apply is that apply is coercing your data frame to a matrix first, and a matrix can only hold one data type. So you end up with a matrix of characters. sapply is just a wrapper for lapply, so it is not surprising that both yield the same error.

The default behavior when you create a data frame is for categorical columns to be stored as factors. Unless you specify that it is an ordered factor, operations like max and min will be undefined, since R is assuming that you've created an unordered factor.

You can change this behavior by specifying options(stringsAsFactors = FALSE), which will change the default for the entire session, or you can pass stringsAsFactors = FALSE in the data.frame() construction call itself. Note that this just means that min and max will assume "alphabetical" ordering by default.

Or you can manually specify an ordering for each factor, although I doubt that's what you want to do.

Regardless, sapply will generally yield an atomic vector, which will entail converting everything to characters in many cases. One way around this is as follows:

#Some test data
d <- data.frame(v1 = runif(10), v2 = letters[1:10], 
                v3 = rnorm(10), v4 = LETTERS[1:10],stringsAsFactors = TRUE)

d[4,] <- NA

#Similar function to DWin's answer          
fun <- function(x){
    if(is.numeric(x)){max(x,na.rm = 1)}

#Use colwise from plyr package
         v1 v2       v3 v4
1 0.8478983  j 1.999435  J

How to display a database table on to the table in the JSP page

you can also print the data onto your HTML/JSP document. like:-

<!DOCTYPE html>
    <title>Jsp Sample</title>
    <%@page import="java.sql.*;"%>
<body bgcolor=yellow>
        Connection con=(Connection)DriverManager.getConnection(
        Statement st=con.createStatement();
        ResultSet rs=st.executeQuery("select * from student;");
    %><table border=1 align=center style="text-align:center">
                <td><%=rs.getString("id") %></td>
                <td><%=rs.getString("name") %></td>
                <td><%=rs.getString("skill") %></td>
                <td><%=rs.getString("action") %></td>
    catch(Exception e){

<!--executeUpdate() mainupulation and executeQuery() for retriving-->

vertical-align with Bootstrap 3

I just did this and it does what I want it to do.

.align-middle {
  margin-top: 25%;
  margin-bottom: 25%;

And now my page looks like

<div class='container-fluid align-middle'>

 |                                |
 |  +--------------------------+  |
 |  |                          |  |
 |  |                          |  |
 |  |                          |  |
 |  |                          |  |
 |  |                          |  |
 |  +--------------------------+  |
 |                                |

Show all tables inside a MySQL database using PHP?

How to get tables


mysql> USE test;
Database changed
| Tables_in_test |
| t1             |
| t2             |
| t3             |
3 rows in set (0.00 sec)

2. SHOW TABLES IN db_name

mysql> SHOW TABLES IN another_db;
| Tables_in_another_db |
| t3                   |
| t4                   |
| t5                   |
3 rows in set (0.00 sec)

3. Using information schema

       FROM information_schema.TABLES
       WHERE TABLE_SCHEMA = 'another_db';
| t3         |
| t4         |
| t5         |
3 rows in set (0.02 sec)

to OP

you have fetched just 1 row. fix like this:

while ( $tables = $result->fetch_array())
    echo $tmp[0]."<br>";

and I think, information_schema would be better than SHOW TABLES

FROM information_schema.TABLES 
WHERE TABLE_SCHEMA = 'your database name'

while ( $tables = $result->fetch_assoc())
    echo $tables['TABLE_NAME']."<br>";

How is a CSS "display: table-column" supposed to work?

The "table-column" display type means it acts like the <col> tag in HTML - i.e. an invisible element whose width* governs the width of the corresponding physical column of the enclosing table.

See the W3C standard for more information about the CSS table model.

* And a few other properties like borders, backgrounds.

Youtube iframe wmode issue

I know this is an old question, but it still comes up in the top searches for this issue so I'm adding a new answer to help those looking for one for IE:

Adding &wmode=opaque to the end of the URL does NOT work in IE 10...

However, adding ?wmode=opaque does the trick!

Found this solution here:

How to sort pandas data frame using values from several columns?

The dataframe.sort() method is - so my understanding - deprecated in pandas > 0.18. In order to solve your problem you should use dataframe.sort_values() instead:

f.sort_values(by=["c1","c2"], ascending=[False, True])

The output looks like this:

    c1  c2
    3   10
    2   15
    2   30
    2   100
    1   20

Async image loading from url inside a UITableView cell - image changes to wrong image while scrolling

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
        MyCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];

        cell.poster.image = nil; // or cell.poster.image = [UIImage imageNamed:@"placeholder.png"];

        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"", self.myJson[indexPath.row][@"movieId"]]];

        NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            if (data) {
                UIImage *image = [UIImage imageWithData:data];
                if (image) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        MyCell *updateCell = (id)[tableView cellForRowAtIndexPath:indexPath];
                        if (updateCell)
                            updateCell.poster.image = image;
        [task resume];

        return cell;

How does Git handle symbolic links?

You can find out what Git does with a file by seeing what it does when you add it to the index. The index is like a pre-commit. With the index committed, you can use git checkout to bring everything that was in the index back into the working directory. So, what does Git do when you add a symbolic link to the index?

To find out, first, make a symbolic link:

$ ln -s /path/referenced/by/symlink symlink

Git doesn't know about this file yet. git ls-files lets you inspect your index (-s prints stat-like output):

$ git ls-files -s ./symlink

Now, add the contents of the symbolic link to the Git object store by adding it to the index. When you add a file to the index, Git stores its contents in the Git object store.

$ git add ./symlink

So, what was added?

$ git ls-files -s ./symlink
120000 1596f9db1b9610f238b78dd168ae33faa2dec15c 0       symlink

The hash is a reference to the packed object that was created in the Git object store. You can examine this object if you look in .git/objects/15/96f9db1b9610f238b78dd168ae33faa2dec15c in the root of your repository. This is the file that Git stores in the repository, that you can later check out. If you examine this file, you'll see it is very small. It does not store the contents of the linked file. To confirm this, print the contents of the packed repository object with git cat-file:

$ git cat-file -p 1596f9db1b9610f238b78dd168ae33faa2dec15c

(Note 120000 is the mode listed in ls-files output. It would be something like 100644 for a regular file.)

But what does Git do with this object when you check it out from the repository and into your filesystem? It depends on the core.symlinks config. From man git-config:


If false, symbolic links are checked out as small plain files that contain the link text.

So, with a symbolic link in the repository, upon checkout you either get a text file with a reference to a full filesystem path, or a proper symbolic link, depending on the value of the core.symlinks config.

Either way, the data referenced by the symlink is not stored in the repository.

Instagram: Share photo from webpage

Updated June 2020

It is no longer possible... allegedly. If you have a Facebook or Instagram dedicated contact (because you work in either a big agency or with a big client) it may potentially be possible depending on your use case, but it's highly discouraged.

Before December 2019:

It is now "possible":

The Content Publishing API is a subset of Instagram Graph API endpoints that allow you to publish media objects. Publishing media objects with this API is a two step process — you first create a media object container, then publish the container on your Business Account.

Its worth noting that "The Content Publishing API is in closed beta with Facebook Marketing Partners and Instagram Partners only. We are not accepting new applicants at this time." from


Here What i did in Django 2.0. Set First MEDIA_ROOT an MEDIA_URL in

MEDIA_ROOT = os.path.join(BASE_DIR, 'data/') # 'data' is my media folder
MEDIA_URL = '/media/'

Then Enable the media context_processors in TEMPLATE_CONTEXT_PROCESSORS by adding

    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [],
    'APP_DIRS': True,
    'OPTIONS': {
        'context_processors': [
            #here add your context Processors

Your media context processor is enabled, Now every RequestContext will contain a variable MEDIA_URL.

Now you can access this in your template_name.html

<p><img src="{{ MEDIA_URL }}/image_001.jpeg"/></p>

HTTP Status 405 - Method Not Allowed Error for Rest API

You might be doing a PUT call for GET operation Please check once

How do I access Configuration in any class in ASP.NET Core?

I know this is old but given the IOptions patterns is relatively simple to implement:

  1. Class with public get/set properties that match the settings in the configuration

    public class ApplicationSettings
        public string UrlBasePath { get; set; }
  2. register your settings

    public void ConfigureServices(IServiceCollection services)
  3. inject via IOptions

    public class HomeController
       public HomeController(IOptions<ApplicationSettings> appSettings)
       { ...
        // or better practice create a readonly private reference

I'm not sure why you wouldn't just do this.

jquery disable form submit on enter

Usually form is submitted on Enter when you have focus on input elements.

We can disable Enter key (code 13) on input elements within a form:

$('form input').on('keypress', function(e) {
    return e.which !== 13;


IN vs OR in the SQL WHERE Clause

The OR operator needs a much more complex evaluation process than the IN construct because it allows many conditions, not only equals like IN.

Here is a like of what you can use with OR but that are not compatible with IN: greater. greater or equal, less, less or equal, LIKE and some more like the oracle REGEXP_LIKE. In addition consider that the conditions may not always compare the same value.

For the query optimizer it's easier to to manage the IN operator because is only a construct that defines the OR operator on multiple conditions with = operator on the same value. If you use the OR operator the optimizer may not consider that you're always using the = operator on the same value and, if it doesn't perform a deeper and very much more complex elaboration, it could probably exclude that there may be only = operators for the same values on all the involved conditions, with a consequent preclusion of optimized search methods like the already mentioned binary search.

[EDIT] Probably an optimizer may not implement optimized IN evaluation process, but this doesn't exclude that one time it could happen(with a database version upgrade). So if you use the OR operator that optimized elaboration will not be used in your case.

How do I get the opposite (negation) of a Boolean in Python?

You can just compare the boolean array. For example

X = [True, False, True]


Y = X == False

would give you

Y = [False, True, False]

How to change MySQL data directory?

We had to move MySQL into /home directory because it was mapped from another physical disc. In order to make live simpler, instead of changing directory in my.cnf, we have mapped the new directory /home/mysql in the place of the original directory /var/lib/mysql. It works for us like a charm (tested on CentOS 7.1).

Create the new dir and set correct permissions.

mkdir -p /home/mysql
chmod 755 /home/mysql
chown mysql:mysql /home/mysql

Stop MySQL if running.

systemctl stop mysql

Move the data dir.

mv -f /var/lib/mysql/* /home/mysql

Create a permanent mount and execute it.

echo "/home/mysql /var/lib/mysql none    bind   0 0" >> /etc/fstab
mount -a

Restart the server.

systemctl start mysql

Merge two json/javascript arrays in to one array

You can achieve this using Lodash _.merge function.

var json1 = [{id:1, name: 'xxx'}];_x000D_
var json2 = [{id:2, name: 'xyz'}];_x000D_
var merged = _.merge(_.keyBy(json1, 'id'), _.keyBy(json2, 'id'));_x000D_
var finalObj = _.values(merged);_x000D_
<script src="[email protected]/lodash.min.js"></script>

How to display a loading screen while site content loads

You can use <progress> element in HTML5. See this page for source code and live demo.

here is the progress element...

<progress id="progressbar" value="20" max="100"></progress>

this will have the loading value starting from 20. Of course only the element wont suffice. You need to move it as the script loads. For that we need JQuery. Here is a simple JQuery script that starts the progress from 0 to 100 and does something in defined time slot.

        $(document).ready(function() {
         alert('Sorry your brower does not support HTML5 progress bar');
         } else {
         var progressbar = $('#progressbar'),
         max = progressbar.attr('max'),
         time = (1000/max)*10, 
         value = progressbar.val();
        var loading = function() {
        value += 1;
        addValue = progressbar.val(value);
        $('.progress-value').html(value + '%');
        if (value == max) {
        //Do Something
if (value == 16) {
//Do something 
if (value == 38) {
//Do something
if (value == 55) {
//Do something 
if (value == 72) {
//Do something 
if (value == 1) {
//Do something 
if (value == 86) {
//Do something 

var animate = setInterval(function() {
}, time);

Add this to your HTML file.

<div class="demo-wrapper html5-progress-bar">
<div class="progress-bar-wrapper">
 <progress id="progressbar" value="0" max="100"></progress>
 <span class="progress-value">0%</span>

Hope this will give you a start.

Why does corrcoef return a matrix?

The correlation matrix is the standard way to express correlations between an arbitrary finite number of variables. The correlation matrix of N data vectors is a symmetric N × N matrix with unity diagonal. Only in the case N = 2 does this matrix have one free parameter.

install cx_oracle for python

Alternatively you can install the cx_Oracle module without the PIP using the following steps

  1. Download the source from here [cx_Oracle-6.1.tar.gz ]
  2. Extract the tar using the following commands (Linux)

    gunzip cx_Oracle-6.1.tar.gz

    tar -xf cx_Oracle-6.1.tar

  3. cd cx_Oracle-6.1

  4. Build the module

    python build

  5. Install the module

    python install

How to get the current time in YYYY-MM-DD HH:MI:Sec.Millisecond format in Java?

I would use something like this:

String.format("%tF %<tT.%<tL", dateTime);

Variable dateTime could be any date and/or time value, see JavaDoc for Formatter.

How to revert initial git commit?

You just need to delete the branch you are on. You can't use git branch -D as this has a safety check against doing this. You can use update-ref to do this.

git update-ref -d HEAD

Do not use rm -rf .git or anything like this as this will completely wipe your entire repository including all other branches as well as the branch that you are trying to reset.

How to color System.out.println output?


You may not be able to color Window's cmd prompt, but it should work in many unix (or unix-like) terminals.

Also, note that some terminals simply won't support some (if any) ANSI escape sequences and, especially, 24-bit colors.


Please refer to the section Curses at the bottom for the best solution. For a personal or easy solution (although not as cross-platform solution), refer to the ANSI Escape Sequences section.


  • java: System.out.println((char)27 + "[31m" + "ERROR MESSAGE IN RED");

  • python: print(chr(27) + "[31m" + "ERROR MESSAGE IN RED")

  • bash or zsh: printf '\x1b[31mERROR MESSAGE IN RED'
    • this may also work for Os X: printf '\e[31mERROR MESSAGE IN RED'
  • sh: printf 'CTRL+V,CTRL+[[31mERROR MESSAGE IN RED'
    • ie, press CTRL+V and then CTRL+[ in order to get a "raw" ESC character when escape interpretation is not available
    • If done correctly, you should see a ^[. Although it looks like two characters, it is really just one, the ESC character.
    • You can also press CTRL+V,CTRL+[ in vim in any of the programming or sripting langauges because that uses a literal ESC character
    • Also, you can replace Ctrl+[ with ESC … eg, you can use CTRL+V,ESC, but I find the former easier, since I am already pressing CTRL and since [ is less out of the way.

ANSI Escape Sequences

Background on Escape Sequences

While it is not the best way to do it, the easiest way to do this in a programming or scripting language is to use escape sequences. From that link:

An escape sequence is a series of characters used to change the state of computers and their attached peripheral devices. These are also known as control sequences, reflecting their use in device control.

Backgound on ANSI Escape Sequences

However, it gets even easier than that in video text terminals, as these terminals use ANSI escape sequences. From that link:

ANSI escape sequences are a standard for in-band signaling to control the cursor location, color, and other options on video text terminals. Certain sequences of bytes, most starting with Esc and '[', are embedded into the text, which the terminal looks for and interprets as commands, not as character codes.

How to Use ANSI Escape Sequences


  • Escape sequences begin with an escape character; for ANSI escape sequences, the sequence always begins with ESC (ASCII: 27 / hex: 0x1B).
  • For a list of what you can do, refer to the ANSI Escape Sequence List on Wikipedia

In Programming Languages

Some programming langauges (like Java) will not interpret \e or \x1b as the ESC character. However, we know that the ASCII character 27 is the ESC character, so we can simply typecast 27 to a char and use that to begin the escape sequence.

Here are some ways to do it in common programming languages:

  • Java

    • System.out.println((char)27 + "[33mYELLOW");
  • Python 3

    • print(chr(27) + "[34mBLUE");
    • print("\x1b[35mMAGENTA");
      • Note that \x1b is interpretted correctly in python
  • Node JS

    • The following will NOT color output in JavaScript in the Web Console
    • console.log(String.fromCharCode(27) + "[36mCYAN");
    • console.log("\x1b[30;47mBLACK_ON_WHITE");
      • Note that \x1b also works in node

In Shell Prompt OR Scripts

If you are working with bash or zsh, it is quite easy to color the output (in most terminals). In Linux, Os X, and in some Window's terminals, you can check to see if your terminal supports color by doing both of the following:

  • printf '\e[31mRED'
  • printf '\x1b[31mRED'

If you see color for both, then that's great! If you see color for only one, then use that sequence. If you do not see color for either of them, then double check to make sure you typed everything correctly and that you are in bash or zsh; if you still do not see any color, then your terminal probably does not support ANSI escape sequences.

If I recall correctly, linux terminals tend to support both \e and \x1b escape sequences, while os x terminals only tend to support \e, but I may be wrong. Nonetheless, if you see something like the following image, then you're all set! (Note that I am using the shell, zsh, and it is coloring my prompt string; also, I am using urxvt as my terminal in linux.)

ANSI Escape Sequences Coloring Text Red

"How does this work?" you might ask. Bascially, printf is interpretting the sequence of characters that follows (everything inside of the single-quotes). When printf encounters \e or \x1b, it will convert these characters to the ESC character (ASCII: 27). That's just what we want. Now, printf sends ESC31m, and since there is an ESC followed by a valid ANSI escape sequence, we should get colored output (so long as it is supported by the terminal).

You can also use echo -e '\e[32mGREEN' (for example), to color output. Note that the -e flag for echo "[enables] interpretation of backslash escapes" and must be used if you want echo to appropriately interpret the escape sequence.

More on ANSI Escape Sequences

ANSI escape sequences can do more than just color output, but let's start with that, and see exactly how color works; then, we will see how to manipulate the cursor; finally, we'll take a look and see how to use 8-bit color and also 24-bit color (although it only has tenuous support).

On Wikipedia, they refer to ESC[ as CSI, so I will do the same.


To color output using ANSI escapes, use the following:

  • CSI n m
    • CSI: escape character—^[[ or ESC[
    • n: a number—one of the following:
      • 30-37, 39: foreground
      • 40-47, 49: background
    • m: a literal ASCII m—terminates the escape sequence

I will use bash or zsh to demonstrate all of the possible color combinations. Plop the following in bash or zsh to see for yourself (You may need to replace \e with \x1b):

  • for fg in {30..37} 39; do for bg in {40..47} 49; do printf "\e[${fg};${bg}m~TEST~"; done; printf "\n"; done;


various foreground/background colors using ANSI escapes

Quick Reference (Color)

|  fg  |  bg  |  color    |
|  30  |  40  |  black    |
|  31  |  41  |  red      |
|  32  |  42  |  green    |
|  33  |  43  |  yellow   |
|  34  |  44  |  blue     |
|  35  |  45  |  magenta  |
|  36  |  46  |  cyan     |
|  37  |  47  |  white    |
|  39  |  49  |  default  |

Select Graphic Rendition (SGR)

SGR just allows you to change the text. Many of these do not work in certain terminals, so use these sparingly in production-level projects. However, they can be useful for making program output more readable or helping you distinguish between different types of output.

Color actually falls under SGR, so the syntax is the same:

  • CSI n m
    • CSI: escape character—^[[ or ESC[
    • n: a number—one of the following:
      • 0: reset
      • 1-9: turns on various text effects
      • 21-29: turns off various text effects (less supported than 1-9)
      • 30-37, 39: foreground color
      • 40-47, 49: background color
      • 38: 8- or 24-bit foreground color (see 8/24-bit Color below)
      • 48: 8- or 24-bit background color (see 8/24-bit Color below)
    • m: a literal ASCII m—terminates the escape sequence

Although there is only tenuous support for faint (2), italic (3), underline (4), blinking (5,6), reverse video (7), conceal (8), and crossed out (9), some (but rarely all) tend to work on linux and os x terminals.

It's also worthwhile to note that you can separate any of the above attributes with a semi-colon. For example printf '\e[34;47;1;3mCRAZY TEXT\n' will show CRAZY TEXT with a blue foreground on a white background, and it will be bold and italic.


string attributes together example screenshot

Plop the following in your bash or zsh shell to see all of the text effects you can do. (You may need to replace \e with \x1b.)

  • for i in {1..9}; do printf "\e[${i}m~TEST~\e[0m "; done


SGR state 1 SGR state 2

You can see that my terminal supports all of the text effects except for faint (2), conceal (8) and cross out (9).

Quick Reference (SGR Attributes 0-9)

|  n  |  effect          |
|  0  |  reset           |
|  1  |  bold            |
|  2  |  faint*          |
|  3  |  italic**        |
|  4  |  underline       |
|  5  |  slow blink      |
|  6  |  rapid blink*    |
|  7  |  inverse         |
|  8  |  conceal*        |
|  9  |  strikethrough*  |

* not widely supported
** not widely supported and sometimes treated as inverse

8-bit Color

While most terminals support this, it is less supported than 0-7,9 colors.


  • CSI 38;5; n m
    • CSI: escape character—^[[ or ESC[
    • 38;5;: literal string that denotes use of 8-bit colors for foreground
    • n: a number—one of the following:
      • 0-255

If you want to preview all of the colors in your terminal in a nice way, I have a nice script on

It looks like this:

8-bit color example screenshot

If you want to change the background using 8-bit colors, just replace the 38 with a 48:

  • CSI 48;5; n m
    • CSI: escape character—^[[ or ESC[
    • 48;5;: literal string that denotes use of 8-bit colors for background
    • n: a number—one of the following:
      • 0-255

24-bit Color

Also known as true color, 24-bit color provides some really cool functionality. Support for this is definitely growing (as far as I know it works in most modern terminals except urxvt, my terminal [insert angry emoji]).

24-bit color is actually supported in vim (see the vim wiki to see how to enable 24-bit colors). It's really neat because it pulls from the colorscheme defined for gvim; eg, it uses the fg/bg from highlight guibg=#______ guifg=#______ for the 24-bit colors! Neato, huh?

Here is how 24-bit color works:

  • CSI 38;2; r ; g ; b m
    • CSI: escape character—^[[ or ESC[
    • 38;2;: literal string that denotes use of 24-bit colors for foreground
    • r,g,b: numbers—each should be 0-255

To test just a few of the many colors you can have ((2^8)^3 or 2^24 or 16777216 possibilites, I think), you can use this in bash or zsh:

  • for r in 0 127 255; do for g in 0 127 255; do for b in 0 127 255; do printf "\e[38;2;${r};${g};${b}m($r,$g,$b)\e[0m "; done; printf "\n"; done; done;

Result (this is in gnome-terminal since urxvt DOES NOT SUPPORT 24-bit color ... get it together, urxvt maintainer ... for real):

24-bit color example screenshot

If you want 24-bit colors for the background ... you guessed it! You just replace 38 with 48:

  • CSI 48;2; r ; g ; b m
    • CSI: escape character—^[[ or ESC[
    • 48;2;: literal string that denotes use of 24-bit colors for background
    • r,g,b: numbers—each should be 0-255

Inserting Raw Escape Sequences

Sometimes \e and \x1b will not work. For example, in the sh shell, sometimes neither works (although it does on my system now, I don't think it used to).

To circumvent this, you can use CTRL+V,CTRL+[ or CTRLV,ESC

This will insert a "raw" ESC character (ASCII: 27). It will look like this ^[, but do not fret; it is only one character—not two.


sh raw escape char example screenshot


Refer to the Curses (Programming Library) page for a full reference on curses. It should be noted that curses only works on unix and unix-like operating systems.

Up and Running with Curses

I won't go into too much detail, for search engines can reveal links to websites that can explain this much better than I can, but I'll discuss it briefly here and give an example.

Why Use Curses Over ANSI Escapes?

If you read the above text, you might recall that \e or \x1b will sometimes work with printf. Well, sometimes \e and \x1b will not work at all (this is not standard and I have never worked with a terminal like this, but it is possible). More importantly, more complex escape sequences (think Home and other multi-character keys) are difficult to support for every terminal (unless you are willing to spend a lot of time and effort parsing terminfo and termcap and and figuring out how to handle every terminal).

Curses solves this problem. Basically, it is able to understand what capabilities a terminal has, using these methods (as described by the wikipedia article linked above):

Most implementations of curses use a database that can describe the capabilities of thousands of different terminals. There are a few implementations, such as PDCurses, which use specialized device drivers rather than a terminal database. Most implementations use terminfo; some use termcap. Curses has the advantage of back-portability to character-cell terminals and simplicity. For an application that does not require bit-mapped graphics or multiple fonts, an interface implementation using curses will usually be much simpler and faster than one using an X toolkit.

Most of the time, curses will poll terminfo and will then be able to understand how to manipulate the cursor and text attributes. Then, you, the programmer, use the API provided by curses to manipulate the cursor or change the text color or other attributes if the functionality you seek is desired.

Example with Python

I find python is really easy to use, but if you want to use curses in a different programming language, then simply search it on duckduckgo or any other search engine. :) Here is a quick example in python 3:

import curses

def main(stdscr):
    # allow curses to use default foreground/background (39/49)

    # Clear screen

    curses.init_pair(1, curses.COLOR_RED, -1)
    curses.init_pair(2, curses.COLOR_GREEN, -1)
    stdscr.addstr("ERROR: I like tacos, but I don't have any.\n", curses.color_pair(1))
    stdscr.addstr("SUCCESS: I found some tacos.\n", curses.color_pair(2))

    stdscr.refresh() # make sure screen is refreshed
    stdscr.getkey()  # wait for user to press key

if __name__ == '__main__':


enter image description here

You might think to yourself that this is a much more round-about way of doing things, but it really is much more cross-platform (really cross-terminal … at least in the unix- and unix-like-platform world). For colors, it is not quite as important, but when it comes to supporting other multi-sequence escape sequences (such as Home, End, Page Up, Page Down, etc), then curses becomes all the more important.

Example with Tput

  • tput is a command line utility for manipulating cursor and text
  • tput comes with the curses package. If you want to use cross-terminal (ish) applications in the terminal, you should use tput, as it parses terminfo or whatever it needs to and uses a set of standardized commands (like curses) and returns the correct escape sequence.
  • example:
echo "$(tput setaf 1)$(tput bold)ERROR:$(tput sgr0)$(tput setaf 1) My tacos have gone missing"
echo "$(tput setaf 2)$(tput bold)SUCCESS:$(tput sgr0)$(tput setaf 2) Oh good\! I found my tacos\!"


example with tput

More Info on Tput

how to rename an index in a cluster?

As such there is no direct method to copy or rename index in ES (I did search extensively for my own project)

However a very easy option is to use a popular migration tool [Elastic-Exporter].

[PS: this is not my blog, just stumbled upon and found it good]

Thereby you can copy index/type and then delete the old one.

In Java, can you modify a List while iterating through it?

Use CopyOnWriteArrayList
and if you want to remove it, do the following:

for (Iterator<String> it = userList.iterator(); it.hasNext() ;)
    if (wordsToRemove.contains(word))

Maximum length of the textual representation of an IPv6 address?

As indicated a standard ipv6 address is at most 45 chars, but an ipv6 address can also include an ending % followed by a "scope" or "zone" string, which has no fixed length but is generally a small positive integer or a network interface name, so in reality it can be bigger than 45 characters. Network interface names are typically "eth0", "eth1", "wlan0", so choosing 50 as the limit is likely good enough.

Using atan2 to find angle between two vectors

You don't have to use atan2 to calculate the angle between two vectors. If you just want the quickest way, you can use dot(v1, v2)=|v1|*|v2|*cos A to get

A = Math.acos( dot(v1, v2)/(v1.length()*v2.length()) );

XML shape drawable not rendering desired color

In drawable I use this xml code to define the border and background:

<shape xmlns:android=""> 
  <stroke android:width="4dp" android:color="#D8FDFB" /> 
  <padding android:left="7dp" android:top="7dp" 
    android:right="7dp" android:bottom="7dp" /> 
  <corners android:radius="4dp" /> 
  <solid android:color="#f0600000"/> 

Getting Spring Application Context

Do autowire in Spring bean as below : @Autowired private ApplicationContext appContext;

you will the applicationcontext object.

How do I remove lines between ListViews on Android?

If this android:divider="@null" doesn't work, maybe changing your ListViews for Recycler Views? 

Open CSV file via VBA (performance)

Workbooks.Open does work too.

Workbooks.Open ActiveWorkbook.Path & "\Temp.csv", Local:=True

this works/is needed because i use Excel in germany and excel does use "," to separate .csv by default because i use an english installation of windows. even if you use the code below excel forces the "," separator.

Workbooks.Open ActiveWorkbook.Path & "\Test.csv", , , 6, , , , , ";"

and Workbooks.Open ActiveWorkbook.Path & "\Temp.csv", , , 4 +variants of this do not work(!)

why do they even have the delimiter parameter if it is blocked by the Local parameter ?! this makes no sense at all. but now it works.

How could I create a list in c++?

Why reinvent the wheel. Just use the STL list container.

#include <list>

// in some function, you now do...
std::list<int> mylist; // integer list

More information...

onchange event on input type=range is not triggering in firefox while dragging

I'm posting this as an answer in case you are like me and cannot figure out why the range type input doesn't work on ANY mobile browsers. If you develop mobile apps on your laptop and use the responsive mode to emulate touch, you will notice the range doesn't even move when you have the touch simulator activated. It starts moving when you deactivate it. I went on for 2 days trying every piece of code I could find on the subject and could not make it work for the life of me. I provide a WORKING solution in this post.

Mobile Browsers And Hybrid Apps

Mobile browsers run using a component called Webkit for iOS and WebView for Android. The WebView/WebKit enables you to embed a web browser, which does not have any chrome or firefox (browser) controls including window frames, menus, toolbars and scroll bars into your activity layout. In other words, mobile browsers lack a lot of web components normally found in regular browsers. This is the problem with the range type input. If the user's browser doesn't support range type, it will fall back and treat it as a text input. This is why you cannot move the range when the touch simulator is activated.

Read more here on browser compatibility

jQuery Slider

jQuery provides a slider that somehow works with touch simulation but it is choppy and not very smooth. It wasn't satisfying to me and it probably wont be for you either but you can make it work more smoothly if you combine it with jqueryUi.

Best Solution : Range Touch

If you develop hybrid apps on your laptop, there is a simple and easy library you can use to enable range type input to work with touch events.

This library is called Range Touch.


For more information on this issue check this thread here

Recreating the HTML5 range input for Mobile Safari (webkit)?

including parameters in OPENQUERY

Just try it this way, should work, easy! In your WHERE clause, after column name and equal to sign:- add TWO single quotes, your search value and then THREE single quotes. Close the bracket.


vagrant login as root by default

I know this is an old question, but looking at the original question, it looks like the user just wanted to run a command as root, that's what I need to do when I was searching for an answer and stumbled across the question.

So this one is worth knowing in my opinion:

vagrant ssh servername -c "echo vagrant | sudo -S shutdown 0"

vagrant is the password being echoed into the the sudo command, because as we all know, the vagrant account has sudo privileges and when you sudo, you need to specify the password of the user account, not root..and of course by default, the vagrant user's password is vagrant !

By default you need root privileges to shutdown so I guess doing a shutdown is a good test.

Obviously you don't need to specify a server name if there is only one for that vagrant environment. Also, we're talking about local vagrant virtual machine to the host, so there isn't really any security issue that I can see.

Hope this helps.

Errno 13 Permission denied Python

The problem here is your user doesn't have proper rights/permissions to open the file this means that you'd need to grant some administrative privileges to your python ide before you run that command.

As you are a windows user you just need to right click on python ide => select option 'Run as Administrator' and then run your command.

And if you are using the command line to run the codes, do the same open the command prompt with admin rights. Hope it helps

How to Create a script via batch file that will uninstall a program if it was installed on windows 7 64-bit or 32-bit

wmic can call an uninstaller. I haven't tried this, but I think it might work.

wmic /node:computername /user:adminuser /password:password product where name="name of application" call uninstall

If you don't know exactly what the program calls itself, do

wmic product get name | sort

and look for it. You can also uninstall using SQL-ish wildcards.

wmic /node:computername /user:adminuser /password:password product where "name like '%j2se%'" call uninstall

... for example would perform a case-insensitive search for *j2se* and uninstall "J2SE Runtime Environment 5.0 Update 12". (Note that in the example above, %j2se% is not an environment variable, but simply the word "j2se" with a SQL-ish wildcard on each end. If your search string could conflict with an environment or script variable, use double percents to specify literal percent signs, like %%j2se%%.)

If wmic prompts for y/n confirmation before completing the uninstall, try this:

echo y | wmic /node:computername /user:adminuser /password:password product where name="whatever" call uninstall

... to pass a y to it before it even asks.

I haven't tested this, but it's worth a shot anyway. If it works on one computer, then you can just loop through a text file containing all the computer names within your organization using a for loop, or put it in a domain policy logon script.

Grant Select on a view not base table when base table is in a different database

You can grant permissions on a view and not the base table. This is one of the reasons people like using views.

Have a look here: GRANT Object Permissions (Transact-SQL)

What can I use for good quality code coverage for C#/.NET?

Code coverage features, as well as programmable API's, come with Visual Studio 2010. Sadly, the only two editions that include the full Code Coverage capabilities are Premium and Ultimate. However, I do believe the API's will be available with any edition, so creating code coverage files and writing a viewer for the coverage info would likely be possible.

C++ cout hex values?

C++20 std::format

This is now the cleanest method in my opinion, as it does not pollute std::cout state with std::hex:


#include <format>
#include <string>

int main() {
    std::cout << std::format("{:x} {:#x} {}\n", 16, 17, 18);

Expected output:

10 0x11 18

Not yet implemented on GCC 10.0.1, Ubuntu 20.04.

But the awesome library that became C++20 and should be the same worked once installed with:

git clone
cd fmt
git checkout 061e364b25b5e5ca7cf50dd25282892922375ddc
mkdir build
cmake ..
sudo make install


#include <fmt/core.h>
#include <iostream>

int main() {
    std::cout << fmt::format("{:x} {:#x} {}\n", 16, 17, 18);

Compile and run:

g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o main2.out main2.cpp -lfmt

Documented at:

More info at: std::string formatting like sprintf

Pre-C++20: cleanly print and restore std::cout to previous state


#include <iostream>
#include <string>

int main() {
    std::ios oldState(nullptr);
    std::cout << std::hex;
    std::cout << 16 << std::endl;
    std::cout << 17 << std::endl;

Compile and run:

g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o main.out main.cpp



More details: Restore the state of std::cout after manipulating it

Tested on GCC 10.0.1, Ubuntu 20.04.

How can I push a specific commit to a remote, and not previous commits?

To push up through a given commit, you can write:

git push <remotename> <commit SHA>:<remotebranchname>

provided <remotebranchname> already exists on the remote. (If it doesn't, you can use git push <remotename> <commit SHA>:refs/heads/<remotebranchname> to autocreate it.)

If you want to push a commit without pushing previous commits, you should first use git rebase -i to re-order the commits.

How do you convert a byte array to a hexadecimal string in C?

Slightly modified Yannith version. It is just I like to have it as a return value

typedef struct {_x000D_
   size_t len;_x000D_
   uint8_t *bytes;_x000D_
} vdata;_x000D_
char* vdata_get_hex(const vdata data)_x000D_
   char hex_str[]= "0123456789abcdef";_x000D_
   char* out;_x000D_
   out = (char *)malloc(data.len * 2 + 1);_x000D_
   (out)[data.len * 2] = 0;_x000D_
   if (!data.len) return NULL;_x000D_
   for (size_t i = 0; i < data.len; i++) {_x000D_
      (out)[i * 2 + 0] = hex_str[(data.bytes[i] >> 4) & 0x0F];_x000D_
      (out)[i * 2 + 1] = hex_str[(data.bytes[i]     ) & 0x0F];_x000D_
   return out;_x000D_

Get Request and Session Parameters and Attributes from JSF pages

Assuming that you already put your object as attribute on the session map of the current instance of the FacesContext from your managed-bean, you can get it from the JSF page by :

<h:outputText value="#{sessionScope['yourObject'] }" />

If your object has a property, get it by:

<h:ouputText value="#{sessionScope['yourObject'].anyProperty }" />

how do I initialize a float to its max/min value?

You can use std::numeric_limits which is defined in <limits> to find the minimum or maximum value of types (As long as a specialization exists for the type). You can also use it to retrieve infinity (and put a - in front for negative infinity).

#include <limits>



As noted in the comments, min() returns the lowest possible positive value. In other words the positive value closest to 0 that can be represented. The lowest possible value is the negative of the maximum possible value.

There is of course the std::max_element and min_element functions (defined in <algorithm>) which may be a better choice for finding the largest or smallest value in an array.

How to show math equations in general github's markdown(not github's blog)

Regarding tex?image conversion, the tool LaTeXiT produces much higher quality output. I believe it is standard in most TeX distributions but you can certainly find it online if you don't already have it. All you need to do is put it in the TeX, drag the image to your desktop, then drag from your desktop to an image hosting site (I use imgur).

Use string contains function in oracle SQL query

The answer of ADTC works fine, but I've find another solution, so I post it here if someone wants something different.

I think ADTC's solution is better, but mine's also works.

Here is the other solution I found

from   person p
where  instr(,chr(8211)) > 0; --contains the character chr(8211) 
                                    --at least 1 time

Thank you.

How to bind Dataset to DataGridView in windows application

you can set the dataset to grid as follows:

//assuming your dataset object is ds

datagridview1.datasource= ds;
datagridview1.datamember= tablename.ToString();

tablename is the name of the table, which you want to show on the grid.

I hope, it helps.


Fetch the row which has the Max value for a column

If (UserID, Date) is unique, i.e. no date appears twice for the same user then:

select TheTable.UserID, TheTable.Value
from TheTable inner join (select UserID, max([Date]) MaxDate
                          from TheTable
                          group by UserID) UserMaxDate
     on TheTable.UserID = UserMaxDate.UserID
        TheTable.[Date] = UserMaxDate.MaxDate;

Sorting dictionary keys in python

I like this one:

sorted(d, key=d.get)

Xcode doesn't see my iOS device but iTunes does

My app worked on all simulators but not on my device. I tried just about all the steps from each comment and didn't have any luck. I went to my device settings and switched my "Personal Hotspot" from off to on. Then it was all good!

How to construct a relative path in Java from two absolute paths (or URLs)?

If you know the second string is part of the first:

String s1 = "/var/data/stuff/xyz.dat";
String s2 = "/var/data";
String s3 = s1.substring(s2.length());

or if you really want the period at the beginning as in your example:

String s3 = ".".concat(s1.substring(s2.length()));

How to check if iframe is loaded or it has a content?

I had the same issue and added to this, i needed to check if iframe is loaded irrespective of cross-domain policy. I was developing a chrome extension which injects certain script on a webpage and displays some content from the parent page in an iframe. I tried following approach and this worked perfect for me.
P.S.: In my case, i do have control over content in iframe but not on the parent site. (Iframe is hosted on my own server)

Create an iframe with a data- attribute in it like (this part was in injected script in my case)
<iframe id="myiframe" src="" data-isloaded="0"></iframe>

Now in the iframe code, use :

var sourceURL = document.referrer;

Now back to the injected script as per my case:

  var myIframe = document.getElementById('myiframe');
  var isLoaded = myIframe.prop('data-isloaded');
  if(isLoaded != '1')
    console.log('iframe failed to load');
  } else {
    console.log('iframe loaded');


window.addEventListener("message", receiveMessage, false);
function receiveMessage(event)
    if(event.origin !== '') //check origin of message for security reasons
        console.log('URL issues');
    else {
        var myMsg =;
        if(myMsg == '1'){
            //8-12-18 changed from 'data-isload' to 'data-isloaded
            $("#myiframe").prop('data-isloaded', '1');

It may not exactly answer the question but it indeed is a possible case of this question which i solved by this method.

How to read file binary in C#?

Use simple FileStream.Read then print it with Convert.ToString(b, 2)

How to modify WooCommerce cart, checkout pages (main theme portion)

You can use function: wc_get_page_id( 'cart' ) to get the ID of the page. This function will use the page setup as 'cart' page and not the slug. Meaning it will keep working also when you setup a different url for your 'cart' on the settings page. This works for all kind of Woocommerce special page, like 'checkout', 'shop' etc.


if (wc_get_page_id( 'cart' ) == get_the_ID()) {
  // Do something.

Regular Expression: Allow letters, numbers, and spaces (with at least one letter or number)

You simply need to specify your current RE, followed by a letter/number followed by your current RE again:

^[A-Z0-9 _]*[A-Z0-9][A-Z0-9 _]*$

Since you've now stated they're Javascript REs, there's a useful site here where you can test the RE against input data.

If you want lowercase letters as well:

^[A-Za-z0-9 _]*[A-Za-z0-9][A-Za-z0-9 _]*$

Angularjs prevent form submission when input validation fails

I know this is an old thread but I thought I'd also make a contribution. My solution being similar to the post already marked as an answer. Some inline JavaScript checks does the trick.

ng-click="form.$invalid ? alert('Please correct the form') : saveTask(task)"

Generate MD5 hash string with T-SQL

Use HashBytes

SELECT HashBytes('MD5', '[email protected]')

That will give you 0xF53BD08920E5D25809DF2563EF9C52B6


SELECT CONVERT(NVARCHAR(32),HashBytes('MD5', '[email protected]'),2)

That will give you F53BD08920E5D25809DF2563EF9C52B6

@Scope("prototype") bean scope not creating new bean

By default, Spring beans are singletons. The problem arises when we try to wire beans of different scopes. For example, a prototype bean into a singleton. This is known as the scoped bean injection problem.

Another way to solve the problem is method injection with the @Lookup annotation.

Here is a nice article on this issue of injecting prototype beans into a singleton instance with multiple solutions.

downcast and upcast

In case you need to check each of the Employee object whether it is a Manager object, use the OfType method:

List<Employee> employees = new List<Employee>();

//Code to add some Employee or Manager objects..

var onlyManagers = employees.OfType<Manager>();

foreach (Manager m in onlyManagers) {
  // Do Manager specific thing..

Python class returning value

You are describing a function, not a class.

def Myclass():
    return []

IE Driver download location Link for Selenium

Use the below link to download IE Driver latest version

IE Driver

How to find Max Date in List<Object>?

A small improvement from the accepted answer is to do the null check and also get full object.

public class DateComparator {

public static void main(String[] args) throws ParseException {
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

    List<Employee> employees = new ArrayList<>();
    employees.add(new Employee(1, "name1", addDays(new Date(), 1)));
    employees.add(new Employee(2, "name2", addDays(new Date(), 3)));
    employees.add(new Employee(3, "name3", addDays(new Date(), 6)));
    employees.add(new Employee(4, "name4", null));
    employees.add(new Employee(5, "name5", addDays(new Date(), 4)));
    employees.add(new Employee(6, "name6", addDays(new Date(), 5)));
    Date maxDate = -> emp.getJoiningDate() != null).map(Employee::getJoiningDate).max(Date::compareTo).get();
    //Comparator<Employee> comparator = (p1, p2) -> p1.getJoiningDate().compareTo(p2.getJoiningDate());
    Comparator<Employee> comparator = Comparator.comparing(Employee::getJoiningDate);
    Employee maxDatedEmploye = -> emp.getJoiningDate() != null).max(comparator).get();
    System.out.println(" maxDatedEmploye : " + maxDatedEmploye);

    Employee minDatedEmployee = -> emp.getJoiningDate() != null).min(comparator).get();
    System.out.println(" minDatedEmployee : " + minDatedEmployee);


public static Date addDays(Date date, int days) {
    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.DATE, days); // minus number would decrement the days
    return cal.getTime();

You would get below results :

 [Employee [empId=1, empName=name1, joiningDate=Wed Mar 21 13:33:09 EDT 2018],
Employee [empId=2, empName=name2, joiningDate=Fri Mar 23 13:33:09 EDT 2018],
Employee [empId=3, empName=name3, joiningDate=Mon Mar 26 13:33:09 EDT 2018],
Employee [empId=4, empName=name4, joiningDate=null],
Employee [empId=5, empName=name5, joiningDate=Sat Mar 24 13:33:09 EDT 2018],
Employee [empId=6, empName=name6, joiningDate=Sun Mar 25 13:33:09 EDT 2018]
 maxDatedEmploye : Employee [empId=3, empName=name3, joiningDate=Mon Mar 26 13:33:09 EDT 2018]

 minDatedEmployee : Employee [empId=1, empName=name1, joiningDate=Wed Mar 21 13:33:09 EDT 2018]

Update : What if list itself is empty ?

        Date maxDate = -> emp.getJoiningDate() != null).map(Employee::getJoiningDate).max(Date::compareTo).orElse(new Date());
    Comparator<Employee> comparator = Comparator.comparing(Employee::getJoiningDate);
    Employee maxDatedEmploye = -> emp.getJoiningDate() != null).max(comparator).orElse(null);
    System.out.println(" maxDatedEmploye : " + maxDatedEmploye);

How can I force browsers to print background images in CSS? proposes an elegant solution, using a custom bullet in place of a background image:

   a.logo {
     display: list-item;
     list-style-image: url("../images/desired-background.png");
     list-style-position: inside;

By including this within a

@media print {

block, I'm able to replace a white-on-transparent logo on the screen, rendered as a background-image, with a black-on-transparent logo for print.

Just what is an IntPtr exactly?

A direct interpretation

An IntPtr is an integer which is the same size as a pointer.

You can use IntPtr to store a pointer value in a non-pointer type. This feature is important in .NET since using pointers is highly error prone and therefore illegal in most contexts. By allowing the pointer value to be stored in a "safe" data type, plumbing between unsafe code segments may be implemented in safer high-level code -- or even in a .NET language that doesn't directly support pointers.

The size of IntPtr is platform-specific, but this detail rarely needs to be considered, since the system will automatically use the correct size.

The name "IntPtr" is confusing -- something like Handle might have been more appropriate. My initial guess was that "IntPtr" was a pointer to an integer. The MSDN documentation of IntPtr goes into somewhat cryptic detail without ever providing much insight about the meaning of the name.

An alternative perspective

An IntPtr is a pointer with two limitations:

  1. It cannot be directly dereferenced
  2. It doesn't know the type of the data that it points to.

In other words, an IntPtr is just like a void* -- but with the extra feature that it can (but shouldn't) be used for basic pointer arithmetic.

In order to dereference an IntPtr, you can either cast it to a true pointer (an operation which can only be performed in "unsafe" contexts) or you can pass it to a helper routine such as those provided by the InteropServices.Marshal class. Using the Marshal class gives the illusion of safety since it doesn't require you to be in an explicit "unsafe" context. However, it doesn't remove the risk of crashing which is inherent in using pointers.

Align HTML input fields by :

You could use a label (see JsFiddle)


label { display: inline-block; width: 210px; text-align: right; }


    <label for="name">Name:</label><input id="name" type="text"><br />
    <label for="email">Email Address:</label><input id="email" type="text"><br /> 
    <label for="desc">Description of the input value:</label><input id="desc" type="text"><br /> 

Or you could use those labels in a table (JsFiddle)

            <tr><td><label for="name">Name:</label></td><td><input id="name" type="text"></td></tr>
            <tr><td><label for="email">Email Address:</label></td><td><input id="email" type = "text"></td></tr>
            <tr><td><label for="desc">Description of the input value:</label></td><td><input id="desc" type="text"></td></tr>

Nested attributes unpermitted parameters

Actually there is a way to just white-list all nested parameters.

params.require(:widget).permit(:name, :description).tap do |whitelisted|
  whitelisted[:position] = params[:widget][:position]
  whitelisted[:properties] = params[:widget][:properties]

This method has advantage over other solutions. It allows to permit deep-nested parameters.

While other solutions like:

params.require(:person).permit(:name, :age, pets_attributes: [:id, :name, :category])



how to remove time from datetime

For more info refer this: SQL Server Date Formats


SELECT CONVERT(VARCHAR(10), cast(dt_col as date), 101) from tbl


SELECT CONVERT(VARCHAR(10), cast(dt_col as date), 103) from tbl

Live Demo

how to hide keyboard after typing in EditText in android?

you can create a singleton class for call easily like this:

public class KeyboardUtils {

    private static KeyboardUtils instance;
    private InputMethodManager inputMethodManager;

    private KeyboardUtils() {

    public static KeyboardUtils getInstance() {
        if (instance == null)
            instance = new KeyboardUtils();
        return instance;

    private InputMethodManager getInputMethodManager() {
        if (inputMethodManager == null)
            inputMethodManager = (InputMethodManager) Application.getInstance().getSystemService(Activity.INPUT_METHOD_SERVICE);
        return inputMethodManager;

    public void hide(final Activity activity) {
        new Handler().post(new Runnable() {
            public void run() {
                try {
                    getInputMethodManager().hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
                } catch (NullPointerException e) {

so, after can call in the activity how the next form:

public class MainActivity extends AppCompatActivity {

    protected void onCreate(Bundle savedInstanceState) {


Set date input field's max date to today

it can be useful : If you want to do it with Symfony forms :

 $today = new DateTime('now');
 $formBuilder->add('startDate', DateType::class, array(
                   'widget' => 'single_text',
                   'data'   => new \DateTime(),
                   'attr'   => ['min' => $today->format('Y-m-d')]

Convert text to columns in Excel using VBA

If someone is facing issue using texttocolumns function in UFT. Please try using below function.

myxl.Workbooks.Open myexcel.xls
myxl.Application.Visible = false `enter code here`
set mysheet = myxl.ActiveWorkbook.Worksheets(1)
Set objRange = myxl.Range("A1").EntireColumn
Set objRange2 = mysheet.Range("A1")
objRange.TextToColumns objRange2,1,1, , , , true

Here we are using coma(,) as delimiter.

How to use a switch case 'or' in PHP

switch ($value) 
   case 1:
   case 2:
      echo 'the value is either 1 or 2';

How to convert any date format to yyyy-MM-dd

You will need to parse the input to a DateTime object and then convert it to any text format you want.

If you are not sure what format you will get, you can restrict the user to a fixed format by using validation or datetimePicker, or some other component.

How to use if, else condition in jsf to display image

It is illegal to nest EL expressions: you should inline them. Using JSTL is perfectly valid in your situation. Correcting the mistake, you'll make the code working:

<html xmlns="" xmlns:c="">
    <c:if test="#{not empty user or user.userId eq 0}">
        <a href="Images/thumb_02.jpg" target="_blank" ></a>
        <img src="Images/thumb_02.jpg" />
    <c:if test="#{empty user or user.userId eq 0}">
        <a href="/DisplayBlobExample?userId=#{user.userId}" target="_blank"></a>
        <img src="/DisplayBlobExample?userId=#{user.userId}" />

Another solution is to specify all the conditions you want inside an EL of one element. Though it could be heavier and less readable, here it is:

<a href="#{not empty user or user.userId eq 0 ? '/Images/thumb_02.jpg' : '/DisplayBlobExample?userId='}#{not empty user or user.userId eq 0 ? '' : user.userId}" target="_blank"></a>
<img src="#{not empty user or user.userId eq 0 ? '/Images/thumb_02.jpg' : '/DisplayBlobExample?userId='}#{not empty user or user.userId eq 0 ? '' : user.userId}" target="_blank"></img>

Trusting all certificates using HttpClient over HTTPS

There a many answers above but I wasn't able to get any of them working correctly (with my limited time), so for anyone else in the same situation you can try the code below which worked perfectly for my java testing purposes:

    public static HttpClient wrapClient(HttpClient base) {
    try {
        SSLContext ctx = SSLContext.getInstance("TLS");
        X509TrustManager tm = new X509TrustManager() {
            public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException { }

            public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException { }

            public X509Certificate[] getAcceptedIssuers() {
                return null;
        ctx.init(null, new TrustManager[]{tm}, null);
        SSLSocketFactory ssf = new SSLSocketFactory(ctx);
        ClientConnectionManager ccm = base.getConnectionManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        sr.register(new Scheme("https", ssf, 443));
        return new DefaultHttpClient(ccm, base.getParams());
    } catch (Exception ex) {
        return null;

and call like:

DefaultHttpClient baseClient = new DefaultHttpClient();
HttpClient httpClient = wrapClient(baseClient );


Git removing upstream from local repository

$ git remote remove <name>


$ git remote remove upstream

that should do the trick

Why can't static methods be abstract in Java?

First, a key point about abstract classes - An abstract class cannot be instantiated (see wiki). So, you can't create any instance of an abstract class.

Now, the way java deals with static methods is by sharing the method with all the instances of that class.

So, If you can't instantiate a class, that class can't have abstract static methods since an abstract method begs to be extended.


How can I add a class attribute to an HTML element generated by MVC's HTML Helpers?

Current best practice in CSS development is to create more general selectors with modifiers that can be applied as widely as possible throughout the web site. I would try to avoid defining separate styles for individual page elements.

If the purpose of the CSS class on the <form/> element is to control the style of elements within the form, you could add the class attribute the existing <fieldset/> element which encapsulates any form by default in web pages generated by ASP.NET MVC. A CSS class on the form is rarely necessary.

Set value for particular cell in pandas DataFrame with iloc

If you know the position, why not just get the index from that?

Then use .loc:

df.loc[index, 'COL_NAME'] = x

LINQ Joining in C# with multiple conditions

If you need not equal object condition use cross join sequences:

var query = from obj1 in set1
from obj2 in set2
where obj1.key1 == obj2.key2 && obj1.key3.contains(obj2.key5) [...conditions...]

Difference between spring @Controller and @RestController annotation

THE new @RestController annotation in Spring4+, which marks the class as a controller where every method returns a domain object instead of a view. It’s shorthand for @Controller and @ResponseBody rolled together.

Add a new column to existing table in a migration

WARNING this is a destructive action. If you use this ensure you back up your database first

you can simply modify your existing migration file, for example adding a column in your table, and then in your terminal typing :

$ php artisan migrate:refresh

Getting a union of two arrays in JavaScript

With the arrival of ES6 with sets and splat operator (at the time of being works only in Firefox, check compatibility table), you can write the following cryptic one liner:

var a = [34, 35, 45, 48, 49];_x000D_
var b = [48, 55];_x000D_
var union = [ Set([...a, ...b])];_x000D_

Little explanation about this line: [...a, ...b] concatenates two arrays, you can use a.concat(b) as well. new Set() create a set out of it and thus your union. And the last [...x] converts it back to an array.

How do I undo a checkout in git?

You probably want git checkout master, or git checkout [branchname].

Add number of days to a date

I know this is an old question, but for PHP <5.3 you could try this:

$date = '05/07/2013';
$add_days = 7;
$date = date('Y-m-d',strtotime($date) + (24*3600*$add_days)); //my preferred method
$date = date('Y-m-d',strtotime($date.' +'.$add_days.' days');

ant warning: "'includeantruntime' was not set"

As @Daniel Kutik mentioned, presetdef is a good option. Especially if one is working on a project with many build.xml files which one cannot, or prefers not to, edit (e.g., those from third-parties.)

To use presetdef, add these lines in your top-level build.xml file:

  <presetdef name="javac">
    <javac includeantruntime="false" />

Now all subsequent javac tasks will essentially inherit includeantruntime="false". If your projects do actually need ant runtime libraries, you can either add them explicitly to your build files OR set includeantruntime="true". The latter will also get rid of warnings.

Subsequent javac tasks can still explicitly change this if desired, for example:

<javac destdir="out" includeantruntime="true">
  <src path="" />
  <src path="" />

I'd recommend against using ANT_OPTS. It works, but it defeats the purpose of the warning. The warning tells one that one's build might behave differently on another system. Using ANT_OPTS makes this even more likely because now every system needs to use ANT_OPTS in the same way. Also, ANT_OPTS will apply globally, suppressing warnings willy-nilly in all your projects

Loop through a date range with JavaScript

Here's a way to do it by making use of the way adding one day causes the date to roll over to the next month if necessary, and without messing around with milliseconds. Daylight savings aren't an issue either.

var now = new Date();
var daysOfYear = [];
for (var d = new Date(2012, 0, 1); d <= now; d.setDate(d.getDate() + 1)) {
    daysOfYear.push(new Date(d));

Note that if you want to store the date, you'll need to make a new one (as above with new Date(d)), or else you'll end up with every stored date being the final value of d in the loop.

Get selected key/value of a combo box using jQuery

$(this).find("select").each(function () {

print highest value in dict with key

The clue is to work with the dict's items (i.e. key-value pair tuples). Then by using the second element of the item as the max key (as opposed to the dict key) you can easily extract the highest value and its associated key.

 mydict = {'A':4,'B':10,'C':0,'D':87}
>>> max(mydict.items(), key=lambda k: k[1])
('D', 87)
>>> min(mydict.items(), key=lambda k: k[1])
('C', 0)

Get element type with jQuery

you can use .is():

  $( "ul" ).click(function( event ) {
      var target = $( );
      if ( "li" ) ) {
         target.css( "background-color", "red" );

see source

Connect to Amazon EC2 file directory using Filezilla and SFTP

Make sure you use port 22. Filezilla will default to port 21 for SFTP.

Get a list of URLs from a site

Here is a list of sitemap generators (from which obviously you can get the list of URLs from a site):

Web Sitemap Generators

The following are links to tools that generate or maintain files in the XML Sitemaps format, an open standard defined on and supported by the search engines such as Ask, Google, Microsoft Live Search and Yahoo!. Sitemap files generally contain a collection of URLs on a website along with some meta-data for these URLs. The following tools generally generate "web-type" XML Sitemap and URL-list files (some may also support other formats).

Please Note: Google has not tested or verified the features or security of the third party software listed on this site. Please direct any questions regarding the software to the software's author. We hope you enjoy these tools!

Server-side Programs

  • Enarion phpSitemapsNG (PHP)
  • Google Sitemap Generator (Linux/Windows, 32/64bit, open-source)
  • Outil en PHP (French, PHP)
  • Perl Sitemap Generator (Perl)
  • Python Sitemap Generator (Python)
  • Simple Sitemaps (PHP)
  • SiteMap XML Dynamic Sitemap Generator (PHP) $
  • Sitemap generator for OS/2 (REXX-script)
  • XML Sitemap Generator (PHP) $

CMS and Other Plugins:

  • ASP.NET - Sitemaps.Net
  • DotClear (Spanish)
  • DotClear (2)
  • Drupal
  • ECommerce Templates (PHP) $
  • Ecommerce Templates (PHP or ASP) $
  • LifeType
  • MediaWiki Sitemap generator
  • mnoGoSearch
  • OS Commerce
  • phpWebSite
  • Plone
  • RapidWeaver
  • Textpattern
  • vBulletin
  • Wikka Wiki (PHP)
  • WordPress

Downloadable Tools

  • GSiteCrawler (Windows)
  • GWebCrawler & Sitemap Creator (Windows)
  • G-Mapper (Windows)
  • Inspyder Sitemap Creator (Windows) $
  • IntelliMapper (Windows) $
  • Microsys A1 Sitemap Generator (Windows) $
  • Rage Google Sitemap Automator $ (OS-X)
  • Screaming Frog SEO Spider and Sitemap generator (Windows/Mac) $
  • Site Map Pro (Windows) $
  • Sitemap Writer (Windows) $
  • Sitemap Generator by DevIntelligence (Windows)
  • Sorrowmans Sitemap Tools (Windows)
  • TheSiteMapper (Windows) $
  • Vigos Gsitemap (Windows)
  • Visual SEO Studio (Windows)
  • WebDesignPros Sitemap Generator (Java Webstart Application)
  • Weblight (Windows/Mac) $
  • WonderWebWare Sitemap Generator (Windows)

Online Generators/Services

  • Sitemap Generator
  • AutoMapIt
  • Autositemap $
  • Enarion phpSitemapsNG
  • Free Sitemap Generator
  • Sitemap Generator
  • ROR Sitemap Generator
  • ScriptSocket Sitemap Generator
  • SeoUtility Sitemap Generator (Italian)
  • SitemapDoc
  • Sitemapspal
  • SitemapSubmit
  • Smart-IT-Consulting Google Sitemaps XML Validator
  • XML Sitemap Generator
  • XML-Sitemaps Generator

CMS with integrated Sitemap generators

  • Concrete5

Google News Sitemap Generators The following plugins allow publishers to update Google News Sitemap files, a variant of the protocol that we describe in our Help Center. In addition to the normal properties of Sitemap files, Google News Sitemaps allow publishers to describe the types of content they publish, along with specifying levels of access for individual articles. More information about Google News can be found in our Help Center and Help Forums.

  • WordPress Google News plugin

Code Snippets / Libraries

  • ASP script
  • Emacs Lisp script
  • Java library
  • Perl script
  • PHP class
  • PHP generator script

If you believe that a tool should be added or removed for a legitimate reason, please leave a comment in the Webmaster Help Forum.

"Call to undefined function mysql_connect()" after upgrade to php-7

From the PHP Manual:

Warning This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:



use MySQLi or PDO

$con = mysqli_connect('localhost', 'username', 'password', 'database');

Could not complete the operation due to error 80020101. IE

wrap your entire code block in this:


//code here


also make sure to specify the type of script to be text/javascript

try that and let me know how it goes

How to hide only the Close (x) button?

You can't hide it, but you can disable it by overriding the CreateParams property of the form.

private const int CP_NOCLOSE_BUTTON = 0x200;
protected override CreateParams CreateParams
       CreateParams myCp = base.CreateParams;
       myCp.ClassStyle = myCp.ClassStyle | CP_NOCLOSE_BUTTON ;
       return myCp;


How to get POST data in WebAPI?

It is hard to handle multiple parameters on the action directly. The better way to do it is to create a view model class. Then you have a single parameter but the parameter contains multiple data properties.

public class MyParameters
    public string a { get; set; } 
    public string b { get; set; }

public MyController : ApiController
    public HttpResponseMessage Get([FromUri] MyParameters parameters) { ... }

Then you go to:



If you want to use "/par1/par2", you can register an asp routing rule. eg routeTemplate: "API/{controller}/{action}/{a}/{b}".


php & mysql query not echoing in html with tags?

You need to append your variables to the echoed string. For example:

echo 'This is a string '.$PHPvariable.' and this is more string'; 

How to comment out particular lines in a shell script

Yes (although it's a nasty hack). You can use a heredoc thus:


# do valuable stuff here
touch /tmp/a

# now comment out all the stuff below up to the EOF
echo <<EOF

What's this doing ? A heredoc feeds all the following input up to the terminator (in this case, EOF) into the nominated command. So you can surround the code you wish to comment out with

echo <<EOF

and it'll take all the code contained between the two EOFs and feed them to echo (echo doesn't read from stdin so it all gets thrown away).

Note that with the above you can put anything in the heredoc. It doesn't have to be valid shell code (i.e. it doesn't have to parse properly).

This is very nasty, and I offer it only as a point of interest. You can't do the equivalent of C's /* ... */

PHP how to get the base domain/url?

Please try this:

$uri = $_SERVER['REQUEST_URI']; // $uri ==
$exploded_uri = explode('/', $uri); //$exploded_uri == array('','sub')
$domain_name = $exploded_uri[1]; //$domain_name = ''

I hope this will help you.

No 'Access-Control-Allow-Origin' header is present on the requested resource- AngularJS

On the client side you can enable cors requests in AngularJS via

app.config(['$httpProvider', function($httpProvider) {
        $httpProvider.defaults.useXDomain = true;
        delete $httpProvider.defaults.headers.common['X-Requested-With'];

However if this still returns an error, this would imply that the server that you are making the request has to allow CORS request and has to be configured for that.

Python return statement error " 'return' outside function"

The return statement only makes sense inside functions:

def foo():
    while True:
        return False

HTML anchor tag with Javascript onclick event

You can even try below option:

<a href="javascript:show_more_menu();">More >>></a>

jQuery change URL of form submit

Try using this:

$(".move_to").on("click", function(e){
    $('#contactsForm').attr('action', "/test1").submit();

Moving the order in which you use .preventDefault() might fix your issue. You also didn't use function(e) so e.preventDefault(); wasn't working.

Here it is working: - first of all, click the 'Check action attribute.' link. You'll get an alert saying undefined. Then click 'Set action attribute.' and click 'Check action attribute.' again. You'll see that the form's action attribute has been correctly set to /test1.

How to check the version of scipy

In [95]: import scipy

In [96]: scipy.__version__
Out[96]: '0.12.0'

In [104]: scipy.version.*version?

In [105]: scipy.version.full_version
Out[105]: '0.12.0'

In [106]: scipy.version.git_revision
Out[106]: 'cdd6b32233bbecc3e8cbc82531905b74f3ea66eb'

In [107]: scipy.version.release
Out[107]: True

In [108]: scipy.version.short_version
Out[108]: '0.12.0'

In [109]: scipy.version.version
Out[109]: '0.12.0'

See SciPy doveloper documentation for reference.

ClassNotFoundException: org.slf4j.LoggerFactory

For a bit more explanation: keep in mind that the "I" in "api" is interface. The slf4j-api jar only holds the needed interfaces (actually LoggerFactory is an abstract class). You also need the actual implementations (an example of which, as noted above, can be found in slf4j-simple). If you look in the jar, you'll find the required classes under the "org.slf4j.impl" package.

Unix command-line JSON parser?

If you're looking for a portable C compiled tool:

From the website:

jq is like sed for JSON data - you can use it to slice and filter and map and transform structured data with the same ease that sed, awk, grep and friends let you play with text.

jq can mangle the data format that you have into the one that you want with very little effort, and the program to do so is often shorter and simpler than you’d expect.


Return Index of an Element in an Array Excel VBA

Is this what you are looking for?

public function GetIndex(byref iaList() as integer, byval iInteger as integer) as integer

dim i as integer

 for i=lbound(ialist) to ubound(ialist)
  if iInteger=ialist(i) then
   exit for
  end if
 next i

end function

Convert Python dictionary to JSON array

One possible solution that I use is to use python3. It seems to solve many utf issues.

Sorry for the late answer, but it may help people in the future.

For example,

#!/usr/bin/env python3
import json
# your code follows

Simulating group_concat MySQL function in Microsoft SQL Server 2005?

Have a look at the GROUP_CONCAT project on Github, I think I does exactly what you are searching for:

This project contains a set of SQLCLR User-defined Aggregate functions (SQLCLR UDAs) that collectively offer similar functionality to the MySQL GROUP_CONCAT function. There are multiple functions to ensure the best performance based on the functionality required...

Substring in excel

Another way you can do this is by using the substitute function. Substitute "(", ")" and "," with spaces. e.g.

 =SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(A1, "(", " "), ")", " "), ",", " ")

Linux shell script for database backup

Create a script similar to this:

#!/bin/sh -e

location=~/`date +%Y%m%d_%H%M%S`.db

mysqldump -u root --password=<your password> database_name > $location

gzip $location

Then you can edit the crontab of the user that the script is going to run as:

$> crontab -e

And append the entry

01 * * * * ~/

This will make it run on the first minute of every hour every day.

Then you just have to add in your rolls and other functionality and you are good to go.

error LNK2001: unresolved external symbol (C++)

Sounds like you are using Microsoft Visual C++. If that is the case, then the most possibility is that you don't compile your two.cpp with one.cpp (one.cpp is the implementation for one.h).

If you are from command line (cmd.exe), then try this first: cl -o two.exe one.cpp two.cpp

If you are from IDE, right click on the project name from Solution Explore. Then choose Add, Existing Item.... Add one.cpp into your project.

Slack clean all messages (~8K) in a channel

Here is a great chrome extension to bulk delete your slack channel/group/im messages - , where you can filter the messages by star, time range, or users. BTW, it also supports load all messages in recent version, then you can load your ~8k messages as you need.

Python: How to convert datetime format?

@Tim's answer only does half the work -- that gets it into a datetime.datetime object.

To get it into the string format you require, you use datetime.strftime:

print(datetime.strftime('%b %d,%Y'))

Delete dynamically-generated table row using jQuery

You need to use event delegation because those buttons don't exist on load:

 $(document).on('click', 'button.removebutton', function () { // <-- changes
     return false;

How do I generate a constructor from class fields using Visual Studio (and/or ReSharper)?

Here is a macro that I use for that purpose. It will generate a constructor from fields and properties that have a private setter.

Imports System
Imports EnvDTE
Imports EnvDTE80
Imports EnvDTE90
Imports EnvDTE90a
Imports EnvDTE100
Imports System.Diagnostics
Imports System.Collections.Generic

Public Module Temp

    Sub AddConstructorFromFields()
        DTE.UndoContext.Open("Add constructor from fields")

        Dim classElement As CodeClass, index As Integer
        GetClassAndInsertionIndex(classElement, index)

        Dim constructor As CodeFunction
        constructor = classElement.AddFunction(classElement.Name, vsCMFunction.vsCMFunctionConstructor, vsCMTypeRef.vsCMTypeRefVoid, index, vsCMAccess.vsCMAccessPublic)

        Dim visitedNames As New Dictionary(Of String, String)
        Dim element As CodeElement, parameterPosition As Integer, isFirst As Boolean = True
        For Each element In classElement.Children
            Dim fieldType As String
            Dim fieldName As String
            Dim parameterName As String

            Select Case element.Kind
                Case vsCMElement.vsCMElementVariable
                    Dim field As CodeVariable = CType(element, CodeVariable)
                    fieldType = field.Type.AsString
                    fieldName = field.Name
                    parameterName = field.Name.TrimStart("_".ToCharArray())

                Case vsCMElement.vsCMElementProperty
                    Dim field As CodeProperty = CType(element, CodeProperty)
                    If field.Setter.Access = vsCMAccess.vsCMAccessPrivate Then
                        fieldType = field.Type.AsString
                        fieldName = field.Name
                        parameterName = field.Name.Substring(0, 1).ToLower() + field.Name.Substring(1)
                    End If
            End Select

            If Not String.IsNullOrEmpty(parameterName) And Not visitedNames.ContainsKey(parameterName) Then
                visitedNames.Add(parameterName, parameterName)

                constructor.AddParameter(parameterName, fieldType, parameterPosition)

                Dim endPoint As EditPoint
                endPoint = constructor.EndPoint.CreateEditPoint()

                If Not isFirst Then
                    isFirst = False
                End If

                endPoint.Insert(String.Format(MemberAssignmentFormat(constructor.Language), fieldName, parameterName))

                parameterPosition = parameterPosition + 1
            End If


            ' This command fails sometimes '
        Catch ex As Exception
        End Try
    End Sub
    Private Sub GetClassAndInsertionIndex(ByRef classElement As CodeClass, ByRef index As Integer, Optional ByVal useStartIndex As Boolean = False)
        Dim selection As TextSelection
        selection = CType(DTE.ActiveDocument.Selection, TextSelection)

        classElement = CType(selection.ActivePoint.CodeElement(vsCMElement.vsCMElementClass), CodeClass)

        Dim childElement As CodeElement
        index = 0
        For Each childElement In classElement.Children
            Dim childOffset As Integer
            childOffset = childElement.GetStartPoint(vsCMPart.vsCMPartWholeWithAttributes).AbsoluteCharOffset
            If selection.ActivePoint.AbsoluteCharOffset < childOffset Or useStartIndex Then
                Exit For
            End If
            index = index + 1
    End Sub
    Private ReadOnly Property MemberAssignmentFormat(ByVal language As String) As String
            Select Case language
                Case CodeModelLanguageConstants.vsCMLanguageCSharp
                    Return "this.{0} = {1};"

                Case CodeModelLanguageConstants.vsCMLanguageVB
                    Return "Me.{0} = {1}"

                Case Else
                    Return ""
            End Select
        End Get
    End Property
End Module

OS X Framework Library not loaded: 'Image not found'

For me this was the solution, after many hours of searching!!

For some reason, well into the development of a Swift 2.3 custom Framework, Xcode 8 had removed the DYLIB_INSTALL_NAME_BASE setting from the project.pbxproj file. A little walk into the Build Settings / Dynamic Library Install Name Base setting back to @rpath fixed it.


How to set a value for a span using jQuery

You're looking for the wrong selector id:


should be


How can I embed a YouTube video on GitHub wiki pages?

Complete Example

Expanding on @MGA's Answer

While it's not possible to embed a video in Markdown you can "fake it" by including a valid linked image in your markup file, using this format:

[![IMAGE ALT TEXT](]( "Video Title")

Explanation of the Markdown

If this markup snippet looks complicated, break it down into two parts:

an image
![image alt text](
wrapped in a link
[link text]( "link title")

Example using Valid Markdown and YouTube Thumbnail:

Everything Is AWESOME

We are sourcing the thumbnail image directly from YouTube and linking to the actual video, so when the person clicks the image/thumbnail they will be taken to the video.


[![Everything Is AWESOME](]( "Everything Is AWESOME")

OR If you want to give readers a visual cue that the image/thumbnail is actually a playable video, take your own screenshot of the video in YouTube and use that as the thumbnail instead.

Example using Screenshot with Video Controls as Visual Cue:

Everything Is AWESOME


[![Everything Is AWESOME](]( "Everything Is AWESOME")

 Clear Advantages

While this requires a couple of extra steps (a) taking the screenshot of the video and (b) uploading it so you can use the image as your thumbnail it does have 3 clear advantages:

  1. The person reading your markdown (or resulting html page) has a visual cue telling them they can watch the video (video controls encourage clicking)
  2. You can chose a specific frame in the video to use as the thumbnail (thus making your content more engaging)
  3. You can link to a specific time in the video from which play will start when the linked-image is clicked. (in our case from 35 seconds)

Taking and uploading a screenshot takes a few seconds but has a big payoff.

Works Everywhere!

Since this is standard markdown, it works everywhere. try it on GitHub, Reddit, Ghost, and here on Stack Overflow.


This approach also works with Vimeo videos


Little red riding hood


[![Little red riding hood](]( "Little red riding hood - Click to Watch!")


set height of imageview as matchparent programmatically

    (new ViewGroup.MarginLayoutParams
        (width, ViewGroup.LayoutParams.MATCH_PARENT));

The Type of layout params depends on the parent view group. If you put the wrong one it will cause exception.

How to create an array for JSON using PHP?

That's how I am able to do with the help of solution given by @tdammers below. The following line will be placed inside foreach loop.

$array[] = array('power' => trim("Some value"), 'time' => "time here" );

And then encode the array with json encode function

json_encode(array('newvalue'=> $array), 200)

Pressing Ctrl + A in Selenium WebDriver


The Robot class will work much more efficiently than sending the keys through Selenium sendkeys. Please try:


Robot rb = new Robot();

To use the above Robot class, you need to import java.awt.Robot;'.

Running CMake on Windows

The default generator for Windows seems to be set to NMAKE. Try to use:

cmake -G "MinGW Makefiles"

Or use the GUI, and select MinGW Makefiles when prompted for a generator. Don't forget to cleanup the directory where you tried to run CMake, or delete the cache in the GUI. Otherwise, it will try again with NMAKE.

Using jQuery's ajax method to retrieve images as a blob

You can't do this with jQuery ajax, but with native XMLHttpRequest.

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
    if (this.readyState == 4 && this.status == 200){
        //this.response is what you're looking for
        console.log(this.response, typeof this.response);
        var img = document.getElementById('img');
        var url = window.URL || window.webkitURL;
        img.src = url.createObjectURL(this.response);
}'GET', '');
xhr.responseType = 'blob';


So revisiting this topic, it seems it is indeed possible to do this with jQuery 3

        xhr:function(){// Seems like the only way to get access to the xhr object_x000D_
            var xhr = new XMLHttpRequest();_x000D_
            xhr.responseType= 'blob'_x000D_
            return xhr;_x000D_
        success: function(data){_x000D_
            var img = document.getElementById('img');_x000D_
            var url = window.URL || window.webkitURL;_x000D_
            img.src = url.createObjectURL(data);_x000D_
<script src=""></script>_x000D_
<img id="img" width=100%>


use xhrFields to set the responseType

                responseType: 'blob'_x000D_
            success: function(data){_x000D_
                var img = document.getElementById('img');_x000D_
                var url = window.URL || window.webkitURL;_x000D_
                img.src = url.createObjectURL(data);_x000D_
<script src=""></script>_x000D_
    <img id="img" width=100%>

How to check that an element is in a std::set?

Another way of simply telling if an element exists is to check the count()

if (myset.count(x)) {
   // x is in the set, count is 1
} else {
   // count zero, i.e. x not in the set

Most of the times, however, I find myself needing access to the element wherever I check for its existence.

So I'd have to find the iterator anyway. Then, of course, it's better to simply compare it to end too.

set< X >::iterator it = myset.find(x);
if (it != myset.end()) {
   // do something with *it

C++ 20

In C++20 set gets a contains function, so the following becomes possible as mentioned at:

if (myset.contains(x)) {
  // x is in the set
} else {
  // no x 

Mongoose (mongodb) batch insert?

Here are both way of saving data with insertMany and save

1) Mongoose save array of documents with insertMany in bulk

/* write mongoose schema model and export this */
var Potato = mongoose.model('Potato', PotatoSchema);

/* write this api in routes directory  */'/addDocuments', function (req, res) {
    const data = [/* array of object which data need to save in db */];

    .then((result) => {
            console.log("result ", result);
            res.status(200).json({'success': 'new documents added!', 'data': result});
    .catch(err => {
            console.error("error ", err);

2) Mongoose save array of documents with .save()

These documents will save parallel.

/* write mongoose schema model and export this */
var Potato = mongoose.model('Potato', PotatoSchema);

/* write this api in routes directory  */'/addDocuments', function (req, res) {
    const saveData = []
    const data = [/* array of object which data need to save in db */]; => {
        var potato = new Potato(data[i])
        .then((result) => {
            if (saveData.length === data.length) {
                res.status(200).json({'success': 'new documents added!', 'data': saveData});
        .catch((err) => {

Twitter Bootstrap: Print content of modal window

@media print{_x000D_
  visibility: hidden; /* no print*/_x000D_
  visibility:visible; /*print*/_x000D_
  <div class="noprint"> <!---no print--->_x000D_
  <div class="noprint"> <!---no print--->_x000D_
  <div class="print">   <!---print--->_x000D_
  <div class="print">   <!---print--->_x000D_

How to draw interactive Polyline on route google maps v2 android

You should use options.addAll(allPoints); instead of options.add(point);

Django ManyToMany filter()

Just restating what Tomasz said.

There are many examples of FOO__in=... style filters in the many-to-many and many-to-one tests. Here is syntax for your specific problem:

users_in_1zone = User.objects.filter(zones__id=<id1>)
# same thing but using in
users_in_1zone = User.objects.filter(zones__in=[<id1>])

# filtering on a few zones, by id
users_in_zones = User.objects.filter(zones__in=[<id1>, <id2>, <id3>])
# and by zone object (object gets converted to pk under the covers)
users_in_zones = User.objects.filter(zones__in=[zone1, zone2, zone3])

The double underscore (__) syntax is used all over the place when working with querysets.

notifyDataSetChanged example

I had the same problem and I prefer not to replace the entire ArrayAdapter with a new instance continuously. Thus I have the AdapterHelper do the heavy lifting somewhere else.

Add this where you would normally (try to) call notify

new AdapterHelper().update((ArrayAdapter)adapter, new ArrayList<Object>(yourArrayList));

AdapterHelper class

public class AdapterHelper {
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public void update(ArrayAdapter arrayAdapter, ArrayList<Object> listOfObject){
        for (Object object : listOfObject){

How to draw rounded rectangle in Android UI?

You could just define a new xml background in the drawables folder

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android=""
<solid android:color="enter_your_desired_color_here" />
<corners android:radius="enter_your_desired_radius_the_corners" />

After this just include it in your TextView or EditText by defining it in the background.

 android:textSize="40sp" /> Repeater get current index, pointer, or counter

Add a label control to your Repeater's ItemTemplate. Handle OnItemCreated event.


<asp:Repeater ID="rptr" runat="server" OnItemCreated="RepeaterItemCreated">
        <div id="width:50%;height:30px;background:#0f0a0f;">
            <asp:Label ID="lblSr" runat="server" 
               style="width:30%;float:left;text-align:right;text-indent:-2px;" />
               style="width:65%;float:right;text-align:left;text-indent:-2px;" >
            <%# Eval("Item") %>

Code Behind:

    protected void RepeaterItemCreated(object sender, RepeaterItemEventArgs e)
        Label l = e.Item.FindControl("lblSr") as Label;
        if (l != null)
            l.Text = e.Item.ItemIndex + 1+"";

How do I export (and then import) a Subversion repository?

You can also use svnsync. This only requires read-only access on the source repository

more at svnbook

Convert NaN to 0 in javascript

Write your own method, and use it everywhere you want a number value:

function getNum(val) {
   if (isNaN(val)) {
     return 0;
   return val;

react-native - Fit Image in containing View, not the whole screen size

the image has a property named Style ( like most of the react-native Compponents) and for Image's Styles, there is a property named resizeMode that takes values like: contain,cover,stretch,center,repeat

most of the time if you use center it will work for you

How to set table name in dynamic SQL query?

Table names cannot be supplied as parameters, so you'll have to construct the SQL string manually like this:

SET @SQLQuery = 'SELECT * FROM ' + @TableName + ' WHERE EmployeeID = @EmpID' 

However, make sure that your application does not allow a user to directly enter the value of @TableName, as this would make your query susceptible to SQL injection. For one possible solution to this, see this answer.

Code to loop through all records in MS Access

You should be able to do this with a pretty standard DAO recordset loop. You can see some examples at the following links:

My own standard loop looks something like this:

Dim rs As DAO.Recordset
Set rs = CurrentDb.OpenRecordset("SELECT * FROM Contacts")

'Check to see if the recordset actually contains rows
If Not (rs.EOF And rs.BOF) Then
    rs.MoveFirst 'Unnecessary in this case, but still a good habit
    Do Until rs.EOF = True
        'Perform an edit
        rs!VendorYN = True
        rs("VendorYN") = True 'The other way to refer to a field

        'Save contact name into a variable
        sContactName = rs!FirstName & " " & rs!LastName

        'Move to the next record. Don't ever forget to do this.
    MsgBox "There are no records in the recordset."
End If

MsgBox "Finished looping through records."

rs.Close 'Close the recordset
Set rs = Nothing 'Clean up

Is an HTTPS query string secure?

SSL first connects to the host, so the host name and port number are transferred as clear text. When the host responds and the challenge succeeds, the client will encrypt the HTTP request with the actual URL (i.e. anything after the third slash) and and send it to the server.

There are several ways to break this security.

It is possible to configure a proxy to act as a "man in the middle". Basically, the browser sends the request to connect to the real server to the proxy. If the proxy is configured this way, it will connect via SSL to the real server but the browser will still talk to the proxy. So if an attacker can gain access of the proxy, he can see all the data that flows through it in clear text.

Your requests will also be visible in the browser history. Users might be tempted to bookmark the site. Some users have bookmark sync tools installed, so the password could end up on or some other place.

Lastly, someone might have hacked your computer and installed a keyboard logger or a screen scraper (and a lot of Trojan Horse type viruses do). Since the password is visible directly on the screen (as opposed to "*" in a password dialog), this is another security hole.

Conclusion: When it comes to security, always rely on the beaten path. There is just too much that you don't know, won't think of and which will break your neck.

How to get request url in a jQuery $.get/ajax request

Since jQuery.get is just a shorthand for jQuery.ajax, another way would be to use the latter one's context option, as stated in the documentation:

The this reference within all callbacks is the object in the context option passed to $.ajax in the settings; if context is not specified, this is a reference to the Ajax settings themselves.

So you would use

$.ajax('', {
  dataType: 'xml',
  data: {'a':1,'b':2,'c':3},
  context: {
    url: ''
}).done(function(xml) {alert(this.url});

Using Node.js require vs. ES6 import/export

Are there any performance benefits to using one over the other?

Keep in mind that there is no JavaScript engine yet that natively supports ES6 modules. You said yourself that you are using Babel. Babel converts import and export declaration to CommonJS (require/module.exports) by default anyway. So even if you use ES6 module syntax, you will be using CommonJS under the hood if you run the code in Node.

There are technical differences between CommonJS and ES6 modules, e.g. CommonJS allows you to load modules dynamically. ES6 doesn't allow this, but there is an API in development for that.

Since ES6 modules are part of the standard, I would use them.

Update 2020

Since Node v12, support for ES modules is enabled by default, but it's still experimental at the time of writing this. Files including node modules must either end in .mjs or the nearest package.json file must contain "type": "module". The Node documentation has a ton more information, also about interop between CommonJS and ES modules.

Performance-wise there is always the chance that newer features are not as well optimized as existing features. However, since module files are only evaluated once, the performance aspect can probably be ignored. In the end you have to run benchmarks to get a definite answer anyway.

ES modules can be loaded dynamically via the import() function. Unlike require, this returns a promise.

single line comment in HTML

TL;DR For conforming browsers, yes; but there are no conforming browsers, so no.

According to the HTML 4 specification, <!------> hello--> is a perfectly valid comment. However, I've not found a browser which implements this correctly (i.e. per the specification) due to developers not knowing, nor following, the standards (as digitaldreamer pointed out).

You can find the definition of a comment for HTML4 on the w3c's website:

Another thing that many browsers get wrong is that -- > closes a comment just like -->.

Android - Back button in the title bar

It can also be done without code by specifying a parent activity in app manifest If you want a back button in Activity B which will goto Activity A, just add Activity A as the parent of Activity B in the manifest.

how to kill the tty in unix

You can run:

ps -ft pts/6 -t pts/9 -t pts/10

This would produce an output similar to:

Vidya      772  2701  0 15:26 pts/6    00:00:00 bash
Vidya      773  2701  0 16:26 pts/9    00:00:00 bash
Vidya      774  2701  0 17:26 pts/10   00:00:00 bash

Grab the PID from the result.

Use the PIDs to kill the processes:

kill <PID1> <PID2> <PID3> ...

For the above example:

kill 772 773 774

If the process doesn't gracefully terminate, just as a last option you can forcefully kill by sending a SIGKILL

kill -9 <PID>

How to declare a variable in a template in Angular

If you need autocomplete support from within in your templates from the Angular Language Service:


myVar = { hello: '' };

<ng-container *ngIf="myVar; let var;">

Using async pipe:

myVar$ = of({ hello: '' });

<ng-container *ngIf="myVar$ | async; let var;">

Disable mouse scroll wheel zoom on embedded Google Maps

In Google Maps v3 you can now disable scroll to zoom, which leads to a much better user experience. Other map functions will still work and you don't need extra divs. I also thought there should be some feedback for the user so they can see when scrolling is enabled, so I added a map border.

// map is the google maps object, '#map' is the jquery selector
preventAccidentalZoom(map, '#map'); 

// Disables and enables scroll to zoom as appropriate. Also
// gives the user a UI cue as to when scrolling is enabled.
function preventAccidentalZoom(map, mapSelector){
  var mapElement = $(mapSelector);

  // Disable the scroll wheel by default
  map.setOptions({ scrollwheel: false })

  // Enable scroll to zoom when there is a mouse down on the map.
  // This allows for a click and drag to also enable the map
  mapElement.on('mousedown', function () {
    map.setOptions({ scrollwheel: true });
    mapElement.css('border', '1px solid blue')

  // Disable scroll to zoom when the mouse leaves the map.
  mapElement.mouseleave(function () {
    map.setOptions({ scrollwheel: false })
    mapElement.css('border', 'none')

How to pass an object into a state using UI-router?


        .state('app.example1', {
                url: '/example',
                views: {
                    'menuContent': {
                        templateUrl: 'templates/example.html',
                        controller: 'ExampleCtrl'
            .state('app.example2', {
                url: '/example2/:object',
                views: {
                    'menuContent': {
                        templateUrl: 'templates/example2.html',
                        controller: 'Example2Ctrl'


.controller('ExampleCtrl', function ($state, $scope, UserService) {

        $scope.goExample2 = function (obj) {

            $state.go("app.example2", {object: JSON.stringify(obj)});

    .controller('Example2Ctrl', function ($state, $scope, $stateParams) {



How to run Linux commands in Java?

The suggested solutions could be optimized using, handling the error stream, and using Exceptions. I would suggest to wrap like this for use in Java 8 or later:

public static List<String> execute(final String command) throws ExecutionFailedException, InterruptedException, IOException {
    try {
        return execute(command, 0, null, false);
    } catch (ExecutionTimeoutException e) { return null; } /* Impossible case! */

public static List<String> execute(final String command, final long timeout, final TimeUnit timeUnit) throws ExecutionFailedException, ExecutionTimeoutException, InterruptedException, IOException {
    return execute(command, 0, null, true);

public static List<String> execute(final String command, final long timeout, final TimeUnit timeUnit, boolean destroyOnTimeout) throws ExecutionFailedException, ExecutionTimeoutException, InterruptedException, IOException {
    Process process = new ProcessBuilder().command("bash", "-c", command).start();
    if(timeUnit != null) {
        if(process.waitFor(timeout, timeUnit)) {
            if(process.exitValue() == 0) {
                return IOUtils.readLines(process.getInputStream(), StandardCharsets.UTF_8);
            } else {
                throw new ExecutionFailedException("Execution failed: " + command, process.exitValue(), IOUtils.readLines(process.getInputStream(), StandardCharsets.UTF_8));
        } else {
            if(destroyOnTimeout) process.destroy();
            throw new ExecutionTimeoutException("Execution timed out: " + command);
    } else {
        if(process.waitFor() == 0) {
            return IOUtils.readLines(process.getInputStream(), StandardCharsets.UTF_8);
        } else {
            throw new ExecutionFailedException("Execution failed: " + command, process.exitValue(), IOUtils.readLines(process.getInputStream(), StandardCharsets.UTF_8));

public static class ExecutionFailedException extends Exception {

    private static final long serialVersionUID = 1951044996696304510L;

    private final int exitCode;
    private final List<String> errorOutput;

    public ExecutionFailedException(final String message, final int exitCode, final List<String> errorOutput) {
        this.exitCode = exitCode;
        this.errorOutput = errorOutput;

    public int getExitCode() {
        return this.exitCode;

    public List<String> getErrorOutput() {
        return this.errorOutput;


public static class ExecutionTimeoutException extends Exception {

    private static final long serialVersionUID = 4428595769718054862L;

    public ExecutionTimeoutException(final String message) {


Oracle - Best SELECT statement for getting the difference in minutes between two DateTime columns?

SELECT date1 - date2
  FROM some_table

returns a difference in days. Multiply by 24 to get a difference in hours and 24*60 to get minutes. So

SELECT (date1 - date2) * 24 * 60 difference_in_minutes
  FROM some_table

should be what you're looking for

Using group by on multiple columns

In simple English from GROUP BY with two parameters what we are doing is looking for similar value pairs and get the count to a 3rd column.

Look at the following example for reference. Here I'm using International football results from 1872 to 2020

|       _c0|             _c1|     _c2|_c3|_c4|     _c5|      _c6|                _c7|  _c8|
|1872-11-30|        Scotland| England|  0|  0|Friendly|  Glasgow|           Scotland|FALSE|
|1873-03-08|         England|Scotland|  4|  2|Friendly|   London|            England|FALSE|
|1874-03-07|        Scotland| England|  2|  1|Friendly|  Glasgow|           Scotland|FALSE|
|1875-03-06|         England|Scotland|  2|  2|Friendly|   London|            England|FALSE|
|1876-03-04|        Scotland| England|  3|  0|Friendly|  Glasgow|           Scotland|FALSE|
|1876-03-25|        Scotland|   Wales|  4|  0|Friendly|  Glasgow|           Scotland|FALSE|
|1877-03-03|         England|Scotland|  1|  3|Friendly|   London|            England|FALSE|
|1877-03-05|           Wales|Scotland|  0|  2|Friendly|  Wrexham|              Wales|FALSE|
|1878-03-02|        Scotland| England|  7|  2|Friendly|  Glasgow|           Scotland|FALSE|
|1878-03-23|        Scotland|   Wales|  9|  0|Friendly|  Glasgow|           Scotland|FALSE|
|1879-01-18|         England|   Wales|  2|  1|Friendly|   London|            England|FALSE|
|1879-04-05|         England|Scotland|  5|  4|Friendly|   London|            England|FALSE|
|1879-04-07|           Wales|Scotland|  0|  3|Friendly|  Wrexham|              Wales|FALSE|
|1880-03-13|        Scotland| England|  5|  4|Friendly|  Glasgow|           Scotland|FALSE|
|1880-03-15|           Wales| England|  2|  3|Friendly|  Wrexham|              Wales|FALSE|
|1880-03-27|        Scotland|   Wales|  5|  1|Friendly|  Glasgow|           Scotland|FALSE|
|1881-02-26|         England|   Wales|  0|  1|Friendly|Blackburn|            England|FALSE|
|1881-03-12|         England|Scotland|  1|  6|Friendly|   London|            England|FALSE|
|1881-03-14|           Wales|Scotland|  1|  5|Friendly|  Wrexham|              Wales|FALSE|
|1882-02-18|Northern Ireland| England|  0| 13|Friendly|  Belfast|Republic of Ireland|FALSE|

And now I'm going to group by similar country(column _c7) and tournament(_c5) value pairs by GROUP BY operation,

SELECT `_c5`,`_c7`,count(*)  FROM res GROUP BY `_c5`,`_c7`

|                 _c5|                _c7|count(1)|
|            Friendly|  Southern Rhodesia|      11|
|            Friendly|            Ecuador|      68|
|African Cup of Na...|           Ethiopia|      41|
|Gold Cup qualific...|Trinidad and Tobago|       9|
|AFC Asian Cup qua...|             Bhutan|       7|
|African Nations C...|              Gabon|       2|
|            Friendly|           China PR|     170|
|FIFA World Cup qu...|             Israel|      59|
|FIFA World Cup qu...|              Japan|      61|
|UEFA Euro qualifi...|            Romania|      62|
|AFC Asian Cup qua...|              Macau|       9|
|            Friendly|        South Sudan|       1|
|CONCACAF Nations ...|           Suriname|       3|
|         Copa Newton|          Argentina|      12|
|            Friendly|        Philippines|      38|
|FIFA World Cup qu...|              Chile|      68|
|African Cup of Na...|         Madagascar|      29|
|FIFA World Cup qu...|       Burkina Faso|      30|
| UEFA Nations League|            Denmark|       4|
|        Atlantic Cup|           Paraguay|       2|

Explanation: The meaning of the first row is there were 11 Friendly tournaments held on Southern Rhodesia in total.

Note: Here it's mandatory to use a counter column in this case.

Get size of all tables in database

A small change on Mar_c's answer, since I have been going back to this page so often, ordered by most row's first:

    t.NAME AS TableName,
    s.Name AS SchemaName,
    p.rows AS RowCounts,
    SUM(a.total_pages) * 8 AS TotalSpaceKB,
    SUM(a.used_pages) * 8 AS UsedSpaceKB,
    (SUM(a.total_pages) - SUM(a.used_pages)) * 8 AS UnusedSpaceKB
    sys.tables t
    sys.indexes i ON t.OBJECT_ID = i.object_id
    sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id
    sys.allocation_units a ON p.partition_id = a.container_id
    sys.schemas s ON t.schema_id = s.schema_id
    t.NAME NOT LIKE 'dt%'
    AND t.is_ms_shipped = 0
    AND i.OBJECT_ID > 255
    t.Name, s.Name, p.Rows
    --p.rows DESC --Uncomment to order by amount rows instead of size in KB.
    SUM(a.total_pages) DESC 

Bulk create model objects in django

Using create will cause one query per new item. If you want to reduce the number of INSERT queries, you'll need to use something else.

I've had some success using the Bulk Insert snippet, even though the snippet is quite old. Perhaps there are some changes required to get it working again.

SQL Server FOR EACH Loop

declare @counter as int
set @counter = 0
declare @date as varchar(50)
set @date = cast(1+@counter as varchar)+'/01/2013'
while(@counter < 12)
select  cast(1+@counter as varchar)+'/01/2013' as date
set @counter = @counter + 1

How to plot time series in python

Convert your x-axis data from text to datetime.datetime, use datetime.strptime:

>>> from datetime import datetime
>>> datetime.strptime("2012-may-31 19:00", "%Y-%b-%d %H:%M")
 datetime.datetime(2012, 5, 31, 19, 0)

This is an example of how to plot data once you have an array of datetimes:

import matplotlib.pyplot as plt
import datetime
import numpy as np

x = np.array([datetime.datetime(2013, 9, 28, i, 0) for i in range(24)])
y = np.random.randint(100, size=x.shape)


enter image description here

LINQ syntax where string value is not null or empty

Problem Statement
It's possible to write LINQ to SQL that gets all rows that have either null or an empty string in a given field, but it's not possible to use string.IsNullOrEmpty to do it, even though many other string methods map to LINQ to SQL. Proposed Solution Allow string.IsNullOrEmpty in a LINQ to SQL where clause so that these two queries have the same result:

var fieldNullOrEmpty =
from item in db.SomeTable
where item.SomeField == null || item.SomeField.Equals(string.Empty)
select item;

var fieldNullOrEmpty2 =
from item in db.SomeTable
where string.IsNullOrEmpty(item.SomeField)
select item;

Other Reading:
1. DevArt
3. StackOverflow Post

Write and read a list from file

If you don't need it to be human-readable/editable, the easiest solution is to just use pickle.

To write:

with open(the_filename, 'wb') as f:
    pickle.dump(my_list, f)

To read:

with open(the_filename, 'rb') as f:
    my_list = pickle.load(f)

If you do need them to be human-readable, we need more information.

If my_list is guaranteed to be a list of strings with no embedded newlines, just write them one per line:

with open(the_filename, 'w') as f:
    for s in my_list:
        f.write(s + '\n')

with open(the_filename, 'r') as f:
    my_list = [line.rstrip('\n') for line in f]

If they're Unicode strings rather than byte strings, you'll want to encode them. (Or, worse, if they're byte strings, but not necessarily in the same encoding as your system default.)

If they might have newlines, or non-printable characters, etc., you can use escaping or quoting. Python has a variety of different kinds of escaping built into the stdlib.

Let's use unicode-escape here to solve both of the above problems at once:

with open(the_filename, 'w') as f:
    for s in my_list:
        f.write((s + u'\n').encode('unicode-escape'))

with open(the_filename, 'r') as f:
    my_list = [line.decode('unicode-escape').rstrip(u'\n') for line in f]

You can also use the 3.x-style solution in 2.x, with either the codecs module or the io module:*

import io

with, 'w', encoding='unicode-escape') as f:
    f.writelines(line + u'\n' for line in my_list)

with open(the_filename, 'r') as f:
    my_list = [line.rstrip(u'\n') for line in f]

* TOOWTDI, so which is the one obvious way? It depends… For the short version: if you need to work with Python versions before 2.6, use codecs; if not, use io.

Python Key Error=0 - Can't find Dict error in code

The error you're getting is that self.adj doesn't already have a key 0. You're trying to append to a list that doesn't exist yet.

Consider using a defaultdict instead, replacing this line (in __init__):

self.adj = {}

with this:

self.adj = defaultdict(list)

You'll need to import at the top:

from collections import defaultdict

Now rather than raise a KeyError, self.adj[0].append(edge) will create a list automatically to append to.

Using variable in SQL LIKE statement

This works for me on the Northwind sample DB, note that SearchLetter has 2 characters to it and SearchLetter also has to be declared for this to run:

declare @SearchLetter2 char(2)
declare @SearchLetter char(1)
Set @SearchLetter = 'A'
Set @SearchLetter2 = @SearchLetter+'%'
select * from Customers where ContactName like @SearchLetter2 and Region='WY'

How do I style a <select> dropdown with only CSS?

label {
    position: relative;
    display: inline-block;
select {
    display: inline-block;
    padding: 4px 3px 5px 5px;
    width: 150px;
    outline: none;
    color: black;
    border: 1px solid #C8BFC4;
    border-radius: 4px;
    box-shadow: inset 1px 1px 2px #ddd8dc;
    background-color: lightblue;

This uses a background color for select elements and I removed the image..

android: data binding error: cannot find symbol class

Don't forget to add in app level gradle, apply plugin: 'kotlin-kapt'

Display all views on oracle database

Open a new worksheet on the related instance (Alt-F10) and run the following query

SELECT view_name, owner
FROM sys.all_views 
ORDER BY owner, view_name

How to style icon color, size, and shadow of Font Awesome Icons

Try to simply use something like fa-lg,fa-2x,fa-3x,fa-4x,fa-5x to increase the icon size relative to their container

for eg:-

Swift_TransportException Connection could not be established with host

If you have hosted your website already it advisable to use the email or create an offical mail to send the email Let say your url is Then go to the cpanel create an email which will be [email protected]. Then request for the setting of the email. Change the email address to [email protected]. Then change your smtp which will be The ssl will remain 465