Programs & Examples On #Listctrl

Limiting number of displayed results when using ngRepeat

Slightly more "Angular way" would be to use the straightforward limitTo filter, as natively provided by Angular:

<ul class="phones">
  <li ng-repeat="phone in phones | filter:query | orderBy:orderProp | limitTo:quantity">
app.controller('PhoneListCtrl', function($scope, $http) {
        $scope.phones =;
    $scope.orderProp = 'age';
    $scope.quantity = 5;


Angular ng-click with call to a controller function not working

You should probably use the ngHref directive along with the ngClick:

 <a ng-href='#here' ng-click='go()' >click me</a>

Here is an example:

<body ng-controller="MainCtrl">
    <p>Hello {{name}}!</p>
    <a ng-href='#here' ng-click='go()' >click me</a>
    <div style='height:1000px'>

      <a id='here'></a>


var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $ = 'World';

  $scope.go = function() {

    $scope.msg = 'clicked';

I don't know if this will work with the library you are using but it will at least let you link and use the ngClick function.

** Update **

Here is a demo of the set and get working fine with a service.

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope, sharedProperties) {
  $ = 'World';

  $scope.go = function(item) {


  $scope.getItem = function() {

    $scope.msg = sharedProperties.getListName();

app.service('sharedProperties', function () {
    var list_name = '';

    return {

        getListName: function() {
            return list_name;
        setListName: function(name) {
            list_name = name;


* Edit *

Please review which talks about how to use lungo and angular. Also note that if your page is completely reloading when browsing to another link, you will need to persist your shared properties into localstorage and/or a cookie.

AngularJS: ng-repeat list is not updated when a model element is spliced from the model array

If you add a $scope.$apply(); right after $scope.pluginsDisplayed.splice(index,1); then it works.

I am not sure why this is happening, but basically when AngularJS doesn't know that the $scope has changed, it requires to call $apply manually. I am also new to AngularJS so cannot explain this better. I need too look more into it.

I found this awesome article that explains it quite properly. Note: I think it might be better to use ng-click (docs) rather than binding to "mousedown". I wrote a simple app here (, source based on AngularJS. It is not very clean, but it might be of help.

Removing the fragment identifier from AngularJS urls (# symbol)

Just add $locationProvider In

.config(function ($routeProvider,$locationProvider)

and then add $locationProvider.hashPrefix(''); after

        redirectTo: '/'

That's it.

How to reload / refresh model data from the server programmatically?

You're half way there on your own. To implement a refresh, you'd just wrap what you already have in a function on the scope:

function PersonListCtrl($scope, $http) {
  $scope.loadData = function () {
     $http.get('/persons').success(function(data) {
       $scope.persons = data;

  //initial load

then in your markup

<div ng-controller="PersonListCtrl">
        <li ng-repeat="person in persons">
            Name: {{}}, Age {{person.age}}
   <button ng-click="loadData()">Refresh</button>

As far as "accessing your model", all you'd need to do is access that $scope.persons array in your controller:

for example (just puedo code) in your controller:

$scope.addPerson = function() {
     $scope.persons.push({ name: 'Test Monkey' });

Then you could use that in your view or whatever you'd want to do.

angular js unknown provider

Here's another possible scenario where you can see this error:

If you use Sublime Text 2 and the angular plugin, it will generate stubs like this

angular.module('utils', [])
.factory('utilFactory', [''
    function() {
        return {


notice the empty ' ' as the first element of the array after the 'utilFactory' string. If you don't have any dependencies, remove that so it's like this:

angular.module('utils', [])
.factory('utilFactory', [
    function() {
        return {


Pagination on a list using ng-repeat

If you have not too much data, you can definitely do pagination by just storing all the data in the browser and filtering what's visible at a certain time.

Here's a simple pagination example:

That example was on the list of fiddles on the angular.js github wiki, which should be helpful:

EDIT: to (won't show "1/4.5" if there is 45 results)

vba listbox multicolumn add

Simplified example (with counter):

With Me.lstbox
    .ColumnCount = 2
    .ColumnWidths = "60;60"
    .List(i, 0) = Company_ID
    .List(i, 1) = Company_name 
    i = i + 1

end with

Make sure to start the counter with 0, not 1 to fill up a listbox.

Rounding a variable to two decimal places C#

You should use a form of Math.Round. Be aware that Math.Round defaults to banker's rounding (rounding to the nearest even number) unless you specify a MidpointRounding value. If you don't want to use banker's rounding, you should use Math.Round(decimal d, int decimals, MidpointRounding mode), like so:

Math.Round(pay, 2, MidpointRounding.AwayFromZero); // .005 rounds up to 0.01
Math.Round(pay, 2, MidpointRounding.ToEven);       // .005 rounds to nearest even (0.00) 
Math.Round(pay, 2);    // Defaults to MidpointRounding.ToEven

(Why does .NET use banker's rounding?)

Check if list contains element that contains a string and get that element

To keep it simple use this;

foreach(string item in myList)//Iterate through each item.
 if(item.Contains("Search Term")//True if the item contains search pattern.
   return item;//Return the matched item.

Alternatively,to do this with for loop,use this;

    for (int iterator = 0; iterator < myList.Count; iterator++)
        if (myList[iterator].Contains("String Pattern"))
            return myList[iterator];

How can strings be concatenated?

Use + for string concatenation as:

section = 'C_type'
new_section = 'Sec_' + section

Comparing date part only without comparing time in JavaScript

You can use some arithmetic with the total of ms.

var date = new Date(date1);
date.setHours(0, 0, 0, 0);

var diff = date2.getTime() - date.getTime();
return diff >= 0 && diff < 86400000;

I like this because no updates to the original dates are made and perfom faster than string split and compare.

Hope this help!

Add centered text to the middle of a <hr/>-like line

Heres a simple solution with css only, no background tricks...

.center-separator {
    display: flex;
  line-height: 1em;
  color: gray;

.center-separator::before, .center-separator::after {
    content: '';
    display: inline-block;
    flex-grow: 1;
    margin-top: 0.5em;
    background: gray;
    height: 1px;
    margin-right: 10px;
    margin-left: 10px;


  <div class="center-separator">
    centered text

example fiddle:

Change the location of the ~ directory in a Windows install of Git Bash

Here you go: Here you go: Create a System Restore Point. Log on under an admin account. Delete the folder C:\SomeUser. Move the folder c:\Users\SomeUser so that it becomes c:\SomeUser. Open the registry editor. Navigate to HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList. Search for "ProfileImagePath" until you find the one that points at c:\Users\SomeUser. Modify it so that it points at c:\SomeUser. Use System Restore in case things go wrong.

Using jQuery to programmatically click an <a> link

<a href="#" id="myAnchor">Click me</a>

<script type="text/javascript">
       window.location.href = 'index.php';

Java JDBC - How to connect to Oracle using Service Name instead of SID

You can also specify the TNS name in the JDBC URL as below


SyntaxError: Unexpected token function - Async Await Nodejs

Node.JS does not fully support ES6 currently, so you can either use asyncawait module or transpile it using Bable.


npm install --save asyncawait


var async = require('asyncawait/async');
var await = require('asyncawait/await');

(async (function testingAsyncAwait() {
    await (console.log("Print me!"));

@HostBinding and @HostListener: what do they do and what are they for?

Theory with less Jargons

@Hostlistnening deals basically with the host element say (a button) listening to an action by a user and performing a certain function say alert("Ahoy!") while @Hostbinding is the other way round. Here we listen to the changes that occurred on that button internally (Say when it was clicked what happened to the class) and we use that change to do something else, say emit a particular color.


Think of the scenario that you would like to make a favorite icon on a component, now you know that you would have to know whether the item has been Favorited with its class changed, we need a way to determine this. That is exactly where @Hostbinding comes in.

And where there is the need to know what action actually was performed by the user that is where @Hostlistening comes in

How to clear jQuery validation error messages?

I tested with:


It will be ok, when you need to validate it again.

Commit empty folder structure (with git)

Traditionally whenever I've wanted to commit and empty directory structure, I create the structure and then in the leaf directories place an empty file called empty.txt.

Then when I put stuff in that's ready to commit, I can simply remove the empty.txt file and commit the real files.


  • data/
    • images/
      • empty.txt

Get max and min value from array in JavaScript

if you have "scattered" (not inside an array) values you can use:

var max_value = Math.max(val1, val2, val3, val4, val5);

Writing outputs to log file and console

I tried joonty's answer, but I also got the

exec: 1: not found

error. This is what works best for me (confirmed to work in zsh also):

exec > >(tee ${LOG_FILE}) 2>&1
echo "this is stdout"
chmmm 77 /makeError

The file /tmp/both.log afterwards contains

this is stdout
chmmm command not found 

The /tmp/both.log is appended unless you remove the -a from tee.

Hint: >(...) is a process substitution. It lets the exec to the tee command as if it were a file.

Could not obtain information about Windows NT group user

In my case I was getting this error trying to use the IS_ROLEMEMBER() function on SQL Server 2008 R2. This function isn't valid prior to SQL Server 2012.

Instead of this function I ended up using

select 1 
from sys.database_principals u 
inner join sys.database_role_members ur 
    on u.principal_id = ur.member_principal_id 
inner join sys.database_principals r 
    on ur.role_principal_id = r.principal_id 
where = @role_name 
and = @username

Significantly more verbose, but it gets the job done.

printf() formatting for hex

The "0x" counts towards the eight character count. You need "%#010x".

Note that # does not append the 0x to 0 - the result will be 0000000000 - so you probably actually should just use "0x%08x" anyway.

How to remove the URL from the printing page?

Nowadays, you can use history API to modify the URL before print, then change back:

var curURL = window.location.href;
history.replaceState(history.state, '', '/');
history.replaceState(history.state, '', curURL);

But you need to make a custom PRINT button for user to click.

How to match letters only using java regex, matches method?

[A-Za-z ]* to match letters and spaces.

Regular Expression Match to test for a valid year

you can go with sth like [^-]\d{4}$: you prevent the minus sign - to be before your 4 digits.
you can also use ^\d{4}$ with ^ to catch the beginning of the string. It depends on your scenario actually...

How can I remove space (margin) above HTML header?

I solved the space issue by adding a border and removing is by setting a negative margin. Do not know what the underlying problem is though.

header {
  border-top: 1px solid gold !important;
  margin-top: -1px !important;

How can I search for a commit message on GitHub?

As of mid-2019

  1. type your query in the top left search box
  2. hit Enter
  3. click "Commits"


enter image description here

How to call C++ function from C?

#include <iostream>

// C++ code //
struct A
  int i;
  int j;

  A() {i=1; j=2; std::cout << "class A created\n";}
  void dump() {std::cout << "class A dumped: " << i << ":" << j << std::endl;}
  ~A() {std::cout << "class A destroyed\n";}

extern "C" {
  // this is the C code interface to the class A
  static void *createA (void)
    // create a handle to the A class
    return (void *)(new A);
  static void dumpA (void *thisPtr)
    // call A->dump ()
    if (thisPtr != NULL) // I'm an anal retentive programmer
      A *classPtr = static_cast<A *>(thisPtr);
      classPtr->dump ();
  static void *deleteA (void *thisPtr)
    // destroy the A class
    if (thisPtr != NULL)
      delete (static_cast<A *>(thisPtr));

// this can be compiled as C code //
int main (int argc, char **argv)
  void *handle = createA();

  dumpA (handle);
  deleteA (handle);

  return 0;

IN vs OR in the SQL WHERE Clause

I assume you want to know the performance difference between the following:

WHERE foo IN ('a', 'b', 'c')
WHERE foo = 'a' OR foo = 'b' OR foo = 'c'

According to the manual for MySQL if the values are constant IN sorts the list and then uses a binary search. I would imagine that OR evaluates them one by one in no particular order. So IN is faster in some circumstances.

The best way to know is to profile both on your database with your specific data to see which is faster.

I tried both on a MySQL with 1000000 rows. When the column is indexed there is no discernable difference in performance - both are nearly instant. When the column is not indexed I got these results:

SELECT COUNT(*) FROM t_inner WHERE val IN (1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000);
1 row fetched in 0.0032 (1.2679 seconds)

SELECT COUNT(*) FROM t_inner WHERE val = 1000 OR val = 2000 OR val = 3000 OR val = 4000 OR val = 5000 OR val = 6000 OR val = 7000 OR val = 8000 OR val = 9000;
1 row fetched in 0.0026 (1.7385 seconds)

So in this case the method using OR is about 30% slower. Adding more terms makes the difference larger. Results may vary on other databases and on other data.

Way to insert text having ' (apostrophe) into a SQL table

INSERT INTO exampleTbl VALUES('he doesn''t work for me')

If you're adding a record through ASP.NET, you can use the SqlParameter object to pass in values so you don't have to worry about the apostrophe's that users enter in.

How to convert an array of key-value tuples into an object

I much more recommend you to use ES6 with it's perfect Object.assign() method.

Object.assign({},[ key, value ]) => ({ [key]: value })));

What happening here - Object.assign() do nothing but take key:value from donating object and puts pair in your result. In this case I'm using ... to split new array to multiply pairs (after map it looks like [{'cardType':'iDEBIT'}, ... ]). So in the end, new {} receives every key:property from each pair from mapped array.

Highlight the difference between two strings in PHP

What you are looking for is a "diff algorithm". A quick google search led me to this solution. I did not test it, but maybe it will do what you need.

Should we pass a shared_ptr by reference or by value?

This question has been discussed and answered by Scott, Andrei and Herb during Ask Us Anything session at C++ and Beyond 2011. Watch from 4:34 on shared_ptr performance and correctness.

Shortly, there is no reason to pass by value, unless the goal is to share ownership of an object (eg. between different data structures, or between different threads).

Unless you can move-optimise it as explained by Scott Meyers in the talk video linked above, but that is related to actual version of C++ you can use.

A major update to this discussion has happened during GoingNative 2012 conference's Interactive Panel: Ask Us Anything! which is worth watching, especially from 22:50.

Unable to connect with remote debugger

The other answers here were missing one crucial step for me. In AndroidManifest.xml I needed to add usesCleartextTraffic:


You probably don't want to keep this in the production release of your app though, unless you want to support insecure http requests.

After I added this to my AndroidManifest.xml, then I followed Tom Aranda's answer, and the emulator was finally able to connect to the debugger.

What is a 'NoneType' object?

In the error message, instead of telling you that you can't concatenate two objects by showing their values (a string and None in this example), the Python interpreter tells you this by showing the types of the objects that you tried to concatenate. The type of every string is str while the type of the single None instance is called NoneType.

You normally do not need to concern yourself with NoneType, but in this example it is necessary to know that type(None) == NoneType.

Fatal error: Namespace declaration statement has to be the very first statement in the script in

Sometimes this issue come because of space in PHP start tag of controller facing same issue just removed whitespace in:

namespace App\Http\Controllers\Auth;

removing the space resolved my error

Download file using libcurl in C/C++

The example you are using is wrong. See the man page for easy_setopt. In the example write_data uses its own FILE, *outfile, and not the fp that was specified in CURLOPT_WRITEDATA. That's why closing fp causes problems - it's not even opened.

This is more or less what it should look like (no libcurl available here to test)

#include <stdio.h>
#include <curl/curl.h>
/* For older cURL versions you will also need 
#include <curl/types.h>
#include <curl/easy.h>
#include <string>

size_t write_data(void *ptr, size_t size, size_t nmemb, FILE *stream) {
    size_t written = fwrite(ptr, size, nmemb, stream);
    return written;

int main(void) {
    CURL *curl;
    FILE *fp;
    CURLcode res;
    char *url = "http://localhost/aaa.txt";
    char outfilename[FILENAME_MAX] = "C:\\bbb.txt";
    curl = curl_easy_init();
    if (curl) {
        fp = fopen(outfilename,"wb");
        curl_easy_setopt(curl, CURLOPT_URL, url);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
        res = curl_easy_perform(curl);
        /* always cleanup */
    return 0;

Updated: as suggested by @rsethc types.h and easy.h aren't present in current cURL versions anymore.

How to use OKHTTP to make a post request?

To add okhttp as a dependency do as follows

  • right click on the app on android studio open "module settings"
  • "dependencies"-> "add library dependency" -> "com.squareup.okhttp3:okhttp:3.10.0" -> add -> ok..

now you have okhttp as a dependency

Now design a interface as below so we can have the callback to our activity once the network response received.

public interface NetworkCallback {

    public void getResponse(String res);

I create a class named NetworkTask so i can use this class to handle all the network requests

    public class NetworkTask extends AsyncTask<String , String, String>{

    public NetworkCallback instance;
    public String url ;
    public String json;
    public int task ;
    OkHttpClient client = new OkHttpClient();
    public static final MediaType JSON
            = MediaType.parse("application/json; charset=utf-8");

    public NetworkTask(){


    public NetworkTask(NetworkCallback ins, String url, String json, int task){
        this.instance = ins;
        this.url = url;
        this.json = json;
        this.task = task;

    public String doGetRequest() throws IOException {
        Request request = new Request.Builder()

        Response response = client.newCall(request).execute();
        return response.body().string();

    public String doPostRequest() throws IOException {
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
        Response response = client.newCall(request).execute();
        return response.body().string();

    protected String doInBackground(String[] params) {
        try {
            String response = "";
                case 1 :
                    response = doGetRequest();
                case 2:
                    response = doPostRequest();

            return response;
        }catch (Exception e){
        return null;

    protected void onPostExecute(String s) {

now let me show how to get the callback to an activity

    public class MainActivity extends AppCompatActivity implements NetworkCallback{
    String postUrl = "http://your-post-url-goes-here";
    String getUrl = "http://your-get-url-goes-here";
    Button doGetRq;
    Button doPostRq;

    protected void onCreate(Bundle savedInstanceState) {
        Button button = findViewById(;

        doGetRq = findViewById(;
    doPostRq = findViewById(;

        doPostRq.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

        doGetRq.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

    public void sendPostRq(){
        JSONObject jo = new JSONObject();
        try {
            jo.put("email", "yourmail");

        } catch (JSONException e) {
    // 2 because post rq is for the case 2
        NetworkTask t = new NetworkTask(this, postUrl,  jo.toString(), 2);

    public void sendGetRq(){

    // 1 because get rq is for the case 1
        NetworkTask t = new NetworkTask(this, getUrl,  jo.toString(), 1);

    public void getResponse(String res) {
    // here is the response from NetworkTask class

How to convert 2D float numpy array to 2D int numpy array?

If you're not sure your input is going to be a Numpy array, you can use asarray with dtype=int instead of astype:

>>> np.asarray([1,2,3,4], dtype=int)
array([1, 2, 3, 4])

If the input array already has the correct dtype, asarray avoids the array copy while astype does not (unless you specify copy=False):

>>> a = np.array([1,2,3,4])
>>> a is np.asarray(a)  # no copy :)
>>> a is a.astype(int)  # copy :(
>>> a is a.astype(int, copy=False)  # no copy :)

R cannot be resolved - Android error

For me, I removed "import android.R;" and it fixed all my problems. What a nightmare!!!

JSON library for C#

To answer your first question, Microsoft does ship a DataContractJsonSerializer: see msdn How to: Serialize and Deserialize JSON Data

How to handle button clicks using the XML onClick within Fragments

I would rather go for the click handling in code than using the onClick attribute in XML when working with fragments.

This becomes even easier when migrating your activities to fragments. You can just call the click handler (previously set to android:onClick in XML) directly from each case block.


OnClickListener clickListener = new OnClickListener() {
    public void onClick(final View v) {
        switch(v.getId()) {
              // Which is supposed to be called automatically in your
              // activity, which has now changed to a fragment.


When it comes to handling clicks in fragments, this looks simpler to me than android:onClick.

Read values into a shell variable from a pipe

In my eyes the best way to read from stdin in bash is the following one, which also lets you work on the lines before the input ends:

while read LINE; do
    echo $LINE
done < /dev/stdin

CSS table layout: why does table-row not accept a margin?

adding a br tag between the divs worked. add br tag between two divs that are display:table-row in a parent with display:table

How to reset selected file with input tag file type in Angular 2?


<input [(ngModel)]="componentField" type="file" (change)="fileChange($event)" placeholder="Upload file">


fileChange(event) {
        this.torrentFileValue = '';

In Flask, What is request.args and how is it used?

It has some interesting behaviour in some cases that is good to be aware of:

from werkzeug.datastructures import MultiDict

d = MultiDict([("ex1", ""), ("ex2", None)])

d.get("ex1", "alternive")
# returns: ''

d.get("ex2", "alternative")
# returns no visible output of any kind
# It is returning literally None, so if you do:
d.get("ex2", "alternative") is None
# it returns: True

d.get("ex3", "alternative")
# returns: 'alternative'

Is there a CSS selector by class prefix?

It's not doable with CSS2.1, but it is possible with CSS3 attribute substring-matching selectors (which are supported in IE7+):

div[class^="status-"], div[class*=" status-"]

Notice the space character in the second attribute selector. This picks up div elements whose class attribute meets either of these conditions:

  • [class^="status-"] — starts with "status-"

  • [class*=" status-"] — contains the substring "status-" occurring directly after a space character. Class names are separated by whitespace per the HTML spec, hence the significant space character. This checks any other classes after the first if multiple classes are specified, and adds a bonus of checking the first class in case the attribute value is space-padded (which can happen with some applications that output class attributes dynamically).

Naturally, this also works in jQuery, as demonstrated here.

The reason you need to combine two attribute selectors as described above is because an attribute selector such as [class*="status-"] will match the following element, which may be undesirable:

<div id='D' class='foo-class foo-status-bar bar-class'></div>

If you can ensure that such a scenario will never happen, then you are free to use such a selector for the sake of simplicity. However, the combination above is much more robust.

If you have control over the HTML source or the application generating the markup, it may be simpler to just make the status- prefix its own status class instead as Gumbo suggests.

Display / print all rows of a tibble (tbl_df)

i prefer to physically print my tables instead:


data.frame = data.frame(1:1000, 1000:2)

connectServer <- Sys.getenv("CONNECT_SERVER")
apiKey <- Sys.getenv("CONNECT_API_KEY")


print2print::send2printer(connectServer, apiKey, data.frame)

Java, How do I get current index/key in "for each" loop

In Java, you can't, as foreach was meant to hide the iterator. You must do the normal For loop in order to get the current iteration.

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

Unrelated, I'm sure, but do wrap your IDisposable objects in using blocks to ensure proper disposal:

using System;
using System.Net;
using System.IO;

namespace ConsoleProgram
    public class Class1
        private const string URL = "";
        private const string DATA = @"{""object"":{""name"":""Name""}}";

        static void Main(string[] args)

        private static void CreateObject()
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
            request.Method = "POST";
            request.ContentType = "application/json";
            request.ContentLength = DATA.Length;
            using (Stream webStream = request.GetRequestStream())
            using (StreamWriter requestWriter = new StreamWriter(webStream, System.Text.Encoding.ASCII))

                WebResponse webResponse = request.GetResponse();
                using (Stream webStream = webResponse.GetResponseStream() ?? Stream.Null)
                using (StreamReader responseReader = new StreamReader(webStream))
                    string response = responseReader.ReadToEnd();
            catch (Exception e)

Linq : select value in a datatable column

If the return value is string and you need to search by Id you can use:

string name = datatable.AsEnumerable().Where(row => Convert.ToInt32(row["Id"]) == Id).Select(row => row.Field<string>("name")).ToString();

or using generic variable:

var name = datatable.AsEnumerable().Where(row => Convert.ToInt32(row["Id"]) == Id).Select(row => row.Field<string>("name"));

background-image: url("images/plaid.jpg") no-repeat; wont show up

Most important

Keep in mind that relative URLs are resolved from the URL of your stylesheet.

So it will work if folder images is inside the stylesheets folder.

From you description you would need to change it to either




Additional 1

Also you cannot have no selector..

CSS is applied through selectors..

Additional 2

You should use either the shorthand background to pass multiple values like this

background: url("../images/plaid.jpg") no-repeat;

or the verbose syntax of specifying each property on its own

background-image: url("../images/plaid.jpg");

send mail to multiple receiver with HTML mailto

"There are no safe means of assigning multiple recipients to a single mailto: link via HTML. There are safe, non-HTML, ways of assigning multiple recipients from a mailto: link."

For a quick fix to your problem, change your ; to a comma , and eliminate the spaces between email addresses

<a href='mailto:[email protected],[email protected]'>Email Us</a>

Get position/offset of element relative to a parent container?

in pure js just use offsetLeft and offsetTop properties.
Example fiddle:

var elm = document.querySelector('span');_x000D_
console.log(elm.offsetLeft, elm.offsetTop);
p   { position:relative; left:10px; top:85px; border:1px solid blue; }_x000D_
span{ position:relative; left:30px; top:35px; border:1px solid red; }

Change the Right Margin of a View Programmatically?

Update: Android KTX

The Core KTX module provides extensions for common libraries that are part of the Android framework, androidx.core.view among them.

dependencies {
    implementation "androidx.core:core-ktx:{latest-version}"

The following extension functions are handy to deal with margins:

Note: they are all extension functions of MarginLayoutParams, so first you need to get and cast the layoutParams of your view:

val params = (myView.layoutParams as ViewGroup.MarginLayoutParams)

Sets the margins of all axes in the ViewGroup's MarginLayoutParams. (The dimension has to be provided in pixels, see the last section if you want to work with dp)

inline fun MarginLayoutParams.setMargins(@Px size: Int): Unit
// E.g. 16px margins

Updates the margins in the ViewGroup's ViewGroup.MarginLayoutParams.

inline fun MarginLayoutParams.updateMargins(
    @Px left: Int = leftMargin, 
    @Px top: Int = topMargin, 
    @Px right: Int = rightMargin, 
    @Px bottom: Int = bottomMargin
): Unit
// Example: 8px left margin 
params.updateMargins(left = 8)

Updates the relative margins in the ViewGroup's MarginLayoutParams (start/end instead of left/right).

inline fun MarginLayoutParams.updateMarginsRelative(
    @Px start: Int = marginStart, 
    @Px top: Int = topMargin, 
    @Px end: Int = marginEnd, 
    @Px bottom: Int = bottomMargin
): Unit
// E.g: 8px start margin 
params.updateMargins(start = 8)

The following extension properties are handy to get the current margins:

inline val View.marginBottom: Int
inline val View.marginEnd: Int
inline val View.marginLeft: Int
inline val View.marginRight: Int
inline val View.marginStart: Int
inline val View.marginTop: Int
// E.g: get margin bottom
val bottomPx = myView1.marginBottom
  • Using dp instead of px:

If you want to work with dp (density-independent pixels) instead of px, you will need to convert them first. You can easily do that with the following extension property:

val Int.px: Int
    get() = (this * Resources.getSystem().displayMetrics.density).toInt()

Then you can call the previous extension functions like:

params.updateMargins(start = 16.px, end = 16.px, top = 8.px, bottom = 8.px)
val bottomDp = myView1.marginBottom.dp

Old answer:

In Kotlin you can declare an extension function like:

fun View.setMargins(
    leftMarginDp: Int? = null,
    topMarginDp: Int? = null,
    rightMarginDp: Int? = null,
    bottomMarginDp: Int? = null
) {
    if (layoutParams is ViewGroup.MarginLayoutParams) {
        val params = layoutParams as ViewGroup.MarginLayoutParams
        leftMarginDp?.run { params.leftMargin = this.dpToPx(context) }
        topMarginDp?.run { params.topMargin = this.dpToPx(context) }
        rightMarginDp?.run { params.rightMargin = this.dpToPx(context) }
        bottomMarginDp?.run { params.bottomMargin = this.dpToPx(context) }

fun Int.dpToPx(context: Context): Int {
    val metrics = context.resources.displayMetrics
    return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, this.toFloat(), metrics).toInt()

Then you can call it like:

myView1.setMargins(8, 16, 34, 42)


myView2.setMargins(topMarginDp = 8) 

Can you delete multiple branches in one command with Git?

You can use git gui to delete multiple branches at once. From Command Prompt/Bash -> git gui -> Remote -> Delete branch ... -> select remote branches you want to remove -> Delete.

Entry point for Java applications: main(), init(), or run()?

The main() method is the entry point for a Java application. run() is typically used for new threads or tasks.

Where have you been writing a run() method, what kind of application are you writing (e.g. Swing, AWT, console etc) and what's your development environment?

Convert java.util.Date to String

public static void main(String[] args) 
    Date d = new Date();
    SimpleDateFormat form = new SimpleDateFormat("dd-mm-yyyy hh:mm:ss");
    String str = form.format(d); // or if you want to save it in String str
    System.out.println(str); // and print after that

Performance differences between ArrayList and LinkedList

The ArrayList class is a wrapper class for an array. It contains an inner array.

public ArrayList<T> {
    private Object[] array;
    private int size;

A LinkedList is a wrapper class for a linked list, with an inner node for managing the data.

public LinkedList<T> {
    class Node<T> {
        T data;
        Node next;
        Node prev;
    private Node<T> first;
    private Node<T> last;
    private int size;

Note, the present code is used to show how the class may be, not the actual implementation. Knowing how the implementation may be, we can do the further analysis:

ArrayList is faster than LinkedList if I randomly access its elements. I think random access means "give me the nth element". Why ArrayList is faster?

Access time for ArrayList: O(1). Access time for LinkedList: O(n).

In an array, you can access to any element by using array[index], while in a linked list you must navigate through all the list starting from first until you get the element you need.

LinkedList is faster than ArrayList for deletion. I understand this one. ArrayList's slower since the internal backing-up array needs to be reallocated.

Deletion time for ArrayList: Access time + O(n). Deletion time for LinkedList: Access time + O(1).

The ArrayList must move all the elements from array[index] to array[index-1] starting by the item to delete index. The LinkedList should navigate until that item and then erase that node by decoupling it from the list.

LinkedList is faster than ArrayList for deletion. I understand this one. ArrayList's slower since the internal backing-up array needs to be reallocated.

Insertion time for ArrayList: O(n). Insertion time for LinkedList: O(1).

Why the ArrayList can take O(n)? Because when you insert a new element and the array is full, you need to create a new array with more size (you can calculate the new size with a formula like 2 * size or 3 * size / 2). The LinkedList just add a new node next to the last.

This analysis is not just in Java but in another programming languages like C, C++ and C#.

More info here:

Convert date time string to epoch in Bash

For Linux Run this command

date -d '06/12/2012 07:21:22' +"%s"

For mac OSX run this command

date -j -u -f "%a %b %d %T %Z %Y" "Tue Sep 28 19:35:15 EDT 2010" "+%s"

creating Hashmap from a JSON String

public Map<String, String> parseJSON(JSONObject json, Map<String, String> dataFields) throws JSONException {
        Iterator<String> keys = json.keys();
        while (keys.hasNext()) {
            String key =;
            String val = null;
            try {
                JSONObject value = json.getJSONObject(key);
                parseJSON(value, dataFields);
            } catch (Exception e) {
                if (json.isNull(key)) {
                    val = "";
                } else {
                    try {
                        val = json.getString(key);
                    } catch (Exception ex) {

            if (val != null) {
                dataFields.put(key, val);
        return dataFields;

The best way to calculate the height in a binary search tree? (balancing an AVL-tree)

  • Height is easily implemented by recursion, take the maximum of the height of the subtrees plus one.

  • The "balance factor of R" refers to the right subtree of the tree which is out of balance, I suppose.

Are multi-line strings allowed in JSON?

JSON does not allow real line-breaks. You need to replace all the line breaks with \n.


"first line second line"

can saved with:

"first line\nsecond line"


for Python, this should be written as:

"first line\\nsecond line"

where \\ is for escaping the backslash, otherwise python will treat \n as the control character "new line"

Creating default object from empty value in PHP?

Try this:

ini_set('error_reporting', E_STRICT);

Word wrapping in phpstorm

You have to enable Soft Wraps. Find that option through this path.

View > Active Editor > Use Soft Wraps

wrap words in PhpStorm

Mocking HttpClient in unit tests

After carefully searching, I figured out the best approach to accomplish this.

    private HttpResponseMessage response;

    public void Setup()
        var handlerMock = new Mock<HttpMessageHandler>();

           // This line will let you to change the response in each test method
           .ReturnsAsync(() => response);

        _httpClient = new HttpClient(handlerMock.Object);

        yourClinet = new YourClient( _httpClient);

As you noticed I have used Moq and Moq.Protected packages.

An unhandled exception of type 'System.IO.FileNotFoundException' occurred in Unknown Module

For me it was occurring in a .net project and turned out to be something to do with my Visual Studio installation. I downloaded and installed the latest .net core sdk separately and then reinstalled VS and it worked.

What does this symbol mean in JavaScript?

See the documentation on MDN about expressions and operators and statements.

Basic keywords and general expressions

this keyword:

var x = function() vs. function x() — Function declaration syntax

(function(){})() — IIFE (Immediately Invoked Function Expression)

someFunction()() — Functions which return other functions

=> — Equal sign, greater than: arrow function expression syntax

|> — Pipe, greater than: Pipeline operator

function*, yield, yield* — Star after function or yield: generator functions

[], Array() — Square brackets: array notation

If the square brackets appear on the left side of an assignment ([a] = ...), or inside a function's parameters, it's a destructuring assignment.

{key: value} — Curly brackets: object literal syntax (not to be confused with blocks)

If the curly brackets appear on the left side of an assignment ({ a } = ...) or inside a function's parameters, it's a destructuring assignment.

`${}` — Backticks, dollar sign with curly brackets: template literals

// — Slashes: regular expression literals

$ — Dollar sign in regex replace patterns: $$, $&, $`, $', $n

() — Parentheses: grouping operator

Property-related expressions

obj.prop, obj[prop], obj["prop"] — Square brackets or dot: property accessors

?., ?.[], ?.() — Question mark, dot: optional chaining operator

:: — Double colon: bind operator

new operator

...iter — Three dots: spread syntax; rest parameters

Increment and decrement

++, -- — Double plus or minus: pre- / post-increment / -decrement operators

Unary and binary (arithmetic, logical, bitwise) operators

delete operator

void operator

+, - — Plus and minus: addition or concatenation, and subtraction operators; unary sign operators

|, &, ^, ~ — Single pipe, ampersand, circumflex, tilde: bitwise OR, AND, XOR, & NOT operators

% — Percent sign: remainder operator

&&, ||, ! — Double ampersand, double pipe, exclamation point: logical operators

?? — Double question mark: nullish-coalescing operator

** — Double star: power operator (exponentiation)

Equality operators

==, === — Equal signs: equality operators

!=, !== — Exclamation point and equal signs: inequality operators

Bit shift operators

<<, >>, >>> — Two or three angle brackets: bit shift operators

Conditional operator

?:… — Question mark and colon: conditional (ternary) operator

Assignment operators

= — Equal sign: assignment operator

%= — Percent equals: remainder assignment

+= — Plus equals: addition assignment operator

&&=, ||=, ??= — Double ampersand, pipe, or question mark, followed by equal sign: logical assignments


Comma operator

, — Comma operator

Control flow

{} — Curly brackets: blocks (not to be confused with object literal syntax)


var, let, const — Declaring variables


label: — Colon: labels

# — Hash (number sign): Private methods or private fields

CryptographicException 'Keyset does not exist', but only through WCF

This issue is got resolved after adding network service role.

Error :Keyset does not exist means System might not have access to private key
Error :Enveloped data … 
Step 1:Install certificate in local machine not in current user store
Step 2:Run certificate manager
Step 3:Find your certificate in the local machine tab and right click manage privatekey and check in allowed personnel following have been added:
c>'Network service'
And then provide respective permissions.

## You need to add 'Network Service' and then it will start working.

Tensorflow: Using Adam optimizer

You need to call tf.global_variables_initializer() on you session, like

init = tf.global_variables_initializer()

Full example is available in this great tutorial

Replace spaces with dashes and make all letters lower-case

Just use the String replace and toLowerCase methods, for example:

var str = "Sonic Free Games";
str = str.replace(/\s+/g, '-').toLowerCase();
console.log(str); // "sonic-free-games"

Notice the g flag on the RegExp, it will make the replacement globally within the string, if it's not used, only the first occurrence will be replaced, and also, that RegExp will match one or more white-space characters.

Check if user is using IE


In order to not depend on the user-agent string, just check for a few properties:

if (document.documentMode) 
    console.log('Hello Microsoft IE User!');

if (!document.documentMode && window.msWriteProfilerMark) {
    console.log('Hello Microsoft Edge User!');

if (document.documentMode || window.msWriteProfilerMark) 
    console.log('Hello Microsoft User!');

if (window.msWriteProfilerMark) 
    console.log('Hello Microsoft User in fewer characters!');

Also, this detects the new Chredge/Edgium (Anaheim):

function isEdg()

    for (var i = 0, u="Microsoft", l =u.length; i < navigator.plugins.length; i++)
        if (navigator.plugins[i].name != null && navigator.plugins[i].name.substr(0, l) === u)
            return true;

    return false;

And this detects chromium:

function isChromium()

    for (var i = 0, u="Chromium", l =u.length; i < navigator.plugins.length; i++)
        if (navigator.plugins[i].name != null && navigator.plugins[i].name.substr(0, l) === u)
            return true;

    return false;

And this Safari:

    console.log("Safari, yeah!");

Inline instantiation of a constant List

const is for compile-time constants. You could just make it static readonly, but that would only apply to the METRICS variable itself (which should typically be Metrics instead, by .NET naming conventions). It wouldn't make the list immutable - so someone could call METRICS.Add("shouldn't be here");

You may want to use a ReadOnlyCollection<T> to wrap it. For example:

public static readonly IList<String> Metrics = new ReadOnlyCollection<string>
    (new List<String> { 
         SourceFile.LoC, SourceFile.McCabe, SourceFile.NoM,
         SourceFile.NoA, SourceFile.FanOut, SourceFile.FanIn, 
         SourceFile.Par, SourceFile.Ndc, SourceFile.Calls });

ReadOnlyCollection<T> just wraps a potentially-mutable collection, but as nothing else will have access to the List<T> afterwards, you can regard the overall collection as immutable.

(The capitalization here is mostly guesswork - using fuller names would make them clearer, IMO.)

Whether you declare it as IList<string>, IEnumerable<string>, ReadOnlyCollection<string> or something else is up to you... if you expect that it should only be treated as a sequence, then IEnumerable<string> would probably be most appropriate. If the order matters and you want people to be able to access it by index, IList<T> may be appropriate. If you want to make the immutability apparent, declaring it as ReadOnlyCollection<T> could be handy - but inflexible.

Convert String to Uri

What are you going to do with the URI?

If you're just going to use it with an HttpGet for example, you can just use the string directly when creating the HttpGet instance.

HttpGet get = new HttpGet("");

bypass invalid SSL certificate in .net core


As mentioned below, not all implementations support this callback (i.e. platforms like iOS). In this case, as the docs say, you can set the validator explicitly:

handler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;

This works too for .NET Core 2.2, 3.0 and 3.1

Old answer, with more control but may throw PlatformNotSupportedException:

You can override SSL cert check on a HTTP call with the a anonymous callback function like this

using (var httpClientHandler = new HttpClientHandler())
   httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return true; };
   using (var client = new HttpClient(httpClientHandler))
       // Make your request...

Additionally, I suggest to use a factory pattern for HttpClient because it is a shared object that might no be disposed immediately and therefore connections will stay open.

How can I convert a string to upper- or lower-case with XSLT?

<xsl:variable name="upper">UPPER CASE</xsl:variable>
<xsl:variable name="lower" select="translate($upper,'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz')"/>
<xsl:value-of select ="$lower"/>

//displays UPPER CASE as upper case

macro run-time error '9': subscript out of range

Why are you using a macro? Excel has Password Protection built-in. When you select File/Save As... there should be a Tools button by the Save button, click it then "General Options" where you can enter a "Password to Open" and a "Password to Modify".

How to check the installed version of React-Native

The best practice for checking the react native environment information.

react-native info

which will give the information

React Native Environment Info:
  OS: Linux 4.15 Ubuntu 18.04.1 LTS (Bionic Beaver)
  CPU: (8) x64 Intel(R) Core(TM) i7-3770 CPU @ 3.40GHz
  Memory: 2.08 GB / 7.67 GB
  Shell: 4.4.19 - /bin/bash
  Node: 8.10.0 - /usr/bin/node
  Yarn: 1.12.3 - /usr/bin/yarn
  npm: 3.5.2 - /usr/bin/npm
  react: 16.4.1 => 16.4.1 
  react-native: 0.56.0 => 0.56.0 
  react-native-cli: 2.0.1
  react-native: 0.57.8

Vendor code 17002 to connect to SQLDeveloper

I encountered same problem with ORACLE 11G express on Windows. After a long time waiting I got the same error message.

My solution is to make sure the hostname in tnsnames.ora (usually it's not "localhost") and the default hostname in sql developer(usually it's "localhost") same. You can either do this by changing it in the tnsnames.ora, or filling up the same in the sql developer.

Oh, of course you need to reboot all the oracle services (just to be safe).

Hope it helps.

I came across the similar problem again on another machine, but this time above solution doesn't work. After some trying, I found restarting all the oracle related services can fix the problem. Originally when the installation is done, connection can be made. Somehow after several reboot of computer, there is problem. I change all the oracle services with start time as auto. And once I could not connect, I restart them all over again (the core service should be restarted at last order), and works fine.

Some article says it might be due to the MTS problem. Microsoft's problem. Maybe!

How do you change the colour of each category within a highcharts column chart?

Also you can set option:

  {plotOptions: {column: {colorByPoint: true}}}

for more information read docs

Clicking URLs opens default browser

in some cases you might need an override of onLoadResource if you get a redirect which doesn't trigger the url loading method. in this case i tried the following:

public void onLoadResource(WebView view, String url)
    if (url.equals(""))
        //do your own thing here
        super.onLoadResource(view, url);

How to copy static files to build directory with Webpack?

Requiring assets using the file-loader module is the way webpack is intended to be used (source). However, if you need greater flexibility or want a cleaner interface, you can also copy static files directly using my copy-webpack-plugin (npm, Github). For your static to build example:

const CopyWebpackPlugin = require('copy-webpack-plugin');
module.exports = {
    context: path.join(__dirname, 'your-app'),
    plugins: [
        new CopyWebpackPlugin({
            patterns: [
                { from: 'static' }

ValueError: shape mismatch: objects cannot be broadcast to a single shape

This particular error implies that one of the variables being used in the arithmetic on the line has a shape incompatible with another on the same line (i.e., both different and non-scalar). Since n and the output of np.add.reduce() are both scalars, this implies that the problem lies with xm and ym, the two of which are simply your x and y inputs minus their respective means.

Based on this, my guess is that your x and y inputs have different shapes from one another, making them incompatible for element-wise multiplication.

** Technically, it's not that variables on the same line have incompatible shapes. The only problem is when two variables being added, multiplied, etc., have incompatible shapes, whether the variables are temporary (e.g., function output) or not. Two variables with different shapes on the same line are fine as long as something else corrects the issue before the mathematical expression is evaluated.

Deploying Java webapp to Tomcat 8 running in Docker container

You are trying to copy the war file to a directory below webapps. The war file should be copied into the webapps directory.

Remove the mkdir command, and copy the war file like this:

COPY /1.0-SNAPSHOT/my-app-1.0-SNAPSHOT.war /usr/local/tomcat/webapps/myapp.war

Tomcat will extract the war if autodeploy is turned on.

Difference between except: and except Exception as e: in Python

There are differences with some exceptions, e.g. KeyboardInterrupt.

Reading PEP8:

A bare except: clause will catch SystemExit and KeyboardInterrupt exceptions, making it harder to interrupt a program with Control-C, and can disguise other problems. If you want to catch all exceptions that signal program errors, use except Exception: (bare except is equivalent to except BaseException:).

How can I declare a two dimensional string array?

A 3x3 (multidimensional) array can also be initialized (you have already declared it) like this:

string[,] Tablero =  {
                        { "a", "b", "c" },
                        { "d", "e", "f" }, 
                        { "g", "h", "i"} 

Setting graph figure size

Write it as a one-liner:

figure('position', [0, 0, 200, 500])  % create new figure with specified size  

enter image description here

How to set child process' environment variable in Makefile

I only needed the environment variables locally to invoke my test command, here's an example setting multiple environment vars in a bash shell, and escaping the dollar sign in make.

SHELL := /bin/bash

.PHONY: test tests
test tests:
    PATH=./node_modules/.bin/:$$PATH \
    nodeunit tests/

Please add a @Pipe/@Directive/@Component annotation. Error

In my case I mistakenly added this:

    selector: 'app-some-item',
    templateUrl: './some-item.component.html',
    styleUrls: ['./some-item.component.scss'],
    providers: [ConfirmationService]

declare var configuration: any;

while the correct form is:

declare var configuration: any;

    selector: 'app-some-item',
    templateUrl: './some-item.component.html',
    styleUrls: ['./some-item.component.scss'],
    providers: [ConfirmationService]

python list in sql query as parameter

To run a select from where field is in list of strings (instead of int), as per this question use repr(tuple(map(str, l))). Full example:

l = ['a','b','c']
sql = f'''

select name 
from students 
where id in {repr(tuple(map(str, l)))}

Returns: select name from students where id in ('a', 'b', 'c')

For a list of dates in Oracle, this worked

dates_str = ','.join([f'DATE {repr(s)}' for s in ['2020-11-24', '2020-12-28']])
dates_str = f'({dates_str})'

sql_cmd = f'''
select *
from students 
and date in {dates_str}

Returns: select * from students where and date in (DATE '2020-11-24',DATE '2020-12-28')

ExtJs Gridpanel store refresh

reload the ds to refresh grid.


Is there a simple, elegant way to define singletons?

I don't really see the need, as a module with functions (and not a class) would serve well as a singleton. All its variables would be bound to the module, which could not be instantiated repeatedly anyway.

If you do wish to use a class, there is no way of creating private classes or private constructors in Python, so you can't protect against multiple instantiations, other than just via convention in use of your API. I would still just put methods in a module, and consider the module as the singleton.

how to compare the Java Byte[] array?

Use Arrays.equals() if you want to compare the actual content of arrays that contain primitive types values (like byte).

System.out.println(Arrays.equals(aa, bb));

Use Arrays.deepEquals for comparison of arrays that contain objects.

Is there a download function in jsFiddle?


then just use inspect element function of browser. you will get code in iframe tab. . in chrome just right click and cick on edit as html tab. and copy the html content. that is your actual code.

await is only valid in async function

The current implementation of async / await only supports the await keyword inside of async functions Change your start function signature so you can use await inside start.

 var start = async function(a, b) {


For those interested, the proposal for top-level await is currently in Stage 2:

Destroy or remove a view in Backbone.js

According to current Backbone documentation....


Removes a view and its el from the DOM, and calls stopListening to remove any bound events that the view has listenTo'd.

Click event doesn't work on dynamically generated elements

Try .live() or .delegate()

Your .test element was added after the .click() method, so it didn't have the event attached to it. Live and Delegate give that event trigger to parent elements which check their children, so anything added afterwards still works. I think Live will check the entire document body, while Delegate can be given to an element, so Delegate is more efficient.

More info:

Why does Git treat this text file as a binary file?

Change the Aux.js to another name, like Sig.js.

The source tree still shows it as a binary file, but you can stage(add) it and commit.

python dict to numpy structured array

Even more simple if you accept using pandas :

import pandas
result = {0: 1.1181753789488595, 1: 0.5566080288678394, 2: 0.4718269778030734, 3: 0.48716683119447185, 4: 1.0, 5: 0.1395076201641266, 6: 0.20941558441558442}
df = pandas.DataFrame(result, index=[0])
print df

gives :

          0         1         2         3  4         5         6
0  1.118175  0.556608  0.471827  0.487167  1  0.139508  0.209416

How to add border radius on table row

You can only apply border-radius to td, not tr or table. I've gotten around this for rounded corner tables by using these styles:

table { border-collapse: separate; }
td { border: solid 1px #000; }
tr:first-child td:first-child { border-top-left-radius: 10px; }
tr:first-child td:last-child { border-top-right-radius: 10px; }
tr:last-child td:first-child { border-bottom-left-radius: 10px; }
tr:last-child td:last-child { border-bottom-right-radius: 10px; }

Be sure to provide all the vendor prefixes. Here's an example of it in action.

How to match any non white space character except a particular one?

You can use a character class:


matches anything that is not a whitespace character nor a \. Here's another example:

[abc] means "match a, b or c"; [^abc] means "match any character except a, b or c".

Spring Security with roles and permissions

ACL was overkill for my requirements also.
I ended up creating a library similar to @Alexander's to inject a GrantedAuthority list for Role->Permissions based on the role membership of a user.

For example, using a DB to hold the relationships -

RolePermissionsRepository repository;

public void setup(){
  String roleName = "ROLE_ADMIN";
  List<String> permissions = new ArrayList<String>();
  permissions.add("DELETE"); RolePermissions(roleName, permissions));

When an Authentication object is injected in the current security session, it will have the original roles/granted authorities.

This library provides 2 built-in integration points for Spring Security. When the integration point is reached, the PermissionProvider is called to get the effective permissions for each role the user is a member of.
The distinct list of permissions are added as GrantedAuthority items in the Authentication object.

You can also implement a custom PermissionProvider to store the relationships in config for example.

A more complete explanation here -

And the source code is here -

How to activate virtualenv?

Windows 10

In Windows these directories are created :

Windows 10 Virtual Environment directories

To activate Virtual Environment in Windows 10.


\scripts directory contain activate file.

Linux Ubuntu

In Ubuntu these directories are created :

Linux Ubuntu Virtual Environment directories

To activate Virtual Environment in Linux Ubuntu.

source ./bin/activate

/bin directory contain activate file.

Virtual Environment copied from Windows to Linux Ubuntu vice versa

If Virtual environment folder copied from Windows to Linux Ubuntu then according to directories:

source ./down/Scripts/activate

Comparing Java enum members: == or equals()?

I want to complement polygenelubricants answer:

I personally prefer equals(). But it lake the type compatibility check. Which I think is an important limitation.

To have type compatibility check at compilation time, declare and use a custom function in your enum.

public boolean isEquals(enumVariable) // compare constant from left
public static boolean areEqual(enumVariable, enumVariable2) // compare two variable

With this, you got all the advantage of both solution: NPE protection, easy to read code and type compatibility check at compilation time.

I also recommend to add an UNDEFINED value for enum.

Converting a JS object to an array using jQuery

I made a custom function:

    var arr=new Array();
    for( var i in this ) {
        if (this.hasOwnProperty(i)){
    return arr;

Echo off but messages are displayed

@echo off
// quote the path or else it won't work if there are spaces in the path
SET INSTALL_PATH="c:\\etc etc\\test";
if exist %INSTALL_PATH% (
   echo 222;

How to generate random number in Bash?

You can also use shuf (available in coreutils).

shuf -i 1-100000 -n 1

Difference between clean, gradlew clean

You should use this one too:

./gradlew :app:dependencies (Mac and Linux) -With ./

gradlew :app:dependencies (Windows) -Without ./

The libs you are using internally using any other versions of google play service.If yes then remove or update those libs.

Marquee text in Android

Here is an example:

public class TextViewMarquee extends Activity {
    private TextView tv;
    protected void onCreate(Bundle savedInstanceState) {
        tv = (TextView) this.findViewById(;  
        tv.setSelected(true);  // Set focus to the textview

The xml file with the textview:

        android:text="Simple application that shows how to use marquee, with a long text" />

Error: invalid operands of types ‘const char [35]’ and ‘const char [2]’ to binary ‘operator+’

In this particular case, an even simpler fix would be to just get rid of the "+" all together because AGE is a string literal and what comes before and after are also string literals. You could write line 3 as:

str += "Do you feel " AGE " years old?";

This is because most C/C++ compilers will concatenate string literals automatically. The above is equivalent to:

str += "Do you feel " "42" " years old?";

which the compiler will convert to:

str += "Do you feel 42 years old?";

How to highlight a current menu item?

Here's a simple approach that works well with Angular.

    <li ng-class="{ active: isActive('/View1') }"><a href="#/View1">View 1</a></li>
    <li ng-class="{ active: isActive('/View2') }"><a href="#/View2">View 2</a></li>
    <li ng-class="{ active: isActive('/View3') }"><a href="#/View3">View 3</a></li>

Within your AngularJS controller:

$scope.isActive = function (viewLocation) {
     var active = (viewLocation === $location.path());
     return active;

This thread has a number of other similar answers.

How to set bootstrap navbar active class with Angular JS?

How to access parameters in a RESTful POST method

Your @POST method should be accepting a JSON object instead of a string. Jersey uses JAXB to support marshaling and unmarshaling JSON objects (see the jersey docs for details). Create a class like:

public class MyJaxBean {
    @XmlElement public String param1;
    @XmlElement public String param2;

Then your @POST method would look like the following:

@POST @Consumes("application/json")
public void create(final MyJaxBean input) {
    System.out.println("param1 = " + input.param1);
    System.out.println("param2 = " + input.param2);

This method expects to receive JSON object as the body of the HTTP POST. JAX-RS passes the content body of the HTTP message as an unannotated parameter -- input in this case. The actual message would look something like:

POST /create HTTP/1.1
Content-Type: application/json
Content-Length: 35


Using JSON in this way is quite common for obvious reasons. However, if you are generating or consuming it in something other than JavaScript, then you do have to be careful to properly escape the data. In JAX-RS, you would use a MessageBodyReader and MessageBodyWriter to implement this. I believe that Jersey already has implementations for the required types (e.g., Java primitives and JAXB wrapped classes) as well as for JSON. JAX-RS supports a number of other methods for passing data. These don't require the creation of a new class since the data is passed using simple argument passing.


The parameters would be annotated using @FormParam:

public void create(@FormParam("param1") String param1,
                   @FormParam("param2") String param2) {

The browser will encode the form using "application/x-www-form-urlencoded". The JAX-RS runtime will take care of decoding the body and passing it to the method. Here's what you should see on the wire:

POST /create HTTP/1.1
Content-Type: application/x-www-form-urlencoded;charset=UTF-8
Content-Length: 25


The content is URL encoded in this case.

If you do not know the names of the FormParam's you can do the following:

@POST @Consumes("application/x-www-form-urlencoded")
public void create(final MultivaluedMap<String, String> formParams) {

HTTP Headers

You can using the @HeaderParam annotation if you want to pass parameters via HTTP headers:

public void create(@HeaderParam("param1") String param1,
                   @HeaderParam("param2") String param2) {

Here's what the HTTP message would look like. Note that this POST does not have a body.

POST /create HTTP/1.1
Content-Length: 0
param1: hello
param2: world

I wouldn't use this method for generalized parameter passing. It is really handy if you need to access the value of a particular HTTP header though.

HTTP Query Parameters

This method is primarily used with HTTP GETs but it is equally applicable to POSTs. It uses the @QueryParam annotation.

public void create(@QueryParam("param1") String param1,
                   @QueryParam("param2") String param2) {

Like the previous technique, passing parameters via the query string does not require a message body. Here's the HTTP message:

POST /create?param1=hello&param2=world HTTP/1.1
Content-Length: 0

You do have to be particularly careful to properly encode query parameters on the client side. Using query parameters can be problematic due to URL length restrictions enforced by some proxies as well as problems associated with encoding them.

HTTP Path Parameters

Path parameters are similar to query parameters except that they are embedded in the HTTP resource path. This method seems to be in favor today. There are impacts with respect to HTTP caching since the path is what really defines the HTTP resource. The code looks a little different than the others since the @Path annotation is modified and it uses @PathParam:

public void create(@PathParam("param1") String param1,
                   @PathParam("param2") String param2) {

The message is similar to the query parameter version except that the names of the parameters are not included anywhere in the message.

POST /create/hello/world HTTP/1.1
Content-Length: 0

This method shares the same encoding woes that the query parameter version. Path segments are encoded differently so you do have to be careful there as well.

As you can see, there are pros and cons to each method. The choice is usually decided by your clients. If you are serving FORM-based HTML pages, then use @FormParam. If your clients are JavaScript+HTML5-based, then you will probably want to use JAXB-based serialization and JSON objects. The MessageBodyReader/Writer implementations should take care of the necessary escaping for you so that is one fewer thing that can go wrong. If your client is Java based but does not have a good XML processor (e.g., Android), then I would probably use FORM encoding since a content body is easier to generate and encode properly than URLs are. Hopefully this mini-wiki entry sheds some light on the various methods that JAX-RS supports.

Note: in the interest of full disclosure, I haven't actually used this feature of Jersey yet. We were tinkering with it since we have a number of JAXB+JAX-RS applications deployed and are moving into the mobile client space. JSON is a much better fit that XML on HTML5 or jQuery-based solutions.

How to default to other directory instead of home directory

Add the line to the .bashrc file in the home directory (create the file if it doesn't exist):

cd ~
touch .bashrc
echo "cd ~/Desktop/repos/" >> .bashrc

How to know which is running in Jupyter notebook?

from platform import python_version


This will give you the exact version of python running your script. eg output:


What's the difference between a temp table and table variable in SQL Server?

In which scenarios does one out-perform the other?

For smaller tables (less than 1000 rows) use a temp variable, otherwise use a temp table.

Increasing (or decreasing) the memory available to R processes

From: (mirror)

Windows users may get the error that R has run out of memory.

If you have R already installed and subsequently install more RAM, you may have to reinstall R in order to take advantage of the additional capacity.

You may also set the amount of available memory manually. Close R, then right-click on your R program icon (the icon on your desktop or in your programs directory). Select ``Properties'', and then select the ``Shortcut'' tab. Look for the ``Target'' field and after the closing quotes around the location of the R executible, add


as shown in the figure below. You may increase this value up to 2GB or the maximum amount of physical RAM you have installed.

If you get the error that R cannot allocate a vector of length x, close out of R and add the following line to the ``Target'' field:


or as appropriate. You can always check to see how much memory R has available by typing at the R prompt


which gives you the amount of available memory in MB. In previous versions of R you needed to use: round(memory.limit()/2^20, 2).

C++ template constructor

Here's a workaround.

Make a template subclass B of A. Do the template-argument-independent part of the construction in A's constructor. Do the template-argument-dependent part in B's constructor.

Could not resolve in Android Studio new project

try this :

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.1"
defaultConfig {

        targetSdkVersion 26


compile ''

It has worked for me

Controlling Spacing Between Table Cells

Check this fiddle. You are going to need to take a look at using border-collapse and border-spacing. There are some quirks for IE (as usual). This is based on an answer to this question.

table.test td {
  background-color: lime;
  margin: 12px 12px 12px 12px;
  padding: 12px 12px 12px 12px;

table.test {
  border-collapse: separate;
  border-spacing: 10px;
  *border-collapse: expression('separate', cellSpacing='10px');
<table class="test">

Adding a module (Specifically pymorph) to Spyder (Python IDE)

Using ! on the IPython console within spyder allows you to use pip. So, in the example, you could do:

[1] !pip install pymorph

Note, this is also available (though perhaps unreliably) on the Python console for Spyder versions before ~2.3.3. Thanks to @CarlosCordoba for this clarification.

Notify ObservableCollection when Item changes

I solved this case by using static Action

public class CatalogoModel 
    private String _Id;
    private String _Descripcion;
    private Boolean _IsChecked;

    public String Id
        get { return _Id; }
        set { _Id = value; }
    public String Descripcion
        get { return _Descripcion; }
        set { _Descripcion = value; }
    public Boolean IsChecked
        get { return _IsChecked; }
           _IsChecked = value;

    public static Action OnItemChecked;

public class ReglaViewModel : ViewModelBase
    private ObservableCollection<CatalogoModel> _origenes;

    CatalogoModel.OnItemChecked = () =>
                var x = Origenes.Count;  //Entra cada vez que cambia algo en _origenes

ASP.NET Identity's default Password Hasher - How does it work and is it secure?

Here is how the default implementation (ASP.NET Framework or ASP.NET Core) works. It uses a Key Derivation Function with random salt to produce the hash. The salt is included as part of the output of the KDF. Thus, each time you "hash" the same password you will get different hashes. To verify the hash the output is split back to the salt and the rest, and the KDF is run again on the password with the specified salt. If the result matches to the rest of the initial output the hash is verified.


public static string HashPassword(string password)
    byte[] salt;
    byte[] buffer2;
    if (password == null)
        throw new ArgumentNullException("password");
    using (Rfc2898DeriveBytes bytes = new Rfc2898DeriveBytes(password, 0x10, 0x3e8))
        salt = bytes.Salt;
        buffer2 = bytes.GetBytes(0x20);
    byte[] dst = new byte[0x31];
    Buffer.BlockCopy(salt, 0, dst, 1, 0x10);
    Buffer.BlockCopy(buffer2, 0, dst, 0x11, 0x20);
    return Convert.ToBase64String(dst);


public static bool VerifyHashedPassword(string hashedPassword, string password)
    byte[] buffer4;
    if (hashedPassword == null)
        return false;
    if (password == null)
        throw new ArgumentNullException("password");
    byte[] src = Convert.FromBase64String(hashedPassword);
    if ((src.Length != 0x31) || (src[0] != 0))
        return false;
    byte[] dst = new byte[0x10];
    Buffer.BlockCopy(src, 1, dst, 0, 0x10);
    byte[] buffer3 = new byte[0x20];
    Buffer.BlockCopy(src, 0x11, buffer3, 0, 0x20);
    using (Rfc2898DeriveBytes bytes = new Rfc2898DeriveBytes(password, dst, 0x3e8))
        buffer4 = bytes.GetBytes(0x20);
    return ByteArraysEqual(buffer3, buffer4);

Aggregate a dataframe on a given column and display another column

Here is a solution using the plyr package.

The following line of code essentially tells ddply to first group your data by Group, and then within each group returns a subset where the Score equals the maximum score in that group.

ddply(data, .(Group), function(x)x[x$Score==max(x$Score), ])

  Group Score Info
1     1     3    c
2     2     4    d

And, as @SachaEpskamp points out, this can be further simplified to:

ddply(df, .(Group), function(x)x[which.max(x$Score), ])

(which also has the advantage that which.max will return multiple max lines, if there are any).

How do I make an editable DIV look like a text field?

You can place a TEXTAREA of similar size under your DIV, so the standard control's frame would be visible around div.

It's probably good to set it to be disabled, to prevent accidental focus stealing.

React Native fetch() Network Request Failed

This is not an answer but option. I switched to It works good both for form-data and files

Difference between nVidia Quadro and Geforce cards?

I have read that while the underlying chips are essentially the same, the design of the board is different.

Gamers want performance, and tend to favor overclocking and other things to get high frame rates but which maybe burn out the hardware occasionally.

Businesses want reliability, and tend to favor underclocking so they can be sure that their people can keep working.

Also, I have read that the quadro boards use ECC memory.

If you don't know what ECC memory is about: it's a [relatively] well known fact that sometimes memory "flips bits (experiences errors)". This does not happen too often, but is an unavoidable consequence of the underlying physics of the memory cards and the world we live in. ECC memory adds a small percentage to the cost and a small penalty to the performance and has enough redundancy to correct occasional errors and to detect (but not correct) somewhat rarer errors. Gamers don't care about that kind of accuracy because for gamers those are just very rare visual glitches. Companies do care about that kind of accuracy because those glitches would wind up as glitches in their products or else would require more double or triple checking (which winds up being a 2x or 3x performance penalty for some part of their business).

Another issue I have read about has to do with hooking up the graphics card to third party hardware. In other words: sending the images to another card or to another machine instead of to the screen. Most gamers are just using canned software that doesn't have any use for such capabilities. Companies that use that kind of thing get orders of magnitude performance gains from the more direct connections.

Update query using Subquery in Sql Server

The title of this thread asks how a subquery can be used in an update. Here's an example of that:

update [dbName].[dbo].[MyTable] 
set MyColumn = 1 
        select count(*) 
        from [dbName].[dbo].[MyTable] mt2 
            mt2.ID > [dbName].[dbo].[MyTable].ID
            and mt2.Category = [dbName].[dbo].[MyTable].Category
    ) > 0

How to vertically center a "div" element for all browsers using CSS?

The three lines of code using transform works practically on modern browsers and Internet Explorer:

     position: relative;
     top: 50%;
     transform: translateY(-50%);
     -moz-transform: translateY(-50%);
     -webkit-transform: translateY(-50%);
     -ms-transform: translateY(-50%);

I am adding this answer since I found some incompleteness in the previous version of this answer (and Stack Overflow won't allow me to simply comment).

  1. 'position' relative messes up the styling if the current div is in the body and has no container div. However 'fixed' seems to work, but it obviously fixes the content in the center of the viewport position: relative

  2. Also I used this styling for centering some overlay divs and found that in Mozilla all elements inside this transformed div had lost their bottom borders. Possibly a rendering issue. But adding just the minimal padding to some of them rendered it correctly. Chrome and Internet Explorer (surprisingly) rendered the boxes without any need for padding mozilla without inner paddings mozilla with paddings

Is there a version of JavaScript's String.indexOf() that allows for regular expressions?

For data with sparse matches, using is the fastest across browsers. It re-slices a string each iteration to :

function lastIndexOfSearch(string, regex, index) {
  if(index === 0 || index)
     string = string.slice(0, Math.max(0,index));
  var idx;
  var offset = -1;
  while ((idx = !== -1) {
    offset += idx + 1;
    string = string.slice(idx + 1);
  return offset;

For dense data I made this. It's complex compared to the execute method, but for dense data, it's 2-10x faster than every other method I tried, and about 100x faster than the accepted solution. The main points are:

  1. It calls exec on the regex passed in once to verify there is a match or quit early. I do this using (?= in a similar method, but on IE checking with exec is dramatically faster.
  2. It constructs and caches a modified regex in the format '(r).(?!.?r)'
  3. The new regex is executed and the results from either that exec, or the first exec, are returned;

    function lastIndexOfGroupSimple(string, regex, index) {
        if (index === 0 || index) string = string.slice(0, Math.max(0, index + 1));
        regex.lastIndex = 0;
        var lastRegex, index
        flags = 'g' + (regex.multiline ? 'm' : '') + (regex.ignoreCase ? 'i' : ''),
        key = regex.source + '$' + flags,
        match = regex.exec(string);
        if (!match) return -1;
        if (lastIndexOfGroupSimple.cache === undefined) lastIndexOfGroupSimple.cache = {};
        lastRegex = lastIndexOfGroupSimple.cache[key];
        if (!lastRegex)
            lastIndexOfGroupSimple.cache[key] = lastRegex = new RegExp('.*(' + regex.source + ')(?!.*?' + regex.source + ')', flags);
        index = match.index;
        lastRegex.lastIndex = match.index;
        return (match = lastRegex.exec(string)) ? lastRegex.lastIndex - match[1].length : index;

jsPerf of methods

I don't understand the purpose of the tests up top. Situations that require a regex are impossible to compare against a call to indexOf, which I think is the point of making the method in the first place. To get the test to pass, it makes more sense to use 'xxx+(?!x)', than adjust the way the regex iterates.

Anonymous method in Invoke call

myControl.Invoke(new MethodInvoker(delegate() {...}))

LEFT function in Oracle

LEFT is not a function in Oracle. This probably came from someone familiar with SQL Server:

Returns the left part of a character string with the specified number of characters.

-- Syntax for SQL Server, Azure SQL Database, Azure SQL Data Warehouse, Parallel Data Warehouse  
LEFT ( character_expression , integer_expression )  

HTML page disable copy/paste

You can use jquery for this:

$('body').bind('copy paste',function(e) {
    e.preventDefault(); return false; 

Using jQuery bind() and specififying your desired eventTypes .

Code line wrapping - how to handle long lines

This is how I do it, and Google does it my way.

  • Break before the symbol for non-assignment operators.
  • Break after the symbol for = and for ,.

In your case, since you're using 120 characters, you can break it after the assignment operator resulting in

private static final Map<Class<? extends Persistent>, PersistentHelper> class2helper =
        new HashMap<Class<? extends Persistent>, PersistentHelper>();

In Java, and for this particular case, I would give two tabs (or eight spaces) after the break, depending on whether tabs or spaces are used for indentation.

This is of course a personal preference and if your project has its own convention for line-wrapping then that is what you should follow whether you like it or not.

Difference between "@id/" and "@+id/" in Android

Difference between @+id and @id is:

  • @+id is used to create an id for a view in file.
  • @id is used to refer the id created for the view in file.

We use @+id with android:id="", but what if the id is not created and we are referring it before getting created(Forward Referencing).

In that case, we have use @+id to create id and while defining the view we have to refer it.

Please refer the below code:


        android:layout_toLeftOf="@+id/spinner" />

     android:layout_alignParentRight="true" />


In the above code,id for Spinner @+id/spinner is created in other view and while defining the spinner we are referring the id created above.

So, we have to create the id if we are using the view before the view has been created.

How can I check if a scrollbar is visible?

I'm going to extend on this even further for those poor souls who, like me, use one of the modern js frameworks and not JQuery and have been wholly abandoned by the people of this thread :

this was written in Angular 6 but if you write React 16, Vue 2, Polymer, Ionic, React-Native, you'll know what to do to adapt it. And it's the whole component so it should be easy.

import {ElementRef, AfterViewInit} from '@angular/core';

  selector: 'app',
  templateUrl: './app.html',
  styleUrls: ['./app.scss']
export class App implements AfterViewInit {

  private fb: FormBuilder,
  private element: ElementRef 
) {}

  this.scrollAmount = this.element.nativeElement.querySelector('.elem-list');
  this.scrollAmount.addEventListener('wheel', e => { //you can put () instead of e
  // but e is usefull if you require the deltaY amount.
    if(this.scrollAmount.scrollHeight > this.scrollAmount.offsetHeight){
       // there is a scroll bar, do something!
       // there is NO scroll bar, do something!

in the html there would be a div with class "elem-list" which is stylized in the css or scss to have a height and an overflow value that isn't hidden. (so auto or sroll )

I trigger this eval upon a scroll event because my end goal was to have "automatic focus scrolls" which decide whether they are scrolling the whole set of components horizontally if said components have no vertical scroll available and otherwise only scroll the innards of one of the components vertically.

but you can place the eval elsewhere to have it be triggered by something else.

the important thing to remember here, is you're never Forced back into using JQuery, there's always a way to access the same functionalities it has without using it.

How do you use math.random to generate random ints?

you are importing java.util package. That's why its giving error. there is a random() in java.util package too. Please remove the import statement importing java.util package. then your program will use random() method for java.lang by default and then your program will work. remember to cast it i.e

int x = (int)(Math.random()*100);

How can I commit files with git?

It looks like all of the edits are already a part of the index. So to commit just use the commit command

git commit -m "My Commit Message"

Looking at your messages though my instinct says that you probably don't want the cache files to be included in your depot. Especially if it something that is built on the fly when running your program. If so then you should add the following line to your .gitignore file


Parsing JSON from XmlHttpRequest.responseJSON

New ways I: fetch

TL;DR I'd recommend this way as long as you don't have to send synchronous requests or support old browsers.

A long as your request is asynchronous you can use the Fetch API to send HTTP requests. The fetch API works with promises, which is a nice way to handle asynchronous workflows in JavaScript. With this approach you use fetch() to send a request and ResponseBody.json() to parse the response:

  .then(function(response) {
    return response.json();
  .then(function(jsonResponse) {
    // do something with jsonResponse

Compatibility: The Fetch API is not supported by IE11 as well as Edge 12 & 13. However, there are polyfills.

New ways II: responseType

As Londeren has written in his answer, newer browsers allow you to use the responseType property to define the expected format of the response. The parsed response data can then be accessed via the response property:

var req = new XMLHttpRequest();
req.responseType = 'json';'GET', url, true);
req.onload  = function() {
   var jsonResponse = req.response;
   // do something with jsonResponse

Compatibility: responseType = 'json' is not supported by IE11.

The classic way

The standard XMLHttpRequest has no responseJSON property, just responseText and responseXML. As long as bitly really responds with some JSON to your request, responseText should contain the JSON code as text, so all you've got to do is to parse it with JSON.parse():

var req = new XMLHttpRequest();
req.overrideMimeType("application/json");'GET', url, true);
req.onload  = function() {
   var jsonResponse = JSON.parse(req.responseText);
   // do something with jsonResponse

Compatibility: This approach should work with any browser that supports XMLHttpRequest and JSON.


If you prefer to use responseJSON, but want a more lightweight solution than JQuery, you might want to check out my JSONHttpRequest. It works exactly like a normal XMLHttpRequest, but also provides the responseJSON property. All you have to change in your code would be the first line:

var req = new JSONHttpRequest();

JSONHttpRequest also provides functionality to easily send JavaScript objects as JSON. More details and the code can be found here:

Full disclosure: I'm the owner of Pixels|Bytes. I thought that my script was a good solution for the original question, but it is rather outdated today. I do not recommend to use it anymore.

How to search for an element in an stl list?

No, not directly in the std::list template itself. You can however use std::find algorithm like that:

std::list<int> my_list;
int some_value = 12;
std::list<int>::iterator iter = std::find (my_list.begin(), my_list.end(), some_value);
// now variable iter either represents valid iterator pointing to the found element,
// or it will be equal to my_list.end()

changing default x range in histogram matplotlib

the following code is for making the same y axis limit on two subplots

f ,ax = plt.subplots(1,2,figsize = (30, 13),gridspec_kw={'width_ratios': [5, 1]})
df.plot(ax = ax[0], linewidth = 2.5)
ylim = [lower_limit,upper_limit]
ax[1].hist(data,normed =1, bins = num_bin, color = 'yellow' ,alpha = 1) 

just a reminder, plt.hist(range=[low, high]) the histogram auto crops the range if the specified range is larger than the max&min of the data points. So if you want to specify the y-axis range number, i prefer to use set_ylim

Best way to work with transactions in MS SQL Server Management Studio

I want to add a point that you can also (and should if what you are writing is complex) add a test variable to rollback if you are in test mode. Then you can execute the whole thing at once. Often I also add code to see the before and after results of various operations especially if it is a complex script.

Example below:

USE AdventureWorks;
DECLARE @TEST INT = 1--1 is test mode, use zero when you are ready to execute

     IF @TEST= 1
            SELECT *FROM Production.Product
                WHERE ProductID = 980;
    -- Generate a constraint violation error.
    DELETE FROM Production.Product
    WHERE ProductID = 980;

     IF @TEST= 1
            SELECT *FROM Production.Product
                WHERE ProductID = 980;
            IF @@TRANCOUNT > 0

        ERROR_NUMBER() AS ErrorNumber
        ,ERROR_SEVERITY() AS ErrorSeverity
        ,ERROR_STATE() AS ErrorState
        ,ERROR_PROCEDURE() AS ErrorProcedure
        ,ERROR_LINE() AS ErrorLine
        ,ERROR_MESSAGE() AS ErrorMessage;

    IF @@TRANCOUNT > 0


Class has been compiled by a more recent version of the Java Environment

For temporary solution just right click on Project => Properties => Java compiler => over there please select compiler compliance level 1.8 => .class compatibility 1.8 => source compatibility 1.8.

Then your code will start to execute on version 1.8.

EOFException - how to handle?

The best way to handle this would be to terminate your infinite loop with a proper condition.

But since you asked for the exception handling:

Try to use two catches. Your EOFException is expected, so there seems to be no problem when it occures. Any other exception should be handled.

} catch (EOFException e) {
   // ... this is fine
} catch(IOException e) {
    // handle exception which is not expected

import httplib ImportError: No module named httplib

If you use PyCharm, please change you 'Project Interpreter' to '2.7.x'

enter image description here

Increase heap size in Java

Can I increase the heap memory to 75% of physical memory(6GB Heap).

Yes you can. In fact, you can increase to more than the amount of physical memory, if you want to.

Whether it is a good idea to do this depends on how much else is running on your system. In particular, if the "working set" of the applications and services that are currently running significantly exceeds the available physical memory, your system is liable to "thrash", spending a lot of time moving virtual memory pages to and from disk. The net effect is that the system gets horribly slow.

Set value to an entire column of a pandas dataframe

I had a similar issue before even with this approach df.loc[:,'industry'] = 'yyy', but once I refreshed the notebook, it ran well.

You may want to try refreshing the cells after you have df.loc[:,'industry'] = 'yyy'.

How to convert int to float in python?

The answers provided above are absolutely correct and worth to read but I just wanted to give a straight forward answer to the question.

The question asked is just a type conversion question and here its conversion from int data type to float data type and for that you can do it by the function :


And for more details you can visit this page.

How do I send a cross-domain POST request via JavaScript?

High level.... You need to have a cname setup on your server so that points to

Your page dynamically creates an invisible iframe, which acts as your transport to You then have to communicate via JS from your page to the and have call backs that return the data back to your page.

Possible but requires coordination from and

Converting a factor to numeric without losing information R (as.numeric() doesn't seem to work)

First, factor consists of indices and levels. This fact is very very important when you are struggling with factor.

For example,

> z <- factor(letters[c(3, 2, 3, 4)])

# human-friendly display, but internal structure is invisible
> z
[1] c b c d
Levels: b c d

# internal structure of factor
> unclass(z)
[1] 2 1 2 3
[1] "b" "c" "d"

here, z has 4 elements.
The index is 2, 1, 2, 3 in that order.
The level is associated with each index: 1 -> b, 2 -> c, 3 -> d.

Then, as.numeric converts simply the index part of factor into numeric.
as.character handles the index and levels, and generates character vector expressed by its level.

?as.numeric says that Factors are handled by the default method.

Commenting code in Notepad++

Two ways for block commenting:

  1. Ctrl+Shift+Q


  1. Select the block
  2. Alt + Right click
  3. Choose block comment.

Box shadow for bottom side only

You have to specify negative spread in the box shadow to remove side shadow

-webkit-box-shadow: 0 10px 10px -10px #000000;
   -moz-box-shadow: 0 10px 10px -10px #000000;
        box-shadow: 0 10px 10px -10px #000000;

Check out and try changing properties and know how it behaves

PHP Curl UTF-8 Charset

function page_title($val){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$val);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:25.0) Gecko/20100101 Firefox/25.0');
    curl_setopt($ch, CURLOPT_ENCODING , "gzip");
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    $return = curl_exec($ch); 
    $encot = false;
    $charset = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);

    $html = str_get_html('"'.$return.'"');

    if(strpos($charset,'charset=') !== false) {
        $c = str_replace("text/html; charset=","",$charset);
        $encot = true;
    else {
        $chrst = $lookat->content;
        preg_match('/charset=(.+)/', $chrst, $found);
        $p = trim($found[1]);
        if(!empty($p) && $p != "")
            $c = $p;
            $encot = true;
    $title = $html->find('title')[0]->innertext;
    if($encot == true && $c != 'utf-8' && $c != 'UTF-8') $title = mb_convert_encoding($title,'UTF-8',$c);

    return $title;

Printing variables in Python 3.4

You can also format the string like so:

>>> print ("{index}. {word} appears {count} times".format(index=1, word='Hello', count=42))

Which outputs

1. Hello appears 42 times.

Because the values are named, their order does not matter. Making the example below output the same as the above example.

>>> print ("{index}. {word} appears {count} times".format(count=42, index=1, word='Hello'))

Formatting string this way allows you to do this.

>>> data = {'count':42, 'index':1, 'word':'Hello'}
>>> print ("{index}. {word} appears {count} times.".format(**data))
1. Hello appears 42 times.

Add a column to existing table and uniquely number them on MS SQL Server

Depends on the database as each database has a different way to add sequence numbers. I would alter the table to add the column then write a db script in groovy/python/etc to read in the data and update the id with a sequence. Once the data has been set, I would add a sequence to the table that starts after the top number. Once the data has been set, set the primary keys correctly.

Tomcat: How to find out running tomcat version

For windows machine 
Go to the tomcat directory C:\apache-tomcat-x.0.xx\bin
    Using CATALINA_BASE:   "C:\apache-tomcat-x.0.xx"
    Using CATALINA_HOME:   "C:\apache-tomcat-x.0.xx"
    Using CATALINA_TMPDIR: "C:\apache-tomcat-x.0.xx\temp"
    Using JRE_HOME:        "C:\Program Files\Java\jdk1.8.0_65"
    Using CLASSPATH:       "C:\apache-tomcat-x.0.xx\bin\bootstrap.jar;C:\apache-tomcat-x.0.xx\bin\tomcat-juli.jar"
    Server version: Apache Tomcat/7.0.53

For Linux Machine 
Go to the tomcat directory /usr/mack/apache-tomcat-x.0.xx/bin
    # ./
    Using CATALINA_BASE:   /usr/mack/apache-tomcat-x.0.xx
    Using CATALINA_HOME:   /usr/mack/apache-tomcat-x.0.xx
    Using CATALINA_TMPDIR: /usr/mack/apache-tomcat-x.0.xx/temp
    Using JRE_HOME:        /usr/java/jdk1.7.0_71/jre
    Using CLASSPATH:       /usr/mack/apache-tomcat-x.0.xx/bin/bootstrap.jar:/usr/mack/apache-tomcat-x.0.xx/bin/tomcat-juli.jar
    Server version: Apache Tomcat/7.0.56

If Tomcat is installed as a service:

#sudo /etc/init.d/tomcat version

How to truncate text in Angular2?

Here's an alternative approach using an interface to describe the shape of an options object to be passed via the pipe in the markup.

  name: 'textContentTruncate'
export class TextContentTruncatePipe implements PipeTransform {

  transform(textContent: string, options: TextTruncateOptions): string {
    if (textContent.length >= options.sliceEnd) {
      let truncatedText = textContent.slice(options.sliceStart, options.sliceEnd);
      if (options.prepend) { truncatedText = `${options.prepend}${truncatedText}`; }
      if (options.append) { truncatedText = `${truncatedText}${options.append}`; }
      return truncatedText;
    return textContent;


interface TextTruncateOptions {
  sliceStart: number;
  sliceEnd: number;
  prepend?: string;
  append?: string;

Then in your markup:

{{someText | textContentTruncate:{sliceStart: 0, sliceEnd: 50, append: '...'} }}

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

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

Problem :

This exception occurs when the app is trying to notify the user from the background thread (AsyncTask) by opening a Dialog.

If you are trying to modify the UI from background thread (usually from onPostExecute() of AsyncTask) and if the activity enters finishing stage i.e.) explicitly calling finish(), user pressing home or back button or activity clean up made by Android then you get this error.

Reason :

The reason for this exception is that, as the exception message says, the activity has finished but you are trying to display a dialog with a context of the finished activity. Since there is no window for the dialog to display the android runtime throws this exception.


Use isFinishing() method which is called by Android to check whether this activity is in the process of finishing: be it explicit finish() call or activity clean up made by Android. By using this method it is very easy to avoid opening dialog from background thread when activity is finishing.

Also maintain a weak reference for the activity (and not a strong reference so that activity can be destroyed once not needed) and check if the activity is not finishing before performing any UI using this activity reference (i.e. showing a dialog).


private class chkSubscription extends AsyncTask<String, Void, String>{

  private final WeakReference<login> loginActivityWeakRef;

  public chkSubscription (login loginActivity) {
    this.loginActivityWeakRef= new WeakReference<login >(loginActivity)

  protected String doInBackground(String... params) {
    //web service call

  protected void onPostExecute(String result) {
    if(page.contains("error")) //when not subscribed
      if (loginActivityWeakRef.get() != null && !loginActivityWeakRef.get().isFinishing()) {
        AlertDialog.Builder builder = new AlertDialog.Builder(login.this);

        builder.setNeutralButton("Ok",new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog, int whichButton){

Update :

Window Tokens:

As its name implies, a window token is a special type of Binder token that the window manager uses to uniquely identify a window in the system. Window tokens are important for security because they make it impossible for malicious applications to draw on top of the windows of other applications. The window manager protects against this by requiring applications to pass their application's window token as part of each request to add or remove a window. If the tokens don't match, the window manager rejects the request and throws a BadTokenException. Without window tokens, this necessary identification step wouldn't be possible and the window manager wouldn't be able to protect itself from malicious applications.

 A real-world scenario:

When an application starts up for the first time, the ActivityManagerService creates a special kind of window token called an application window token, which uniquely identifies the application's top-level container window. The activity manager gives this token to both the application and the window manager, and the application sends the token to the window manager each time it wants to add a new window to the screen. This ensures secure interaction between the application and the window manager (by making it impossible to add windows on top of other applications), and also makes it easy for the activity manager to make direct requests to the window manager.

jQuery AJAX form data serialize using PHP

try it , but first be sure what is you response console.log(response) on ajax success from server

<script src=""></script>
var form=$("#myForm");

        success: function(response){
        if(response === 1){
            //load chech.php file  
        }  else {
            //show error

Converting to UTC timestamp in Python

Considering you have a datetime object called d, use the following to get the timestamp in UTC:


And for the opposite direction, use following :

d = datetime.strptime("2008-09-03T20:56:35.450686Z", "%Y-%m-%dT%H:%M:%S.%fZ")

sublime text2 python error message /usr/bin/python: can't find '__main__' module in ''

Save the .py files before you build in sublime.Such as save the file on desktop or other document.

How to get option text value using AngularJS?

Also you can do like this:

<select class="form-control postType" ng-model="selectedProd">
    <option ng-repeat="product in productList" value="{{product}}">{{}}</option>

where "selectedProd" will be selected product.

Append to string variable

var str1 = "add";
str1 = str1 + " ";

Hope that helps,


How to remove undefined and null values from an object using lodash?

Taking in account that undefined == null we can write as follows:

let collection = {
  a: undefined,
  b: 2,
  c: 4,
  d: null,

console.log(_.omit(collection, it => it == null))
// -> { b: 2, c: 4 }

JSBin example

INSERT ... ON DUPLICATE KEY (do nothing)

Negative : because the UPDATE uses resources for the second action.

Negative : MySQL will not show any errors if something goes wrong, so you cannot handle the errors. Use it only if you don’t care about the query.

How to restart a windows service using Task Scheduler

Instead of using a bat file, you can simply create a Scheduled Task. Most of the time you define just one action. In this case, create two actions with the NET command. The first one to stop the service, the second one to start the service. Give them a STOP and START argument, followed by the service name.

In this example we restart the Printer Spooler service.

NET STOP "Print Spooler" 
NET START "Print Spooler"

enter image description here

enter image description here

Note: unfortunately NET RESTART <service name> does not exist.

Show row number in row header of a DataGridView

private void ShowRowNumber(DataGridView dataGridView)
   dataGridView.RowHeadersWidth = 50;
   for (int i = 0; i < dataGridView.Rows.Count; i++)
        dataGridView.Rows[i].HeaderCell.Value = (i + 1).ToString();

How do I read a text file of about 2 GB?

I always use 010 Editor to open huge files. It can handle 2 GB easily. I was manipulating files with 50 GB with 010 Editor :-)

It's commercial now, but it has a trial version.

Parse json string using JSON.NET

I did not test the following snippet... hopefully it will point you towards the right direction:

    var jsreader = new JsonTextReader(new StringReader(stringData));
    var json = (JObject)new JsonSerializer().Deserialize(jsreader);
    var tableRows = from p in json["items"]
                 select new
                     Name = (string)p["Name"],
                     Age = (int)p["Age"],
                     Job = (string)p["Job"]

MetadataException: Unable to load the specified metadata resource

After hours of googling and trying to solve none of the solutions suggested worked. I have listed several solution here. I have also noted the one that worked for me. (I was using EF version 6.1.1, and SQL server 2014 - but an older DB)

  1. Rebuilding the project and try again.
  2. Close and open VS - I don't know how this works
  3. make sure if you have placed the .EDMX file inside a Directory, make sure you include the Directories in your ConnectionString. for example mine is inside DAL folder. SO it looks like this: connectionString="metadata=res://*/DAL.nameModel.csdl|res://*/DAL.nameModel.ssdl|res://*/DAL.nameModel.msl;(these are files. to see them you can toggle Show All Files in solution explorer, under ~/obj/.. directory)

...and many more which I had tried [like: reverting the EntityFramework version to a later version(not sure about it)]

what worked for me:

from this article here, it helped me solve my problem. I just changed my ProviderManifestToken="2012" to ProviderManifestToken="2008" in the EDMX file. To do this:

Solution Explorer

  1. Right click over file .edmx
  2. Open with..
  3. Editor XML
  4. Change ProviderManifestToken="XXXX" with 2008

I hope that helps.

how does work?

The arguments object is not actually an instance of an Array, and does not have any of the Array methods. So, arguments.slice(...) will not work because the arguments object does not have the slice method.

Arrays do have this method, and because the arguments object is very similar to an array, the two are compatible. This means that we can use array methods with the arguments object. And since array methods were built with arrays in mind, they will return arrays rather than other argument objects.

So why use Array.prototype? The Array is the object which we create new arrays from (new Array()), and these new arrays are passed methods and properties, like slice. These methods are stored in the [Class].prototype object. So, for efficiency sake, instead of accessing the slice method by (new Array()) or [], we just get it straight from the prototype. This is so we don't have to initialise a new array.

But why do we have to do this in the first place? Well, as you said, it converts an arguments object into an Array instance. The reason why we use slice, however, is more of a "hack" than anything. The slice method will take a, you guessed it, slice of an array and return that slice as a new array. Passing no arguments to it (besides the arguments object as its context) causes the slice method to take a complete chunk of the passed "array" (in this case, the arguments object) and return it as a new array.

Python: import cx_Oracle ImportError: No module named cx_Oracle error is thown

Windows help:

  1. Get the instant client from here.
  2. Put the directory into your PATH variable.
  3. Go to the command prompt (Win+R and type cmd) and set 2 variables matching your location- for example:

    set TNS_ADMIN=C:\instant_client\instantclient_11_2 set ORACLE_HOME=C:\instant_client\instantclient_11_2

Then install the cx_Oracle module from an exe. If you use pip or easy_install, ...good luck.

You can get the installer here:

How to display all elements in an arraylist?

Hi sorry the code for the second one should be:

private static void getAll(CarList c1) {

ArrayList <Car> cars = c1.getAll(); // error incompatible type
for(Car item : cars)
                       + " "
                       + item.getReg()


I have a class called CarList which contains the arraylist and its method, so in the tester class, i have basically this code to use that CarList class:

CarList c1; c1 = new CarList();

everything else works, such as adding and removing cars and displaying an inidividual car, i just need a code to display all cars in the arraylist.

How to break long string to multiple lines

If the long string to multiple lines confuses you. Then you may install mz-tools addin which is a freeware and has the utility which splits the line for you.

Download Mz-tools

If your string looks like below

SqlQueryString = "Insert into Employee values(" & txtEmployeeNo.Value & "','" & txtContractStartDate.Value & "','" & txtSeatNo.Value & "','" & txtFloor.Value & "','" & txtLeaves.Value & "')"

Simply select the string > right click on VBA IDE > Select MZ-tools > Split Lines

enter image description here

Using routes in Express-js

Seems that only index.js get loaded when you require("./routes") . I used the following code in index.js to load the rest of the routes:

var fs = require('fs')
  , path = require('path');

  var route_fname = __dirname + '/' + file;
  var route_name = path.basename(route_fname, '.js');
  if(route_name !== 'index' && route_name[0] !== "."){ 
    exports[route_name] = require(route_fname)[route_name];

FirstOrDefault: Default value other than null

I know its been a while but Ill add to this, based on the most popular answer but with a little extension Id like to share the below:

static class ExtensionsThatWillAppearOnIEnumerables
    public static T FirstOr<T>(this IEnumerable<T> source, Func<T, bool> predicate, Func<T> alternate)
        var thing = source.FirstOrDefault(predicate);
        if (thing != null)
            return thing;
        return alternate();

This allows me to call it inline as such with my own example I was having issues with:

_controlDataResolvers.FirstOr(x => x.AppliesTo(item.Key), () => newDefaultResolver()).GetDataAsync(conn, item.ToList())

So for me I just wanted a default resolver to be used inline, I can do my usual check and then pass in a function so a class isn't instantiated even if unused, its a function to execute when required instead!

Getting PEAR to work on XAMPP (Apache/MySQL stack on Windows)

AS per point 1, your PEAR path is c:\xampplite\php\pear\

However, your path is pointing to \xampplite\php\pear\PEAR

Putting the two one above the other you can clearly see one is too long:



Your include path is set to go one PEAR too deep into the pear tree. The PEAR subfolder of the pear folder includes the PEAR component. You need to adjust your include path up one level.

(you don't need the c: by the way, your path is fine as is, just too deep)

SSH -L connection successful, but localhost port forwarding not working "channel 3: open failed: connect failed: Connection refused"

Note: localhost is the hostname for an address using the local (loopback) network interface, and is its IP in the IPv4 network standard (it's ::1 in IPv6). is the IPv4 standard "current network" IP address.

I experienced this error with a Docker setup. I had a Docker container running on an external server, and I'd (correctly) mapped its ports out as By port-forwarding ssh remote -L 9232:, I'd expected to be able to communicate with the remote server's port 9232 as if it were my own local port.

It turned out that the Docker container was internally running its process on rather than, and so even though I'd specified the container's port-mappings correctly, they weren't on the correct interface for being mapped out.

How many characters can you store with 1 byte?

1 byte may hold 1 character. For Example: Refer Ascii values for each character & convert into binary. This is how it works.

enter image description here value 255 is stored as (11111111) base 2. Visit this link for knowing more about binary conversion.

Size of Tiny Int = 1 Byte ( -128 to 127)

Int = 4 Bytes (-2147483648 to 2147483647)

Hide/encrypt password in bash file to stop accidentally seeing it

OpenSSL provides a passwd command that can encrypt but doesn't decrypt as it only does hashes. You could also download something like aesutil so you can use a capable and well-known symmetric encryption routine.

For example:

# using aesutil
SALT=$(mkrand 15) # mkrand generates a 15-character random passwd
MYENCPASS="i/b9pkcpQAPy7BzH2JlqHVoJc2mNTBM=" # echo "passwd" | aes -e -b -B -p $SALT 
MYPASS=$(echo "$MYENCPASS" | aes -d -b -p $SALT)

# and usage -u admin -p $MYPASS -c shutdown

How to set default values for Angular 2 component properties?

That is interesting subject. You can play around with two lifecycle hooks to figure out how it works: ngOnChanges and ngOnInit.

Basically when you set default value to Input that's mean it will be used only in case there will be no value coming on that component. And the interesting part it will be changed before component will be initialized.

Let's say we have such components with two lifecycle hooks and one property coming from input.

  selector: 'cmp',
export class Login implements OnChanges, OnInit {
  @Input() property: string = 'default';

  ngOnChanges(changes) {

  ngOnInit() {


Situation 1

Component included in html without defined property value

As result we will see in console: Init default

That's mean onChange was not triggered. Init was triggered and property value is default as expected.

Situation 2

Component included in html with setted property <cmp [property]="'new value'"></cmp>

As result we will see in console:

Changed new value Object {}

Init new value

And this one is interesting. Firstly was triggered onChange hook, which setted property to new value, and previous value was empty object! And only after that onInit hook was triggered with new value of property.

ImportError: No module named 'encodings'

I was facing the same problem under Windows7. The error message looks like that:

Fatal Python error: Py_Initialize: unable to load the file system codec
ModuleNotFoundError: No module named 'encodings'

Current thread 0x000011f4 (most recent call first):

I have installed python 2.7(uninstalled now), and I checked "Add Python to environment variables in Advanced Options" while installing python 3.6. It comes out that the Environment Variable "PYTHONHOME" and "PYTHONPATH" is still python2.7.

Finally I solved it by modify "PYTHONHOME" to python3.6 install path and remove variable "PYTHONPATH".

JavaScript variable number of arguments to function

Yes, just like this :

function load()
  var var0 = arguments[0];
  var var1 = arguments[1];


How do you remove an invalid remote branch reference from Git?

The accepted answer didn't work for me when the ref was packed. This does however:

$ git remote add public
$ git remote rm public

List files recursively in Linux CLI with path relative to the current directory

Use find:

find . -name \*.txt -print

On systems that use GNU find, like most GNU/Linux distributions, you can leave out the -print.

Is there a Java equivalent or methodology for the typedef keyword in C++?

You could use an Enum, although that's semantically a bit different than a typedef in that it only allows a restricted set of values. Another possible solution is a named wrapper class, e.g.

public class Apple {
      public Apple(Integer i){this.i=i; }

but that seems way more clunky, especially given that it's not clear from the code that the class has no other function than as an alias.

How do I split a string by a multi-character delimiter in C#?

...In short:

string[] arr = "This is a sentence".Split(new string[] { "is" }, StringSplitOptions.None);

Find which version of package is installed with pip

The python function returning just the package version in a machine-readable format:

from importlib.metadata import version 

Prior to python 3.8:

pip install importlib-metadata 
from importlib_metadata import version

The bash equivalent (here also invoked from python) would be much more complex (but more robust - see caution below):

import subprocess
def get_installed_ver(pkg_name):
    bash_str="pip freeze | grep -w %s= | awk -F '==' {'print $2'} | tr -d '\n'" %(pkg_name)
    return(subprocess.check_output(bash_str, shell=True).decode())

Sample usage:

# pkg_name="xgboost"
# pkg_name="Flask"
# pkg_name="Flask-Caching"

>>> 0.22

Note that in both cases pkg_name parameter should contain package name in the format as returned by pip freeze and not as used during import, e.g. scikit-learn not sklearn or Flask-Caching, not flask_caching.

Note that while invoking pip freeze in bash version may seem inefficient, only this method proves to be sufficiently robust to package naming peculiarities and inconsistencies (e.g. underscores vs dashes, small vs large caps, and abbreviations such as sklearn vs scikit-learn).

Caution: in complex environments both variants can return surprise version numbers, inconsistent with what you can actually get during import.

One such problem arises when there are other versions of the package hidden in a user site-packages subfolder. As an illustration of the perils of using version() here's a situation I encountered:

$ pip freeze | grep lightgbm


$ python -c "import lightgbm; print(lightgbm.__version__)"


$ python -c "from importlib_metadata import version; print(version(\"lightgbm\"))"

until you delete the subfolder with the old version (here 2.2.3) from the user folder (only one would normally be preserved by `pip` - the one installed as last with the `--user` switch):

$ ls /home/jovyan/.local/lib/python3.7/site-packages/lightgbm*

Another problem is having some conda-installed packages in the same environment. If they share dependencies with your pip-installed packages, and versions of these dependencies differ, you may get downgrades of your pip-installed dependencies.

To illustrate, the latest version of numpy available in PyPI on 04-01-2020 was 1.18.0, while at the same time Anaconda's conda-forge channel had only 1.17.3 version on numpy as their latest. So when you installed a basemap package with conda (as second), your previously pip-installed numpy would get downgraded by conda to 1.17.3, and version 1.18.0 would become unavailable to the import function. In this case version() would be right, and pip freeze/conda list wrong:

$ python -c "from importlib_metadata import version; print(version(\"numpy\"))"

$ python -c "import numpy; print(numpy.__version__)"

$ pip freeze | grep numpy

$ conda list | grep numpy
numpy                     1.18.0                   pypi_0    pypi

Remove multiple objects with rm()

Or using regular expressions

"rmlike" <- function(...) {
  names <- sapply( = FALSE)$..., as.character)
  names = paste(names,collapse="|")
  Vars <- ls(1)
  r <- Vars[grep(paste("^(",names,").*",sep=""),Vars)]


Column "invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause"

You can use case in update and SWAP as many as you want

update Table SET column=(case when is_row_1 then value_2 else value_1 end) where rule_to_match_swap_columns

How do I jump out of a foreach loop in C#?

Use break; and this will exit the foreach loop

How to perform a for loop on each character in a string in Bash?

${#var} returns the length of var

${var:pos:N} returns N characters from pos onwards


$ words="abc"
$ echo ${words:0:1}
$ echo ${words:1:1}
$ echo ${words:2:1}

so it is easy to iterate.

another way:

$ grep -o . <<< "abc"


$ grep -o . <<< "abc" | while read letter;  do echo "my letter is $letter" ; done 

my letter is a
my letter is b
my letter is c

How do you update Xcode on OSX to the latest version?

  1. Open up App Store

    enter image description here

  2. Look in the top right for the updates section (may also be in lefthand column "Updates"..)

    enter image description here

  3. Find Xcode & click Update enter image description here

Dynamic Web Module 3.0 -- 3.1

  1. Go to Workspace location
  2. select your project folder
  3. .setting folder
  4. edit "org.eclipse.wst.common.project.facet.core"
  5. change installed facet="jst.web" version="3.0"

How to debug (only) JavaScript in Visual Studio?

It is possible to debug by writing key word "debugger" to place where you want to debug and just press F5 key to debug JavaScript code.

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

In Python 3, the behaviour changes.

>>> import my_stuff

... do something with my_stuff, then later:

>>>> import imp
>>>> imp.reload(my_stuff)

and you get a brand new, reloaded my_stuff.

How do I create an executable in Visual Studio 2013 w/ C++?

  1. Click BUILD > Configuration Manager...
  2. Under Project contexts > Configuration, select "Release"
  3. BUILD > Build Solution or Rebuild Solution

Send a SMS via intent

This is another solution using SMSManager:

SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage("PhoneNumber-example:+989147375410", null, "SMS Message Body", null, null);

Set Text property of asp:label in Javascript PROPER way

The label's information is stored in the ViewState input on postback (keep in mind the server knows nothing of the page outside of the form values posted back, which includes your label's text).. you would have to somehow update that on the client side to know what changed in that label, which I'm guessing would not be worth your time.

I'm not entirely sure what problem you're trying to solve here, but this might give you a few ideas of how to go about it:

You could create a hidden field to go along with your label, and anytime you update your label, you'd update that value as well.. then in the code behind set the Text property of the label to be what was in that hidden field.

Bind failed: Address already in use

It also happens when you have not give enough permissions(read and write) to your sock file!

Just add expected permission to your sock contained folder and your sock file:

 chmod ug+rw /path/to/your/
 chmod ug+rw /path/to/your/file.sock

Then have fun!

How to indent a few lines in Markdown markup?

This is an old thread, but I would have thought markdown's blockquotes ('> ') would be best for this:

CSS Font "Helvetica Neue"

You can use to encode any font for websites. It'll generate the code to include the font.

I don't really use it for fonts over 30px. They look much better as an image (because images are anti-aliased, and some browsers don't anti-alias fonts in the browser).


Hope that helps...

How do I clear this setInterval inside a function?


How to Store Historical Data

Just wanted to add an option that I started using because I use Azure SQL and the multiple table thing was way too cumbersome for me. I added an insert/update/delete trigger on my table and then converted the before/after change to json using the "FOR JSON AUTO" feature.


That returns a JSON representation fo the record before/after the change. I then store those values in a history table with a timestamp of when the change occurred (I also store the ID for current record of concern). Using the serialization process, I can control how data is backfilled in the case of changes to schema.

I learned about this from this link here