Programs & Examples On #Jexcelapi

Java Excel API(jexcelapi) - A Java API to read, write, and modify Excel spreadsheets

Create Excel file in Java

//Find jar from here "http://poi.apache.org/download.html"
import  java.io.*;
import  org.apache.poi.hssf.usermodel.HSSFSheet;
import  org.apache.poi.hssf.usermodel.HSSFWorkbook;
import  org.apache.poi.hssf.usermodel.HSSFRow;

public class CreateExlFile{
    public static void main(String[]args) {
        try {
            String filename = "C:/NewExcelFile.xls" ;
            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet sheet = workbook.createSheet("FirstSheet");  

            HSSFRow rowhead = sheet.createRow((short)0);
            rowhead.createCell(0).setCellValue("No.");
            rowhead.createCell(1).setCellValue("Name");
            rowhead.createCell(2).setCellValue("Address");
            rowhead.createCell(3).setCellValue("Email");

            HSSFRow row = sheet.createRow((short)1);
            row.createCell(0).setCellValue("1");
            row.createCell(1).setCellValue("Sankumarsingh");
            row.createCell(2).setCellValue("India");
            row.createCell(3).setCellValue("[email protected]");

            FileOutputStream fileOut = new FileOutputStream(filename);
            workbook.write(fileOut);
            fileOut.close();
            workbook.close();
            System.out.println("Your excel file has been generated!");

        } catch ( Exception ex ) {
            System.out.println(ex);
        }
    }
}

jquery: get id from class selector

Use "attr" method in jquery.

$('.test').click(function(){
    var id = $(this).attr('id');
});

Android Preventing Double Click On A Button

Try this, it is working:

mButton.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {

                mSlotLayout.setEnabled(false);

        //      do your work here

                Timer buttonTimer = new Timer();
                buttonTimer.schedule(new TimerTask() {

                    @Override
                    public void run() {

                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                mButton.setEnabled(true);
                            }
                        });
                    }
                }, 500); // delay button enable for 0.5 sec
    }
});

Determine Whether Integer Is Between Two Other Integers?

Your operator is incorrect. Should be if number >= 10000 and number <= 30000:. Additionally, Python has a shorthand for this sort of thing, if 10000 <= number <= 30000:.

How to access component methods from “outside” in ReactJS?

If you want to call functions on components from outside React, you can call them on the return value of renderComponent:

var Child = React.createClass({…});
var myChild = React.renderComponent(Child);
myChild.someMethod();

The only way to get a handle to a React Component instance outside of React is by storing the return value of React.renderComponent. Source.

"Sub or Function not defined" when trying to run a VBA script in Outlook

I need to add that, if the Module name and the sub name is the same you have such issue. Consider change the Module name to mod_Test instead of "Test" which is the same as the sub.

failed to resolve com.android.support:appcompat-v7:22 and com.android.support:recyclerview-v7:21.1.2

Real path for Support Repository Libraries:

enter image description here

  1. You should download Support Repository Libraries.

If the problem still exists:

  1. Go to the real path of your Support Repository Libraries and check that the following folder exists:

    "ANDROID_SDK_DIRECTORY\extras\android\m2repository\com\android\support" 
    

    In that folder there are support libraries that can't be found. for example:

    "ANDROID_SDK_DIRECTORY\extras\android\m2repository\com\android\support\appcompat-v7"
    
  2. Open folder appcompat-v7 and you see folders with all available version. You should use only one of these versions in the build.gradle file dependencies or use +, for ex. 18.0.+

    dependencies {
        compile fileTree(dir: 'libs', include: ['*.jar'])
        compile 'com.android.support:appcompat-v7:18.0.+'
        compile 'com.android.support:gridlayout-v7:23.1.1'
        compile 'com.android.support:support-v4:23.1.1'
    }
    

That is the path taken from grade.build dependencies file:

com.android.support:appcompat-v7:18.0.0

Refer to the real path on your HDD -->

ANDROID_SDK_DIRECTORY\extras\android\m2repository\com\android\support\appcompat-v7\18.0.0

If there is no such folder, you will receive the error:

"failed to resolve com.android.support:appcompat-v7:18.0.0"  

p.s. If you have Windows x64, when installing sdk and jdk, make sure that the installation path does not have Program Files(86). Brackets that add Windows may cause additional problems with resolving paths for your project. Use simple paths for your installation folder.

For example:

c:\androidSDK\

Preloading images with jQuery

Quick and easy:

function preload(arrayOfImages) {
    $(arrayOfImages).each(function(){
        $('<img/>')[0].src = this;
        // Alternatively you could use:
        // (new Image()).src = this;
    });
}

// Usage:

preload([
    'img/imageName.jpg',
    'img/anotherOne.jpg',
    'img/blahblahblah.jpg'
]);

Or, if you want a jQuery plugin:

$.fn.preload = function() {
    this.each(function(){
        $('<img/>')[0].src = this;
    });
}

// Usage:

$(['img1.jpg','img2.jpg','img3.jpg']).preload();

Max retries exceeded with URL in requests

I had the same error when I run the route in the browser, but in postman, it works fine. It issue with mine was that, there was no / after the route before the query string.

127.0.0.1:5000/api/v1/search/?location=Madina raise the error and removing / after the search worked for me.

How do you normalize a file path in Bash?

Based on loveborg's excellent python snippet, I wrote this:

#!/bin/sh

# Version of readlink that follows links to the end; good for Mac OS X

for file in "$@"; do
  while [ -h "$file" ]; do
    l=`readlink $file`
    case "$l" in
      /*) file="$l";;
      *) file=`dirname "$file"`/"$l"
    esac
  done
  #echo $file
  python -c "import os,sys; print os.path.abspath(sys.argv[1])" "$file"
done

How to identify numpy types in python?

Note that the type(numpy.ndarray) is a type itself and watch out for boolean and scalar types. Don't be too discouraged if it's not intuitive or easy, it's a pain at first.

See also: - https://docs.scipy.org/doc/numpy-1.15.1/reference/arrays.dtypes.html - https://github.com/machinalis/mypy-data/tree/master/numpy-mypy

>>> import numpy as np
>>> np.ndarray
<class 'numpy.ndarray'>
>>> type(np.ndarray)
<class 'type'>
>>> a = np.linspace(1,25)
>>> type(a)
<class 'numpy.ndarray'>
>>> type(a) == type(np.ndarray)
False
>>> type(a) == np.ndarray
True
>>> isinstance(a, np.ndarray)
True

Fun with booleans:

>>> b = a.astype('int32') == 11
>>> b[0]
False
>>> isinstance(b[0], bool)
False
>>> isinstance(b[0], np.bool)
False
>>> isinstance(b[0], np.bool_)
True
>>> isinstance(b[0], np.bool8)
True
>>> b[0].dtype == np.bool
True
>>> b[0].dtype == bool  # python equivalent
True

More fun with scalar types, see: - https://docs.scipy.org/doc/numpy-1.15.1/reference/arrays.scalars.html#arrays-scalars-built-in

>>> x = np.array([1,], dtype=np.uint64)
>>> x[0].dtype
dtype('uint64')
>>> isinstance(x[0], np.uint64)
True
>>> isinstance(x[0], np.integer)
True  # generic integer
>>> isinstance(x[0], int)
False  # but not a python int in this case

# Try matching the `kind` strings, e.g.
>>> np.dtype('bool').kind                                                                                           
'b'
>>> np.dtype('int64').kind                                                                                          
'i'
>>> np.dtype('float').kind                                                                                          
'f'
>>> np.dtype('half').kind                                                                                           
'f'

# But be weary of matching dtypes
>>> np.integer
<class 'numpy.integer'>
>>> np.dtype(np.integer)
dtype('int64')
>>> x[0].dtype == np.dtype(np.integer)
False

# Down these paths there be dragons:

# the .dtype attribute returns a kind of dtype, not a specific dtype
>>> isinstance(x[0].dtype, np.dtype)
True
>>> isinstance(x[0].dtype, np.uint64)
False  
>>> isinstance(x[0].dtype, np.dtype(np.uint64))
Traceback (most recent call last):
  File "<console>", line 1, in <module>
TypeError: isinstance() arg 2 must be a type or tuple of types
# yea, don't go there
>>> isinstance(x[0].dtype, np.int_)
False  # again, confusing the .dtype with a specific dtype


# Inequalities can be tricky, although they might
# work sometimes, try to avoid these idioms:

>>> x[0].dtype <= np.dtype(np.uint64)
True
>>> x[0].dtype <= np.dtype(np.float)
True
>>> x[0].dtype <= np.dtype(np.half)
False  # just when things were going well
>>> x[0].dtype <= np.dtype(np.float16)
False  # oh boy
>>> x[0].dtype == np.int
False  # ya, no luck here either
>>> x[0].dtype == np.int_
False  # or here
>>> x[0].dtype == np.uint64
True  # have to end on a good note!

How to "properly" create a custom object in JavaScript?

There are two models for implementing classes and instances in JavaScript: the prototyping way, and the closure way. Both have advantages and drawbacks, and there are plenty of extended variations. Many programmers and libraries have different approaches and class-handling utility functions to paper over some of the uglier parts of the language.

The result is that in mixed company you will have a mishmash of metaclasses, all behaving slightly differently. What's worse, most JavaScript tutorial material is terrible and serves up some kind of in-between compromise to cover all bases, leaving you very confused. (Probably the author is also confused. JavaScript's object model is very different to most programming languages, and in many places straight-up badly designed.)

Let's start with the prototype way. This is the most JavaScript-native you can get: there is a minimum of overhead code and instanceof will work with instances of this kind of object.

function Shape(x, y) {
    this.x= x;
    this.y= y;
}

We can add methods to the instance created by new Shape by writing them to the prototype lookup of this constructor function:

Shape.prototype.toString= function() {
    return 'Shape at '+this.x+', '+this.y;
};

Now to subclass it, in as much as you can call what JavaScript does subclassing. We do that by completely replacing that weird magic prototype property:

function Circle(x, y, r) {
    Shape.call(this, x, y); // invoke the base class's constructor function to take co-ords
    this.r= r;
}
Circle.prototype= new Shape();

before adding methods to it:

Circle.prototype.toString= function() {
    return 'Circular '+Shape.prototype.toString.call(this)+' with radius '+this.r;
}

This example will work and you will see code like it in many tutorials. But man, that new Shape() is ugly: we're instantiating the base class even though no actual Shape is to be created. It happens to work in this simple case because JavaScript is so sloppy: it allows zero arguments to be passed in, in which case x and y become undefined and are assigned to the prototype's this.x and this.y. If the constructor function were doing anything more complicated, it would fall flat on its face.

So what we need to do is find a way to create a prototype object which contains the methods and other members we want at a class level, without calling the base class's constructor function. To do this we are going to have to start writing helper code. This is the simplest approach I know of:

function subclassOf(base) {
    _subclassOf.prototype= base.prototype;
    return new _subclassOf();
}
function _subclassOf() {};

This transfers the base class's members in its prototype to a new constructor function which does nothing, then uses that constructor. Now we can write simply:

function Circle(x, y, r) {
    Shape.call(this, x, y);
    this.r= r;
}
Circle.prototype= subclassOf(Shape);

instead of the new Shape() wrongness. We now have an acceptable set of primitives to built classes.

There are a few refinements and extensions we can consider under this model. For example here is a syntactical-sugar version:

Function.prototype.subclass= function(base) {
    var c= Function.prototype.subclass.nonconstructor;
    c.prototype= base.prototype;
    this.prototype= new c();
};
Function.prototype.subclass.nonconstructor= function() {};

...

function Circle(x, y, r) {
    Shape.call(this, x, y);
    this.r= r;
}
Circle.subclass(Shape);

Either version has the drawback that the constructor function cannot be inherited, as it is in many languages. So even if your subclass adds nothing to the construction process, it must remember to call the base constructor with whatever arguments the base wanted. This can be slightly automated using apply, but still you have to write out:

function Point() {
    Shape.apply(this, arguments);
}
Point.subclass(Shape);

So a common extension is to break out the initialisation stuff into its own function rather than the constructor itself. This function can then inherit from the base just fine:

function Shape() { this._init.apply(this, arguments); }
Shape.prototype._init= function(x, y) {
    this.x= x;
    this.y= y;
};

function Point() { this._init.apply(this, arguments); }
Point.subclass(Shape);
// no need to write new initialiser for Point!

Now we've just got the same constructor function boilerplate for each class. Maybe we can move that out into its own helper function so we don't have to keep typing it, for example instead of Function.prototype.subclass, turning it round and letting the base class's Function spit out subclasses:

Function.prototype.makeSubclass= function() {
    function Class() {
        if ('_init' in this)
            this._init.apply(this, arguments);
    }
    Function.prototype.makeSubclass.nonconstructor.prototype= this.prototype;
    Class.prototype= new Function.prototype.makeSubclass.nonconstructor();
    return Class;
};
Function.prototype.makeSubclass.nonconstructor= function() {};

...

Shape= Object.makeSubclass();
Shape.prototype._init= function(x, y) {
    this.x= x;
    this.y= y;
};

Point= Shape.makeSubclass();

Circle= Shape.makeSubclass();
Circle.prototype._init= function(x, y, r) {
    Shape.prototype._init.call(this, x, y);
    this.r= r;
};

...which is starting to look a bit more like other languages, albeit with slightly clumsier syntax. You can sprinkle in a few extra features if you like. Maybe you want makeSubclass to take and remember a class name and provide a default toString using it. Maybe you want to make the constructor detect when it has accidentally been called without the new operator (which would otherwise often result in very annoying debugging):

Function.prototype.makeSubclass= function() {
    function Class() {
        if (!(this instanceof Class))
            throw('Constructor called without "new"');
        ...

Maybe you want to pass in all the new members and have makeSubclass add them to the prototype, to save you having to write Class.prototype... quite so much. A lot of class systems do that, eg:

Circle= Shape.makeSubclass({
    _init: function(x, y, z) {
        Shape.prototype._init.call(this, x, y);
        this.r= r;
    },
    ...
});

There are a lot of potential features you might consider desirable in an object system and no-one really agrees on one particular formula.


The closure way, then. This avoids the problems of JavaScript's prototype-based inheritance, by not using inheritance at all. Instead:

function Shape(x, y) {
    var that= this;

    this.x= x;
    this.y= y;

    this.toString= function() {
        return 'Shape at '+that.x+', '+that.y;
    };
}

function Circle(x, y, r) {
    var that= this;

    Shape.call(this, x, y);
    this.r= r;

    var _baseToString= this.toString;
    this.toString= function() {
        return 'Circular '+_baseToString(that)+' with radius '+that.r;
    };
};

var mycircle= new Circle();

Now every single instance of Shape will have its own copy of the toString method (and any other methods or other class members we add).

The bad thing about every instance having its own copy of each class member is that it's less efficient. If you are dealing with large numbers of subclassed instances, prototypical inheritance may serve you better. Also calling a method of the base class is slightly annoying as you can see: we have to remember what the method was before the subclass constructor overwrote it, or it gets lost.

[Also because there is no inheritance here, the instanceof operator won't work; you would have to provide your own mechanism for class-sniffing if you need it. Whilst you could fiddle the prototype objects in a similar way as with prototype inheritance, it's a bit tricky and not really worth it just to get instanceof working.]

The good thing about every instance having its own method is that the method may then be bound to the specific instance that owns it. This is useful because of JavaScript's weird way of binding this in method calls, which has the upshot that if you detach a method from its owner:

var ts= mycircle.toString;
alert(ts());

then this inside the method won't be the Circle instance as expected (it'll actually be the global window object, causing widespread debugging woe). In reality this typically happens when a method is taken and assigned to a setTimeout, onclick or EventListener in general.

With the prototype way, you have to include a closure for every such assignment:

setTimeout(function() {
    mycircle.move(1, 1);
}, 1000);

or, in the future (or now if you hack Function.prototype) you can also do it with function.bind():

setTimeout(mycircle.move.bind(mycircle, 1, 1), 1000);

if your instances are done the closure way, the binding is done for free by the closure over the instance variable (usually called that or self, though personally I would advise against the latter as self already has another, different meaning in JavaScript). You don't get the arguments 1, 1 in the above snippet for free though, so you would still need another closure or a bind() if you need to do that.

There are lots of variants on the closure method too. You may prefer to omit this completely, creating a new that and returning it instead of using the new operator:

function Shape(x, y) {
    var that= {};

    that.x= x;
    that.y= y;

    that.toString= function() {
        return 'Shape at '+that.x+', '+that.y;
    };

    return that;
}

function Circle(x, y, r) {
    var that= Shape(x, y);

    that.r= r;

    var _baseToString= that.toString;
    that.toString= function() {
        return 'Circular '+_baseToString(that)+' with radius '+r;
    };

    return that;
};

var mycircle= Circle(); // you can include `new` if you want but it won't do anything

Which way is “proper”? Both. Which is “best”? That depends on your situation. FWIW I tend towards prototyping for real JavaScript inheritance when I'm doing strongly OO stuff, and closures for simple throwaway page effects.

But both ways are quite counter-intuitive to most programmers. Both have many potential messy variations. You will meet both (as well as many in-between and generally broken schemes) if you use other people's code/libraries. There is no one generally-accepted answer. Welcome to the wonderful world of JavaScript objects.

[This has been part 94 of Why JavaScript Is Not My Favourite Programming Language.]

Wait until ActiveWorkbook.RefreshAll finishes - VBA

You must turn off "background refresh" for all queries. If background refresh is on, Excel works ahead while the refresh occurs and you have problems.

Data > Connections > Properties > (uncheck) enable background refresh

How to loop through a collection that supports IEnumerable?

or even a very classic old fashion method

IEnumerable<string> collection = new List<string>() { "a", "b", "c" };

for(int i = 0; i < collection.Count(); i++) 
{
    string str1 = collection.ElementAt(i);
    // do your stuff   
}

maybe you would like this method also :-)

Shorthand for if-else statement

?: Operator

If you want to shorten If/Else you can use ?: operator as:

condition ? action-on-true : action-on-false(else)

For instance:

let gender = isMale ? 'Male' : 'Female';

In this case else part is mandatory.

&& Operator

In another case, if you have only if condition you can use && operator as:

condition && action;

For instance:

!this.settings && (this.settings = new TableSettings());

FYI: You have to try to avoid using if-else or at least decrease using it and try to replace it with Polymorphism or Inheritance. Go for being Anti-If guy.

Optimistic vs. Pessimistic locking

There are basically two most popular answers. The first one basically says

Optimistic needs a three-tier architectures where you do not necessarily maintain a connection to the database for your session whereas Pessimistic Locking is when you lock the record for your exclusive use until you have finished with it. It has much better integrity than optimistic locking you need either a direct connection to the database.

Another answer is

optimistic (versioning) is faster because of no locking but (pessimistic) locking performs better when contention is high and it is better to prevent the work rather than discard it and start over.

or

Optimistic locking works best when you have rare collisions

As it is put on this page.

I created my answer to explain how "keep connection" is related to "low collisions".

To understand which strategy is best for you, think not about the Transactions Per Second your DB has but the duration of a single transaction. Normally, you open trasnaction, performa operation and close the transaction. This is a short, classical transaction ANSI had in mind and fine to get away with locking. But, how do you implement a ticket reservation system where many clients reserve the same rooms/seats at the same time?

You browse the offers, fill in the form with lots of available options and current prices. It takes a lot of time and options can become obsolete, all the prices invalid between you started to fill the form and press "I agree" button because there was no lock on the data you have accessed and somebody else, more agile, has intefered changing all the prices and you need to restart with new prices.

You could lock all the options as you read them, instead. This is pessimistic scenario. You see why it sucks. Your system can be brought down by a single clown who simply starts a reservation and goes smoking. Nobody can reserve anything before he finishes. Your cash flow drops to zero. That is why, optimistic reservations are used in reality. Those who dawdle too long have to restart their reservation at higher prices.

In this optimistic approach you have to record all the data that you read (as in mine Repeated Read) and come to the commit point with your version of data (I want to buy shares at the price you displayed in this quote, not current price). At this point, ANSI transaction is created, which locks the DB, checks if nothing is changed and commits/aborts your operation. IMO, this is effective emulation of MVCC, which is also associated with Optimistic CC and also assumes that your transaction restarts in case of abort, that is you will make a new reservation. A transaction here involves a human user decisions.

I am far from understanding how to implement the MVCC manually but I think that long-running transactions with option of restart is the key to understanding the subject. Correct me if I am wrong anywhere. My answer was motivated by this Alex Kuznecov chapter.

WCF Service, the type provided as the service attribute values…could not be found

Faced this exact issue. The problem resolved when i changed the Service="Namespace.ServiceName" tag in the Markup (right click xxxx.svc and select View Markup in visual studio) to match the namespace i used for my xxxx.svc.cs file

Override devise registrations controller

Very simple methods Just go to the terminal and the type following

rails g devise:controllers users //This will create devise controllers in controllers/users folder

Next to use custom views

rails g devise:views users //This will create devise views in views/users folder

now in your route.rb file

devise_for :users, controllers: {
           :sessions => "users/sessions",
           :registrations => "users/registrations" }

You can add other controllers too. This will make devise to use controllers in users folder and views in users folder.

Now you can customize your views as your desire and add your logic to controllers in controllers/users folder. Enjoy !

Git pull till a particular commit

git pull is nothing but git fetch followed by git merge. So what you can do is

git fetch remote example_branch

git merge <commit_hash>

How does functools partial do what it does?

This answer is more of an example code. All the above answers give good explanations regarding why one should use partial. I will give my observations and use cases about partial.

from functools import partial
 def adder(a,b,c):
    print('a:{},b:{},c:{}'.format(a,b,c))
    ans = a+b+c
    print(ans)
partial_adder = partial(adder,1,2)
partial_adder(3)  ## now partial_adder is a callable that can take only one argument

Output of the above code should be:

a:1,b:2,c:3
6

Notice that in the above example a new callable was returned that will take parameter (c) as it's argument. Note that it is also the last argument to the function.

args = [1,2]
partial_adder = partial(adder,*args)
partial_adder(3)

Output of the above code is also:

a:1,b:2,c:3
6

Notice that * was used to unpack the non-keyword arguments and the callable returned in terms of which argument it can take is same as above.

Another observation is: Below example demonstrates that partial returns a callable which will take the undeclared parameter (a) as an argument.

def adder(a,b=1,c=2,d=3,e=4):
    print('a:{},b:{},c:{},d:{},e:{}'.format(a,b,c,d,e))
    ans = a+b+c+d+e
    print(ans)
partial_adder = partial(adder,b=10,c=2)
partial_adder(20)

Output of the above code should be:

a:20,b:10,c:2,d:3,e:4
39

Similarly,

kwargs = {'b':10,'c':2}
partial_adder = partial(adder,**kwargs)
partial_adder(20)

Above code prints

a:20,b:10,c:2,d:3,e:4
39

I had to use it when I was using Pool.map_async method from multiprocessing module. You can pass only one argument to the worker function so I had to use partial to make my worker function look like a callable with only one input argument but in reality my worker function had multiple input arguments.

Filter dataframe rows if value in column is in a set list of values

isin() is ideal if you have a list of exact matches, but if you have a list of partial matches or substrings to look for, you can filter using the str.contains method and regular expressions.

For example, if we want to return a DataFrame where all of the stock IDs which begin with '600' and then are followed by any three digits:

>>> rpt[rpt['STK_ID'].str.contains(r'^600[0-9]{3}$')] # ^ means start of string
...   STK_ID   ...                                    # [0-9]{3} means any three digits
...  '600809'  ...                                    # $ means end of string
...  '600141'  ...
...  '600329'  ...
...      ...   ...

Suppose now we have a list of strings which we want the values in 'STK_ID' to end with, e.g.

endstrings = ['01$', '02$', '05$']

We can join these strings with the regex 'or' character | and pass the string to str.contains to filter the DataFrame:

>>> rpt[rpt['STK_ID'].str.contains('|'.join(endstrings)]
...   STK_ID   ...
...  '155905'  ...
...  '633101'  ...
...  '210302'  ...
...      ...   ...

Finally, contains can ignore case (by setting case=False), allowing you to be more general when specifying the strings you want to match.

For example,

str.contains('pandas', case=False)

would match PANDAS, PanDAs, paNdAs123, and so on.

Equivalent of jQuery .hide() to set visibility: hidden

If you only need the standard functionality of hide only with visibility:hidden to keep the current layout you can use the callback function of hide to alter the css in the tag. Hide docs in jquery

An example :

$('#subs_selection_box').fadeOut('slow', function() {
      $(this).css({"visibility":"hidden"});
      $(this).css({"display":"block"});
});

This will use the normal cool animation to hide the div, but after the animation finish you set the visibility to hidden and display to block.

An example : http://jsfiddle.net/bTkKG/1/

I know you didnt want the $("#aa").css() solution, but you did not specify if it was because using only the css() method you lose the animation.

Password must have at least one non-alpha character

  function randomPassword(length) {
        var chars = "abcdefghijklmnopqrstuvwxyz#$%ABCDEFGHIJKLMNOP1234567890";
        var pass = "";
        for (var x = 0; x < length; x++) {
            var i = Math.floor(Math.random() * chars.length);
            pass += chars.charAt(i);
        }
        var pattern = false;
        var passwordpattern = new RegExp("[^a-zA-Z0-9+]+[0-9+]+[A-Z+]+[a-z+]");
        pattern = passwordpattern.test(pass);
        if (pattern == true)
            { alert(pass); }
        else
         { randomPassword(length); }
    }

try this to create the random password with atleast one special character

tmux set -g mouse-mode on doesn't work

Try this. It works on my computer.

set -g mouse on

SSRS Expression for IF, THEN ELSE

You should be able to use

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

http://msdn.microsoft.com/en-us/library/ms157328.aspx

Modifying location.hash without page scrolling

Use history.replaceState or history.pushState* to change the hash. This will not trigger the jump to the associated element.

Example

$(document).on('click', 'a[href^=#]', function(event) {
  event.preventDefault();
  history.pushState({}, '', this.href);
});

Demo on JSFiddle

* If you want history forward and backward support

History behaviour

If you are using history.pushState and you don't want page scrolling when the user uses the history buttons of the browser (forward/backward) check out the experimental scrollRestoration setting (Chrome 46+ only).

history.scrollRestoration = 'manual';

Browser Support

Convert Mercurial project to Git

You can try using fast-export:

cd ~
git clone https://github.com/frej/fast-export.git
git init git_repo
cd git_repo
~/fast-export/hg-fast-export.sh -r /path/to/old/mercurial_repo
git checkout HEAD

Also have a look at this SO question.


If you're using Mercurial version below 4.6, adrihanu got your back:

As he stated in his comment: "In case you use Mercurial < 4.6 and you got "revsymbol not found" error. You need to update your Mercurial or downgrade fast-export by running git checkout tags/v180317 inside ~/fast-export directory.".

Use Toast inside Fragment

As stated by alfo888_ibg:

@Override
public void onClick(View arg0) {
   Toast.makeText(activity,"Text!",Toast.LENGTH_SHORT).show();
}

Just do:

    Toast.makeText(getActivity(),"Text!",Toast.LENGTH_SHORT).show();

this worked for me.

How to get current url in view in asp.net core 1.0

There is a clean way to get the current URL from a Razor page or PageModel class. That is:

Url.PageLink()

Please note that I meant, the "ASP.NET Core Razor Pages", not the MVC.

I use this method when I want to print the canonical URL meta tag in the ASP.NET Core razor pages. But there is a catch. It will give you the URL which is supposed to be the right URL for that page. Let me explain.

Say, you have defined a route named "id" for your page and therefore, your URL should look like

http://example.com/product?id=34

The Url.PageLink() will give you exactly that URL as shown above.

Now, if the user adds anything extra on that URL, say,

http://example.com/product?id=34&somethingElse

Then, you will not get that "somethingElse" from this method. And that is why it is exactly good for printing canonical URL meta tag in the HTML page.

Why am I getting an Exception with the message "Invalid setup on a non-virtual (overridable in VB) member..."?

Moq cannot mock non-virtual methods and sealed classes. While running a test using mock object, MOQ actually creates an in-memory proxy type which inherits from your "XmlCupboardAccess" and overrides the behaviors that you have set up in the "SetUp" method. And as you know in C#, you can override something only if it is marked as virtual which isn't the case with Java. Java assumes every non-static method to be virtual by default.

Another thing I believe you should consider is introducing an interface for your "CupboardAccess" and start mocking the interface instead. It would help you decouple your code and have benefits in the longer run.

Lastly, there are frameworks like : TypeMock and JustMock which work directly with the IL and hence can mock non-virtual methods. Both however, are commercial products.

Document directory path of Xcode Device Simulator

It is correct that we need to look into the path ~/Library/Developer/CoreSimulator/Devices/.

But the issue I am seeing is that the path keeps changing every time I run the app. The path contains another set of long IDs after the Application string and that keeps changing every time I run the app. This basically means that my app will not have any cached data when it runs the next time.

CSS background image alt attribute

The general belief is that you shouldn't be using background images for things with meaningful semantic value so there isn't really a proper way to store alt data with those images. The important question is what are you going to be doing with that alt data? Do you want it to display if the images don't load? Do you need it for some programmatic function on the page? You could store the data arbitrarily using made up css properties that have no meaning (might cause errors?) OR by adding in hidden images that have the image and the alt tag, and then when you need a background images alt you can compare the image paths and then handle the data however you want using some custom script to simulate what you need. There's no way I know of to make the browser automatically handle some sort of alt attribute for background images though.

Angular - res.json() is not a function

HttpClient.get() applies res.json() automatically and returns Observable<HttpResponse<string>>. You no longer need to call this function yourself.

See Difference between HTTP and HTTPClient in angular 4?

How can I build multiple submit buttons django form?

You can also do like this,

 <form method='POST'>
    {{form1.as_p}}
    <button type="submit" name="btnform1">Save Changes</button>
    </form>
    <form method='POST'>
    {{form2.as_p}}
    <button type="submit" name="btnform2">Save Changes</button>
    </form>

CODE

if request.method=='POST' and 'btnform1' in request.POST:
    do something...
if request.method=='POST' and 'btnform2' in request.POST:
    do something...

Select a Column in SQL not in Group By

What you are asking, Sir, is as the answer of RedFilter. This answer as well helps in understanding why group by is somehow a simpler version or partition over: SQL Server: Difference between PARTITION BY and GROUP BY since it changes the way the returned value is calculated and therefore you could (somehow) return columns group by can not return.

How to get first N number of elements from an array

I believe what you're looking for is:

// ...inside the render() function

var size = 3;
var items = list.slice(0, size).map(i => {
    return <myview item={i} key={i.id} />
}

return (
  <div>
    {items}
  </div>   
)

What's an Aggregate Root?

Aggregate means collection of something.
root is like top node of tree, from where we can access everything like <html> node in web page document.
Blog Analogy, A user can have many posts and each post can have many comments. so if we fetch any user then it can act as root to access all the related posts and further comments of those posts. These are all together said to be collection or Aggregated

Tkinter example code for multiple windows, why won't buttons load correctly?

I rewrote your code in a more organized, better-practiced way:

import tkinter as tk

class Demo1:
    def __init__(self, master):
        self.master = master
        self.frame = tk.Frame(self.master)
        self.button1 = tk.Button(self.frame, text = 'New Window', width = 25, command = self.new_window)
        self.button1.pack()
        self.frame.pack()

    def new_window(self):
        self.newWindow = tk.Toplevel(self.master)
        self.app = Demo2(self.newWindow)

class Demo2:
    def __init__(self, master):
        self.master = master
        self.frame = tk.Frame(self.master)
        self.quitButton = tk.Button(self.frame, text = 'Quit', width = 25, command = self.close_windows)
        self.quitButton.pack()
        self.frame.pack()

    def close_windows(self):
        self.master.destroy()

def main(): 
    root = tk.Tk()
    app = Demo1(root)
    root.mainloop()

if __name__ == '__main__':
    main()

Result:

Demo1 window Demo2 window

How do I determine the dependencies of a .NET application?

It's funny I had a similar issue and didn't find anything suitable and was aware of good old Dependency Walker so in the end I wrote one myself.

This deals with .NET specifically and will show what references an assembly has (and missing) recursively. It'll also show native library dependencies.

It's free (for personal use) and available here for anyone interested: www.netdepends.com

www.netdepends.com

Feedback welcome.

How to add a tooltip to an svg graphic?

I came up with something using HTML + CSS only. Hope it works for you

_x000D_
_x000D_
.mzhrttltp {
  position: relative;
  display: inline-block;
}
.mzhrttltp .hrttltptxt {
  visibility: hidden;
  width: 120px;
  background-color: #040505;
  font-size:13px;color:#fff;font-family:IranYekanWeb;
  text-align: center;
  border-radius: 3px;
  padding: 4px 0;
  position: absolute;
  z-index: 1;
  top: 105%;
  left: 50%;
  margin-left: -60px;
}

.mzhrttltp .hrttltptxt::after {
  content: "";
  position: absolute;
  bottom: 100%;
  left: 50%;
  margin-left: -5px;
  border-width: 5px;
  border-style: solid;
  border-color: transparent transparent #040505 transparent;
}

.mzhrttltp:hover .hrttltptxt {
  visibility: visible;
}
_x000D_
<div class="mzhrttltp"><svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 24 24" fill="none" stroke="#e2062c" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" class="feather feather-heart"><path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"></path></svg><div class="hrttltptxt">?????&zwnj;????&zwnj;??</div></div>
_x000D_
_x000D_
_x000D_

How to get a jqGrid cell value when editing

You can use getCol to get the column values as an array then index into it by the row you are interested in.

var col = $('#grid').jqGrid('getCol', 'Sales', false);

var val = col[row];

How do I check if file exists in Makefile so I can delete it?

The problem is when you split your command over multiple lines. So, you can either use the \ at the end of lines for continuation as above or you can get everything on one line with the && operator in bash.

Then you can use a test command to test if the file does exist, e.g.:

test -f myApp && echo File does exist

-f file True if file exists and is a regular file.

-s file True if file exists and has a size greater than zero.

or does not:

test -f myApp || echo File does not exist
test ! -f myApp && echo File does not exist

The test is equivalent to [ command.

[ -f myApp ] && rm myApp   # remove myApp if it exists

and it would work as in your original example.

See: help [ or help test for further syntax.

"Non-static method cannot be referenced from a static context" error

Instance methods need to be called from an instance. Your setLoanItem method is an instance method (it doesn't have the modifier static), which it needs to be in order to function (because it is setting a value on the instance that it's called on (this)).

You need to create an instance of the class before you can call the method on it:

Media media = new Media();
media.setLoanItem("Yes");

(Btw it would be better to use a boolean instead of a string containing "Yes".)

Package signatures do not match the previously installed version

If you are trying to install it in an Emulator but have another phone connected to the computer via USB, detach the USB cable or disable USB debugging in the physical device. (Wasted 30min on it myself.)

Quickest way to convert a base 10 number to any base in .NET?

If anyone is seeking a VB option, this was based on Pavel's answer:

Public Shared Function ToBase(base10 As Long, Optional baseChars As String = "0123456789ABCDEFGHIJKLMNOPQRTSUVWXYZ") As String

    If baseChars.Length < 2 Then Throw New ArgumentException("baseChars must be at least 2 chars long")

    If base10 = 0 Then Return baseChars(0)

    Dim isNegative = base10 < 0
    Dim radix = baseChars.Length
    Dim index As Integer = 64 'because it's how long a string will be if the basechars are 2 long (binary)
    Dim chars(index) As Char '65 chars, 64 from above plus one for sign if it's negative

    base10 = Math.Abs(base10)


    While base10 > 0
        chars(index) = baseChars(base10 Mod radix)
        base10 \= radix

        index -= 1
    End While

    If isNegative Then
        chars(index) = "-"c
        index -= 1
    End If

    Return New String(chars, index + 1, UBound(chars) - index)

End Function

How to view method information in Android Studio?

If you just need a shortcut, then it is Ctrl + Q on Linux (and Windows). Just hover the mouse on the method and press Ctrl + Q to see the doc.

SPA best practices for authentication and session management

This question has been addressed, in a slightly different form, at length, here:

RESTful Authentication

But this addresses it from the server-side. Let's look at this from the client-side. Before we do that, though, there's an important prelude:

Javascript Crypto is Hopeless

Matasano's article on this is famous, but the lessons contained therein are pretty important:

https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2011/august/javascript-cryptography-considered-harmful/

To summarize:

  • A man-in-the-middle attack can trivially replace your crypto code with <script> function hash_algorithm(password){ lol_nope_send_it_to_me_instead(password); }</script>
  • A man-in-the-middle attack is trivial against a page that serves any resource over a non-SSL connection.
  • Once you have SSL, you're using real crypto anyways.

And to add a corollary of my own:

  • A successful XSS attack can result in an attacker executing code on your client's browser, even if you're using SSL - so even if you've got every hatch battened down, your browser crypto can still fail if your attacker finds a way to execute any javascript code on someone else's browser.

This renders a lot of RESTful authentication schemes impossible or silly if you're intending to use a JavaScript client. Let's look!

HTTP Basic Auth

First and foremost, HTTP Basic Auth. The simplest of schemes: simply pass a name and password with every request.

This, of course, absolutely requires SSL, because you're passing a Base64 (reversibly) encoded name and password with every request. Anybody listening on the line could extract username and password trivially. Most of the "Basic Auth is insecure" arguments come from a place of "Basic Auth over HTTP" which is an awful idea.

The browser provides baked-in HTTP Basic Auth support, but it is ugly as sin and you probably shouldn't use it for your app. The alternative, though, is to stash username and password in JavaScript.

This is the most RESTful solution. The server requires no knowledge of state whatsoever and authenticates every individual interaction with the user. Some REST enthusiasts (mostly strawmen) insist that maintaining any sort of state is heresy and will froth at the mouth if you think of any other authentication method. There are theoretical benefits to this sort of standards-compliance - it's supported by Apache out of the box - you could store your objects as files in folders protected by .htaccess files if your heart desired!

The problem? You are caching on the client-side a username and password. This gives evil.ru a better crack at it - even the most basic of XSS vulnerabilities could result in the client beaming his username and password to an evil server. You could try to alleviate this risk by hashing and salting the password, but remember: JavaScript Crypto is Hopeless. You could alleviate this risk by leaving it up to the Browser's Basic Auth support, but.. ugly as sin, as mentioned earlier.

HTTP Digest Auth

Is Digest authentication possible with jQuery?

A more "secure" auth, this is a request/response hash challenge. Except JavaScript Crypto is Hopeless, so it only works over SSL and you still have to cache the username and password on the client side, making it more complicated than HTTP Basic Auth but no more secure.

Query Authentication with Additional Signature Parameters.

Another more "secure" auth, where you encrypt your parameters with nonce and timing data (to protect against repeat and timing attacks) and send the. One of the best examples of this is the OAuth 1.0 protocol, which is, as far as I know, a pretty stonking way to implement authentication on a REST server.

http://tools.ietf.org/html/rfc5849

Oh, but there aren't any OAuth 1.0 clients for JavaScript. Why?

JavaScript Crypto is Hopeless, remember. JavaScript can't participate in OAuth 1.0 without SSL, and you still have to store the client's username and password locally - which puts this in the same category as Digest Auth - it's more complicated than HTTP Basic Auth but it's no more secure.

Token

The user sends a username and password, and in exchange gets a token that can be used to authenticate requests.

This is marginally more secure than HTTP Basic Auth, because as soon as the username/password transaction is complete you can discard the sensitive data. It's also less RESTful, as tokens constitute "state" and make the server implementation more complicated.

SSL Still

The rub though, is that you still have to send that initial username and password to get a token. Sensitive information still touches your compromisable JavaScript.

To protect your user's credentials, you still need to keep attackers out of your JavaScript, and you still need to send a username and password over the wire. SSL Required.

Token Expiry

It's common to enforce token policies like "hey, when this token has been around too long, discard it and make the user authenticate again." or "I'm pretty sure that the only IP address allowed to use this token is XXX.XXX.XXX.XXX". Many of these policies are pretty good ideas.

Firesheeping

However, using a token Without SSL is still vulnerable to an attack called 'sidejacking': http://codebutler.github.io/firesheep/

The attacker doesn't get your user's credentials, but they can still pretend to be your user, which can be pretty bad.

tl;dr: Sending unencrypted tokens over the wire means that attackers can easily nab those tokens and pretend to be your user. FireSheep is a program that makes this very easy.

A Separate, More Secure Zone

The larger the application that you're running, the harder it is to absolutely ensure that they won't be able to inject some code that changes how you process sensitive data. Do you absolutely trust your CDN? Your advertisers? Your own code base?

Common for credit card details and less common for username and password - some implementers keep 'sensitive data entry' on a separate page from the rest of their application, a page that can be tightly controlled and locked down as best as possible, preferably one that is difficult to phish users with.

Cookie (just means Token)

It is possible (and common) to put the authentication token in a cookie. This doesn't change any of the properties of auth with the token, it's more of a convenience thing. All of the previous arguments still apply.

Session (still just means Token)

Session Auth is just Token authentication, but with a few differences that make it seem like a slightly different thing:

  • Users start with an unauthenticated token.
  • The backend maintains a 'state' object that is tied to a user's token.
  • The token is provided in a cookie.
  • The application environment abstracts the details away from you.

Aside from that, though, it's no different from Token Auth, really.

This wanders even further from a RESTful implementation - with state objects you're going further and further down the path of plain ol' RPC on a stateful server.

OAuth 2.0

OAuth 2.0 looks at the problem of "How does Software A give Software B access to User X's data without Software B having access to User X's login credentials."

The implementation is very much just a standard way for a user to get a token, and then for a third party service to go "yep, this user and this token match, and you can get some of their data from us now."

Fundamentally, though, OAuth 2.0 is just a token protocol. It exhibits the same properties as other token protocols - you still need SSL to protect those tokens - it just changes up how those tokens are generated.

There are two ways that OAuth 2.0 can help you:

  • Providing Authentication/Information to Others
  • Getting Authentication/Information from Others

But when it comes down to it, you're just... using tokens.

Back to your question

So, the question that you're asking is "should I store my token in a cookie and have my environment's automatic session management take care of the details, or should I store my token in Javascript and handle those details myself?"

And the answer is: do whatever makes you happy.

The thing about automatic session management, though, is that there's a lot of magic happening behind the scenes for you. Often it's nicer to be in control of those details yourself.

I am 21 so SSL is yes

The other answer is: Use https for everything or brigands will steal your users' passwords and tokens.

Select unique values with 'select' function in 'dplyr' library

In dplyr 0.3 this can be easily achieved using the distinct() method.

Here is an example:

distinct_df = df %>% distinct(field1)

You can get a vector of the distinct values with:

distinct_vector = distinct_df$field1

You can also select a subset of columns at the same time as you perform the distinct() call, which can be cleaner to look at if you examine the data frame using head/tail/glimpse.:

distinct_df = df %>% distinct(field1) %>% select(field1) distinct_vector = distinct_df$field1

How to create a horizontal loading progress bar?

Worked for me , can try with the same

<ProgressBar
    android:id="@+id/determinateBar"
    android:indeterminateOnly="true"
    android:indeterminateDrawable="@android:drawable/progress_indeterminate_horizontal"
    android:indeterminateDuration="10"
    android:indeterminateBehavior="repeat"
    android:progressBackgroundTint="#208afa"
    android:progressBackgroundTintMode="multiply"
    android:minHeight="24dip"
    android:maxHeight="24dip"
    android:layout_width="match_parent"
    android:layout_height="10dp"
    android:visibility="visible"/>

100% width in React Native Flexbox

Use javascript to get the width and height and add them in View's style. To get full width and height, use Dimensions.get('window').width https://facebook.github.io/react-native/docs/dimensions.html

getSize() {
    return {
        width: Dimensions.get('window').width, 
        height: Dimensions.get('window').height
    }
}

and then,

<View style={[styles.overlay, this.getSize()]}>

.do extension in web pages?

I've occasionally thought that it might serve a purpose to add a layer of security by obscuring the back-end interpreter through a remapping of .php or whatever to .aspx or whatever so that any potential hacker would be sent down the wrong path, at least for a while. I never bothered to try it and I don't do a lot of webserver work any more so I'm unlikely to.

However, I'd be interested in the perspective of an experienced server admin on that notion.

Programmatically add new column to DataGridView

Keep it simple

dataGridView1.Columns.Add("newColumnName", "Column Name in Text");

To add rows

dataGridView1.Rows.Add("Value for column#1"); // [,"column 2",...]

Java synchronized block vs. Collections.synchronizedMap

If you are using JDK 6 then you might want to check out ConcurrentHashMap

Note the putIfAbsent method in that class.

How to display multiple images in one figure correctly?

You could try the following:

import matplotlib.pyplot as plt
import numpy as np

def plot_figures(figures, nrows = 1, ncols=1):
    """Plot a dictionary of figures.

    Parameters
    ----------
    figures : <title, figure> dictionary
    ncols : number of columns of subplots wanted in the display
    nrows : number of rows of subplots wanted in the figure
    """

    fig, axeslist = plt.subplots(ncols=ncols, nrows=nrows)
    for ind,title in zip(range(len(figures)), figures):
        axeslist.ravel()[ind].imshow(figures[title], cmap=plt.jet())
        axeslist.ravel()[ind].set_title(title)
        axeslist.ravel()[ind].set_axis_off()
    plt.tight_layout() # optional



# generation of a dictionary of (title, images)
number_of_im = 20
w=10
h=10
figures = {'im'+str(i): np.random.randint(10, size=(h,w)) for i in range(number_of_im)}

# plot of the images in a figure, with 5 rows and 4 columns
plot_figures(figures, 5, 4)

plt.show()

However, this is basically just copy and paste from here: Multiple figures in a single window for which reason this post should be considered to be a duplicate.

I hope this helps.

How to list the tables in a SQLite database file that was opened with ATTACH?

There is a command available for this on the SQLite command line:

.tables ?PATTERN?      List names of tables matching a LIKE pattern

Which converts to the following SQL:

SELECT name FROM sqlite_master
WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%'
UNION ALL
SELECT name FROM sqlite_temp_master
WHERE type IN ('table','view')
ORDER BY 1

How to determine if .NET Core is installed

dotnet --info

OR

dotnet --version

write the above command(s) on your CMD or Terminal. Then it will show something like bellow enter image description here

Or

enter image description here

How does the "this" keyword work?

This is the best explanation I've seen: Understand JavaScripts this with Clarity

The this reference ALWAYS refers to (and holds the value of) an object—a singular object—and it is usually used inside a function or a method, although it can be used outside a function in the global scope. Note that when we use strict mode, this holds the value of undefined in global functions and in anonymous functions that are not bound to any object.

There are Four Scenarios where this can be confusing:

  1. When we pass a method (that uses this) as an argument to be used as a callback function.
  2. When we use an inner function (a closure). It is important to take note that closures cannot access the outer function’s this variable by using the this keyword because the this variable is accessible only by the function itself, not by inner functions.
  3. When a method which relies on this is assigned to a variable across contexts, in which case this references another object than originally intended.
  4. When using this along with the bind, apply, and call methods.

He gives code examples, explanations, and solutions, which I thought was very helpful.

ERROR 1148: The used command is not allowed with this MySQL version

I find the answer here.

It's because the server variable local_infile is set to FALSE|0. Refer from the document.

You can verify by executing:

SHOW VARIABLES LIKE 'local_infile';

If you have SUPER privilege you can enable it (without restarting server with a new configuration) by executing:

SET GLOBAL local_infile = 1;

How to get parameter on Angular2 route in Angular way?

Update: Sep 2019

As a few people have mentioned, the parameters in paramMap should be accessed using the common MapAPI:

To get a snapshot of the params, when you don't care that they may change:

this.bankName = this.route.snapshot.paramMap.get('bank');

To subscribe and be alerted to changes in the parameter values (typically as a result of the router's navigation)

this.route.paramMap.subscribe( paramMap => {
    this.bankName = paramMap.get('bank');
})

Update: Aug 2017

Since Angular 4, params have been deprecated in favor of the new interface paramMap. The code for the problem above should work if you simply substitute one for the other.

Original Answer

If you inject ActivatedRoute in your component, you'll be able to extract the route parameters

    import {ActivatedRoute} from '@angular/router';
    ...
    
    constructor(private route:ActivatedRoute){}
    bankName:string;
    
    ngOnInit(){
        // 'bank' is the name of the route parameter
        this.bankName = this.route.snapshot.params['bank'];
    }

If you expect users to navigate from bank to bank directly, without navigating to another component first, you ought to access the parameter through an observable:

    ngOnInit(){
        this.route.params.subscribe( params =>
            this.bankName = params['bank'];
        )
    }

For the docs, including the differences between the two check out this link and search for "activatedroute"

how to format date in Component of angular 5

Refer to the below link,

https://angular.io/api/common/DatePipe

**Code Sample**

@Component({
 selector: 'date-pipe',
 template: `<div>
   <p>Today is {{today | date}}</p>
   <p>Or if you prefer, {{today | date:'fullDate'}}</p>
   <p>The time is {{today | date:'h:mm a z'}}</p>
 </div>`
})
// Get the current date and time as a date-time value.
export class DatePipeComponent {
  today: number = Date.now();
}

{{today | date:'MM/dd/yyyy'}} output: 17/09/2019

or

{{today | date:'shortDate'}} output: 17/9/19

Getting Hour and Minute in PHP

Try this:

$hourMin = date('H:i');

This will be 24-hour time with an hour that is always two digits. For all options, see the PHP docs for date().

Euclidean distance of two vectors

Use the dist() function, but you need to form a matrix from the two inputs for the first argument to dist():

dist(rbind(x1, x2))

For the input in the OP's question we get:

> dist(rbind(x1, x2))
        x1
x2 7.94821

a single value that is the Euclidean distance between x1 and x2.

Are there constants in JavaScript?

For a while, I specified "constants" (which still weren't actually constants) in object literals passed through to with() statements. I thought it was so clever. Here's an example:

with ({
    MY_CONST : 'some really important value'
}) {
    alert(MY_CONST);
}

In the past, I also have created a CONST namespace where I would put all of my constants. Again, with the overhead. Sheesh.

Now, I just do var MY_CONST = 'whatever'; to KISS.

Internet Explorer 11- issue with security certificate error prompt

If you updated Internet Explorer and began having technical problems, you can use the Compatibility View feature to emulate a previous version of Internet Explorer.

For instructions, see the section below that corresponds with your version. To find your version number, click Help > About Internet Explorer. Internet Explorer 11

To edit the Compatibility View list:

Open the desktop, and then tap or click the Internet Explorer icon on the taskbar.
Tap or click the Tools button (Image), and then tap or click Compatibility View settings.
To remove a website:
Click the website(s) where you would like to turn off Compatibility View, clicking Remove after each one.
To add a website:
Under Add this website, enter the website(s) where you would like to turn on Compatibility View, clicking Add after each one.

setInterval in a React app

Updated 10-second countdown using Hooks (a new feature proposal that lets you use state and other React features without writing a class. They’re currently in React v16.7.0-alpha).

import React, { useState, useEffect } from 'react';
import ReactDOM from 'react-dom';

const Clock = () => {
    const [currentCount, setCount] = useState(10);
    const timer = () => setCount(currentCount - 1);

    useEffect(
        () => {
            if (currentCount <= 0) {
                return;
            }
            const id = setInterval(timer, 1000);
            return () => clearInterval(id);
        },
        [currentCount]
    );

    return <div>{currentCount}</div>;
};

const App = () => <Clock />;

ReactDOM.render(<App />, document.getElementById('root'));

How to shuffle an ArrayList

Try Collections.shuffle(list).If usage of this method is barred for solving the problem, then one can look at the actual implementation.

jQuery .search() to any string

Ah, that would be because RegExp is not jQuery. :)

Try this page. jQuery.attr doesn't return a String so that would certainly cause in this regard. Fortunately I believe you can just use .text() to return the String representation.

Something like:

$("li").val("title").search(/sometext/i));

How to set a string's color

for linux (bash) following code works for me:

System.out.print("\033[31mERROR  \033[0m");

the \033[31m will switch the color to red and \033[0m will switch it back to normal.

How to avoid the "Windows Defender SmartScreen prevented an unrecognized app from starting warning"

If you have a standard code signing certificate, some time will be needed for your application to build trust. Microsoft affirms that an Extended Validation (EV) Code Signing Certificate allows us to skip this period of trust-building. According to Microsoft, extended validation certificates allow the developer to immediately establish a reputation with SmartScreen. Otherwise, the users will see a warning like "Windows Defender SmartScreen prevented an unrecognized app from starting. Running this app might put your PC at risk.", with the two buttons: "Run anyway" and "Don't run".

Another Microsoft resource states the following (quote): "Although not required, programs signed by an EV code signing certificate can immediately establish a reputation with SmartScreen reputation services even if no prior reputation exists for that file or publisher. EV code signing certificates also have a unique identifier which makes it easier to maintain reputation across certificate renewals."

My experience is as follows. Since 2005, we have been using regular (non-EV) code signing certificates to sign .MSI, .EXE and .DLL files with time stamps, and there has never been a problem with SmartScreen until 2018, when there was just one case when it took 3 days for a beta version of our application to build trust since we have released it to beta testers, and it was in the middle of certificate validity period. I don't know what SmartScreen might not like in that specific version of our application, but there have been no SmartScreen complaints since then. Therefore, if your certificate is a non-EV, it is a signed application (such as an .MSI file) that will build trust over time, not a certificate. For example, a certificate can be issued a few months ago and used to sign many files, but for each signed file you publish, it may take a few days for SmartScreen to stop complaining about the file after publishing, as was in our case in 2018.

As a conclusion, to avoid the warning completely, i.e. prevent it from happening even suddenly, you need an Extended Validation (EV) code signing certificate.

What are the different usecases of PNG vs. GIF vs. JPEG vs. SVG?

GIF has 8 bit (256 color) palette where PNG as upto 24 bit color palette. So, PNG can support more color and of course the algorithm support compression

Hiding an Excel worksheet with VBA

This can be done in a single line, as long as the worksheet is active:

ActiveSheet.Visible = xlSheetHidden

However, you may not want to do this, especially if you use any "select" operations or you use any more ActiveSheet operations.

relative path in require_once doesn't work

I just came across this same problem, where it was all working fine, up until the point I had an includes within another includes.

require_once '../script/pdocrud.php';  //This worked fine up until I had an includes within another includes, then I got this error:
Fatal error: require_once() [function.require]: Failed opening required '../script/pdocrud.php' (include_path='.:/opt/php52/lib/php')

Solution 1. (undesired hardcoding of my public html folder name, but it works):

require_once $_SERVER["DOCUMENT_ROOT"] . '/orders.simplystyles.com/script/pdocrud.php';

Solution 2. (undesired comment above about DIR only working since php 5.3, but it works):

require_once __DIR__. '/../script/pdocrud.php';

Solution 3. (I can't see any downsides, and it works perfectly in my php 5.3):

require_once dirname(__FILE__). '/../script/pdocrud.php';

System.Timers.Timer vs System.Threading.Timer

In his book "CLR Via C#", Jeff Ritcher discourages using System.Timers.Timer, this timer is derived from System.ComponentModel.Component, allowing it to be used in design surface of Visual Studio. So that it would be only useful if you want a timer on a design surface.

He prefers to use System.Threading.Timer for background tasks on a thread pool thread.

What is the difference between supervised learning and unsupervised learning?

Supervised Learning is basically a technique in which the training data from which the machine learns is already labelled that is suppose a simple even odd number classifier where you have already classified the data during training . Therefore it uses "LABELLED" data.

Unsupervised learning on the contrary is a technique in which the machine by itself labels the data . Or you can say its the case when the machine learns by itself from scratch.

psql: FATAL: database "<user>" does not exist

Login using default template1 database:

#psql -d template1
#template1=# \l

  List of databases
   Name    |  Owner  | Encoding |   Collate   |    Ctype    |  Access privileges  
-----------+---------+----------+-------------+-------------+---------------------
 postgres  | gogasca | UTF8     | en_US.UTF-8 | en_US.UTF-8 | 
 template0 | gogasca | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/gogasca         +
           |         |          |             |             | gogasca=CTc/gogasca
 template1 | gogasca | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/gogasca         +
           |         |          |             |             | gogasca=CTc/gogasca
(3 rows)

Create a database with your userId:

template1=# CREATE DATABASE gogasca WITH OWNER gogasca ENCODING 'UTF8';
CREATE DATABASE

Quit and then login again

template1=# \q
gonzo:~ gogasca$ psql -h localhost
psql (9.4.0)
Type "help" for help.

gogasca=# \l
                                List of databases
   Name    |  Owner  | Encoding |   Collate   |    Ctype    |  Access privileges  
-----------+---------+----------+-------------+-------------+---------------------
 gogasca   | gogasca | UTF8     | en_US.UTF-8 | en_US.UTF-8 | 
 postgres  | gogasca | UTF8     | en_US.UTF-8 | en_US.UTF-8 | 
 template0 | gogasca | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/gogasca         +
           |         |          |             |             | gogasca=CTc/gogasca
 template1 | gogasca | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/gogasca         +
           |         |          |             |             | gogasca=CTc/gogasca
(4 rows)

mySQL convert varchar to date

select date_format(str_to_date('31/12/2010', '%d/%m/%Y'), '%Y%m'); 

or

select date_format(str_to_date('12/31/2011', '%m/%d/%Y'), '%Y%m'); 

hard to tell from your example

SqlDataAdapter vs SqlDataReader

Use an SqlDataAdapter when wanting to populate an in-memory DataSet/DataTable from the database. You then have the flexibility to close/dispose off the connection, pass the datatable/set around in memory. You could then manipulate the data and persist it back into the DB using the data adapter, in conjunction with InsertCommand/UpdateCommand.

Use an SqlDataReader when wanting fast, low-memory footprint data access without the need for flexibility for e.g. passing the data around your business logic. This is more optimal for quick, low-memory usage retrieval of large data volumes as it doesn't load all the data into memory all in one go - with the SqlDataAdapter approach, the DataSet/DataTable would be filled with all the data so if there's a lot of rows & columns, that will require a lot of memory to hold.

ORA-01031: insufficient privileges when selecting view

Finally I got it to work. Steve's answer is right but not for all cases. It fails when that view is being executed from a third schema. For that to work you have to add the grant option:

GRANT SELECT ON [TABLE_NAME] TO [READ_USERNAME] WITH GRANT OPTION;

That way, [READ_USERNAME] can also grant select privilege over the view to another schema

WPF: ItemsControl with scrollbar (ScrollViewer)

You have to modify the control template instead of ItemsPanelTemplate:

<ItemsControl >
    <ItemsControl.Template>
        <ControlTemplate>
            <ScrollViewer x:Name="ScrollViewer" Padding="{TemplateBinding Padding}">
                <ItemsPresenter />
            </ScrollViewer>
        </ControlTemplate>
    </ItemsControl.Template>
</ItemsControl>

Maybe, your code does not working because StackPanel has own scrolling functionality. Try to use StackPanel.CanVerticallyScroll property.

Google MAP API v3: Center & Zoom on displayed markers

In case you prefer more functional style:

// map - instance of google Map v3
// markers - array of Markers
var bounds = markers.reduce(function(bounds, marker) {
    return bounds.extend(marker.getPosition());
}, new google.maps.LatLngBounds());

map.setCenter(bounds.getCenter());
map.fitBounds(bounds);

C# generics syntax for multiple type parameter constraints

void foo<TOne, TTwo>() 
   where TOne : BaseOne
   where TTwo : BaseTwo

More info here:
http://msdn.microsoft.com/en-us/library/d5x73970.aspx

How to update std::map after using the find method?

I would use the operator[].

map <char, int> m1;

m1['G'] ++;  // If the element 'G' does not exist then it is created and 
             // initialized to zero. A reference to the internal value
             // is returned. so that the ++ operator can be applied.

// If 'G' did not exist it now exist and is 1.
// If 'G' had a value of 'n' it now has a value of 'n+1'

So using this technique it becomes really easy to read all the character from a stream and count them:

map <char, int>                m1;
std::ifstream                  file("Plop");
std::istreambuf_iterator<char> end;

for(std::istreambuf_iterator<char> loop(file); loop != end; ++loop)
{
    ++m1[*loop]; // prefer prefix increment out of habbit
}

Flutter: how to make a TextField with HintText but no Underline?

change the focused border to none

TextField(
      decoration: new InputDecoration(
          border: InputBorder.none,
          focusedBorder: InputBorder.none,
          contentPadding: EdgeInsets.only(left: 15, bottom: 11, top: 11, right: 15),
          hintText: 'Subject'
      ),
    ),

How can I read comma separated values from a text file in Java?

Use BigDecimal, not double

The Answer by adatapost is right about using String::split but wrong about using double to represent your longitude-latitude values. The float/Float and double/Double types use floating-point technology which trades away accuracy for speed of execution.

Instead use BigDecimal to correctly represent your lat-long values.

Use Apache Commons CSV library

Also, best to let a library such as Apache Commons CSV perform the chore of reading and writing CSV or Tab-delimited files.

Example app

Here is a complete example app using that Commons CSV library. This app writes then reads a data file. It uses String::split for the writing. And the app uses BigDecimal objects to represent your lat-long values.

package work.basil.example;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import org.apache.commons.csv.CSVRecord;

import java.io.BufferedReader;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Instant;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

public class LatLong
{
    //----------|  Write  |-----------------------------
    public void write ( final Path path )
    {
        List < String > inputs =
                List.of(
                        "28.515046280572285,77.38258838653564" ,
                        "28.51430151808072,77.38336086273193" ,
                        "28.513566177802456,77.38413333892822" ,
                        "28.512830832397192,77.38490581512451" ,
                        "28.51208605426073,77.3856782913208" ,
                        "28.511341270865113,77.38645076751709" );

        // Use try-with-resources syntax to auto-close the `CSVPrinter`.
        try ( final CSVPrinter printer = CSVFormat.RFC4180.withHeader( "latitude" , "longitude" ).print( path , StandardCharsets.UTF_8 ) ; )
        {
            for ( String input : inputs )
            {
                String[] fields = input.split( "," );
                printer.printRecord( fields[ 0 ] , fields[ 1 ] );
            }
        } catch ( IOException e )
        {
            e.printStackTrace();
        }
    }

    //----------|  Read  |-----------------------------
    public void read ( Path path )
    {
        // TODO: Add a check for valid file existing.

        try
        {
            // Read CSV file.
            BufferedReader reader = Files.newBufferedReader( path );
            Iterable < CSVRecord > records = CSVFormat.RFC4180.withFirstRecordAsHeader().parse( reader );
            for ( CSVRecord record : records )
            {
                BigDecimal latitude = new BigDecimal( record.get( "latitude" ) );
                BigDecimal longitude = new BigDecimal( record.get( "longitude" ) );
                System.out.println( "lat: " + latitude + " | long: " + longitude );
            }
        } catch ( IOException e )
        {
            e.printStackTrace();
        }
    }

    //----------|  Main  |-----------------------------
    public static void main ( String[] args )
    {
        LatLong app = new LatLong();

        // Write
        Path pathOutput = Paths.get( "/Users/basilbourque/lat-long.csv" );
        app.write( pathOutput );
        System.out.println( "Writing file: " + pathOutput );

        // Read
        Path pathInput = Paths.get( "/Users/basilbourque/lat-long.csv" );
        app.read( pathInput );

        System.out.println( "Done writing & reading lat-long data file. " + Instant.now() );
    }

}

In MySQL, can I copy one row to insert into the same table?

I just had to do this and this was my manual solution:

  1. In phpmyadmin, check the row you wish to copy
  2. At the bottom under query result operations click 'Export'
  3. On the next page check 'Save as file' then click 'Go'
  4. Open the exported file with a text editor, find the value of the primary field and change it to something unique.
  5. Back in phpmyadmin click on the 'Import' tab, locate the file to import .sql file under browse, click 'Go' and the duplicate row should be inserted.

If you don't know what the PRIMARY field is, look back at your phpmyadmin page, click on the 'Structure' tab and at the bottom of the page under 'Indexes' it will show you which 'Field' has a 'Keyname' value 'PRIMARY'.

Kind of a long way around, but if you don't want to deal with markup and just need to duplicate a single row there you go.

Why does JSON.parse fail with the empty string?

As an empty string is not valid JSON it would be incorrect for JSON.parse('') to return null because "null" is valid JSON. e.g.

JSON.parse("null");

returns null. It would be a mistake for invalid JSON to also be parsed to null.

While an empty string is not valid JSON two quotes is valid JSON. This is an important distinction.

Which is to say a string that contains two quotes is not the same thing as an empty string.

JSON.parse('""');

will parse correctly, (returning an empty string). But

JSON.parse('');

will not.

Valid minimal JSON strings are

The empty object '{}'

The empty array '[]'

The string that is empty '""'

A number e.g. '123.4'

The boolean value true 'true'

The boolean value false 'false'

The null value 'null'

DECODE( ) function in SQL Server

You could use the 'CASE .. WHEN .. THEN .. ELSE .. END' syntax in SQL.

What is the unix command to see how much disk space there is and how much is remaining?

I love doing du -sh * | sort -nr | less to sort by the largest files first

Can I safely delete contents of Xcode Derived data folder?

I got this error because Int was int in one file. So stupid.

How to pre-populate the sms body text via an html link

I suspect in most applications you won't know who to text, so you only want to fill the text body, not the number. That works as you'd expect by just leaving out the number - here's what the URLs look like in that case:

sms:?body=message

For iOS same thing except with the ;

sms:;body=message

Here's an example of the code I use to set up the SMS:

var ua = navigator.userAgent.toLowerCase();
var url;

if (ua.indexOf("iphone") > -1 || ua.indexOf("ipad") > -1)
   url = "sms:;body=" + encodeURIComponent("I'm at " + mapUrl + " @ " + pos.Address);
else
   url = "sms:?body=" + encodeURIComponent("I'm at " + mapUrl + " @ " + pos.Address);

   location.href = url;

Upgrading PHP in XAMPP for Windows?

I needed to update my php from 5.3.8 to 5.3.29. (both Thread Safe) on Windows

Steps I did:

  1. Back-up my initial php folder, under xampp.
  2. Downloaded zip from here http://windows.php.net/download/#php-5.3-ts-VC9-x86
  3. Unpack that zip into xampp folder.
  4. Copied php.ini file from old php folder into new one.
  5. Copied a couple of folders that I didn't have in the new php folder, from old one. For example: extras, which contained browscap.ini file (this one is needed)
  6. Copied needed extensions, from old php ext folder into new php ext folder. I copied them manually, by checking list of extensions from php.ini file.
  7. Copied also these files: php5apache2_2.dll, php5ts.dll

Hope that I covered everything.

Most probably these steps will not work if you change major versions of php, e.g. 5.3.x to 5.4.x, but for minor versions, it should work.

Also, a good way to see what's wrong... start command line and try to start httpd.exe, under xampp/apache/bin from there, it will list errors found.

How to copy a selection to the OS X clipboard

I am currently on OS X 10.9 and my efforts to compile vim with +xterm_clipboard brought me nothing. So my current solution is to use MacVim in terminal mode with option set clipboard=unnamed in my ~/.vimrc file. Works perfect for me.

MySQL - UPDATE query based on SELECT Query

You can use:

UPDATE Station AS st1, StationOld AS st2
   SET st1.already_used = 1
 WHERE st1.code = st2.code

The 'packages' element is not declared

You can also find a copy of the nuspec.xsd here as it seems to no longer be available:

https://gist.github.com/sharwell/6131243

Error: free(): invalid next size (fast):

We need the code, but that usually pops up when you try to free() memory from a pointer that is not allocated. This often happens when you're double-freeing.

How to pass List from Controller to View in MVC 3

  1. Create a model which contains your list and other things you need for the view.

    For example:

    public class MyModel
    {
        public List<string> _MyList { get; set; }
    }
    
  2. From the action method put your desired list to the Model, _MyList property, like:

    public ActionResult ArticleList(MyModel model)
    {
        model._MyList = new List<string>{"item1","item2","item3"};
        return PartialView(@"~/Views/Home/MyView.cshtml", model);
    }
    
  3. In your view access the model as follows

    @model MyModel
    foreach (var item in Model)
    {
       <div>@item</div>
    }
    

I think it will help for start.

Getting new Twitter API consumer and secret keys

consumer_key = API key

consumer_secret = API key secret

Found it hidden in Twitter API Docs

Twitter Docs screenshot

Twitter's naming is just too confusing.

wamp server mysql user id and password

Hit enter as there is no password. Enter the following commands:

mysql> SET PASSWORD for 'root'@'localhost' = password('enteryourpassword');
mysql> SET PASSWORD for 'root'@'127.0.0.1' = password('enteryourpassword');
mysql> SET PASSWORD for 'root'@'::1' = password('enteryourpassword');

That’s it, I keep the passwords the same to keep things simple. If you want to check the user’s table to see that the info has been updated just enter the additional commands as shown below. This is a good option to check that you have indeed entered the same password for all hosts.

How much should a function trust another function

Typically this is bad practice. Since it is possible to call addEdge before addNode and have a NullPointerException (NPE) thrown, addEdge should check if the result is null and throw a more descriptive Exception. In my opinion, the only time it is acceptable not to check for nulls is when you expect the result to never be null, in which case, an NPE is plenty descriptive.

How to switch from POST to GET in PHP CURL

Make sure that you're putting your query string at the end of your URL when doing a GET request.

$qry_str = "?x=10&y=20";
$ch = curl_init();

// Set query data here with the URL
curl_setopt($ch, CURLOPT_URL, 'http://example.com/test.php' . $qry_str); 

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 3);
$content = trim(curl_exec($ch));
curl_close($ch);
print $content;
With a POST you pass the data via the CURLOPT_POSTFIELDS option instead 
of passing it in the CURLOPT__URL.
-------------------------------------------------------------------------

$qry_str = "x=10&y=20";
curl_setopt($ch, CURLOPT_URL, 'http://example.com/test.php');  
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 3);

// Set request method to POST
curl_setopt($ch, CURLOPT_POST, 1);

// Set query data here with CURLOPT_POSTFIELDS
curl_setopt($ch, CURLOPT_POSTFIELDS, $qry_str);

$content = trim(curl_exec($ch));
curl_close($ch);
print $content;

Note from the curl_setopt() docs for CURLOPT_HTTPGET (emphasis added):

[Set CURLOPT_HTTPGET equal to] TRUE to reset the HTTP request method to GET.
Since GET is the default, this is only necessary if the request method has been changed.

How to view DLL functions?

Without telling us what language this dll/assembly is from, we can only guess.

So how about .NET Reflector

How do you run a single query through mysql from the command line?

echo "select * from users;" | mysql -uroot -p -hslavedb.mydomain.com mydb_production

Git: How do I list only local branches?

Just git branch without options.

From the manpage:

With no arguments, existing branches are listed and the current branch will be highlighted with an asterisk.

How to uninstall a Windows Service when there is no executable for it left on the system?

found here

I just tried on windows XP, it worked

local computer: sc \\. delete [service-name]

  Deleting services in Windows Server 2003

  We can use sc.exe in the Windows Server 2003 to control services, create services and delete services. Since some people thought they must directly modify the registry to delete a service, I would like to share how to use sc.exe to delete a service without directly modifying the registry so that decreased the possibility for system failures.

  To delete a service: 

  Click “start“ - “run“, and then enter “cmd“ to open Microsoft Command Console.

  Enter command:

  sc servername delete servicename

  For instance, sc \\dc delete myservice

  (Note: In this example, dc is my Domain Controller Server name, which is not the local machine, myservice is the name of the service I want to delete on the DC server.)

  Below is the official help of all sc functions:

  DESCRIPTION:
    SC is a command line program used for communicating with the
    NT Service Controller and services. 
  USAGE:
          sc

Cannot use Server.MapPath

you can try using this

    System.Web.HttpContext.Current.Server.MapPath(path);

or use HostingEnvironment.MapPath

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

How to uninstall/upgrade Angular CLI?

Run the following commands to get the very latest of angular

npm uninstall -g @angular/cli
npm cache verify
npm install -g @angular/cli@latest
npm install

How to list npm user-installed packages?

You can try NPM Desktop manager NPM Desktop manager

With just one click, you can install/uninstall packages in dev or global status.

Simple example of threading in C++

It largely depends on the library you decide to use. For instance, if you use the wxWidgets library, the creation of a thread would look like this:

class RThread : public wxThread {

public:
    RThread()
        : wxThread(wxTHREAD_JOINABLE){
    }
private:
    RThread(const RThread &copy);

public:
    void *Entry(void){
        //Do...

        return 0;
    }

};

wxThread *CreateThread() {
    //Create thread
    wxThread *_hThread = new RThread();

    //Start thread
    _hThread->Create();
    _hThread->Run();

    return _hThread;
}

If your main thread calls the CreateThread method, you'll create a new thread that will start executing the code in your "Entry" method. You'll have to keep a reference to the thread in most cases to join or stop it. More info here: wxThread documentation

Best way to iterate through a Perl array

In single line to print the element or array.

print $_ for (@array);

NOTE: remember that $_ is internally referring to the element of @array in loop. Any changes made in $_ will reflect in @array; ex.

my @array = qw( 1 2 3 );
for (@array) {
        $_ = $_ *2 ;
}
print "@array";

output: 2 4 6

Visual Studio Code pylint: Unable to import 'protorpc'

I've not played around with all possibilities, but at least I had the impression that this could be a python version related issue. No idea why, I just trusted my gut.

Thus I just changed the pythonPath to python3 (default: python):

"python.pythonPath": "python3"

I reinstalled the dependencies (including pylint!!!) with

pip3 install <package> --user

... and after restarting vs code, everything looked fine.

HTH Kai

The request was aborted: Could not create SSL/TLS secure channel

I found the type of certificate also comes into play.

I had a cert that was:

(the below output was in mmc , certificate properties )

Digital Signature, Key Encipherment (a0)

(the below output was from my C# code below)

X509Extension.X509KeyUsageExtension.KeyUsages='KeyEncipherment, DigitalSignature' X509KeyUsageExtension.KeyUsages.X509KeyUsageFlags.CrlSign='False' X509KeyUsageExtension.KeyUsages.X509KeyUsageFlags.DataEncipherment='False' X509KeyUsageExtension.KeyUsages.X509KeyUsageFlags.DecipherOnly='False' X509KeyUsageExtension.KeyUsages.X509KeyUsageFlags.DigitalSignature='True' X509KeyUsageExtension.KeyUsages.X509KeyUsageFlags.EncipherOnly='False' X509KeyUsageExtension.KeyUsages.X509KeyUsageFlags.KeyAgreement='False' X509KeyUsageExtension.KeyUsages.X509KeyUsageFlags.KeyCertSign='False' X509KeyUsageExtension.KeyUsages.X509KeyUsageFlags.KeyEncipherment='True' X509KeyUsageExtension.KeyUsages.X509KeyUsageFlags.None='False' X509KeyUsageExtension.KeyUsages.X509KeyUsageFlags.NonRepudiation='False'

the above did not work.

===============================

Then another certificate with :

(the below output was in mmc , certificate properties )

Certificate Signing, Off-line CRL Signing, CRL Signing (06)

(the below output was from my C# code below)

X509Extension.X509KeyUsageExtension.KeyUsages='CrlSign, KeyCertSign' X509KeyUsageExtension.KeyUsages.X509KeyUsageFlags.CrlSign='True' X509KeyUsageExtension.KeyUsages.X509KeyUsageFlags.DataEncipherment='False' X509KeyUsageExtension.KeyUsages.X509KeyUsageFlags.DecipherOnly='False' X509KeyUsageExtension.KeyUsages.X509KeyUsageFlags.DigitalSignature='False' X509KeyUsageExtension.KeyUsages.X509KeyUsageFlags.EncipherOnly='False' X509KeyUsageExtension.KeyUsages.X509KeyUsageFlags.KeyAgreement='False' X509KeyUsageExtension.KeyUsages.X509KeyUsageFlags.KeyCertSign='True' X509KeyUsageExtension.KeyUsages.X509KeyUsageFlags.KeyEncipherment='False' X509KeyUsageExtension.KeyUsages.X509KeyUsageFlags.None='False' X509KeyUsageExtension.KeyUsages.X509KeyUsageFlags.NonRepudiation='False'

and it did work

The below code will allow you to inspect your client certificate

using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;

namespace MyNamespace
{
    public static class SecurityShower
    {
        public static void ShowHttpWebRequest(System.Net.HttpWebRequest hwr)
        {
            StringBuilder sb = new StringBuilder();
            if (null != hwr)
            {
                sb.Append("-----------------------------------------------HttpWebRequest" + System.Environment.NewLine);
                sb.Append(string.Format("HttpWebRequest.Address.AbsolutePath='{0}'", hwr.Address.AbsolutePath) + System.Environment.NewLine);
                sb.Append(string.Format("HttpWebRequest.Address.AbsoluteUri='{0}'", hwr.Address.AbsoluteUri) + System.Environment.NewLine);
                sb.Append(string.Format("HttpWebRequest.Address='{0}'", hwr.Address) + System.Environment.NewLine);

                sb.Append(string.Format("HttpWebRequest.RequestUri.AbsolutePath='{0}'", hwr.RequestUri.AbsolutePath) + System.Environment.NewLine);
                sb.Append(string.Format("HttpWebRequest.RequestUri.AbsoluteUri='{0}'", hwr.RequestUri.AbsoluteUri) + System.Environment.NewLine);
                sb.Append(string.Format("HttpWebRequest.RequestUri='{0}'", hwr.RequestUri) + System.Environment.NewLine);

                foreach (X509Certificate cert in hwr.ClientCertificates)
                {
                    sb.Append("START*************************************************");
                    ShowX509Certificate(sb, cert);
                    sb.Append("END*************************************************");
                }
            }

            string result = sb.ToString();
            Console.WriteLine(result);
        }

        public static void ShowCertAndChain(X509Certificate2 cert)
        {
            X509Chain chain = new X509Chain();
            chain.ChainPolicy.RevocationFlag = X509RevocationFlag.EntireChain;
            chain.ChainPolicy.RevocationMode = X509RevocationMode.Offline;
            chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllFlags;

            ////chain.ChainPolicy.VerificationFlags = X509VerificationFlags.IgnoreCtlSignerRevocationUnknown &&
            ////X509VerificationFlags.IgnoreRootRevocationUnknown &&
            ////X509VerificationFlags.IgnoreEndRevocationUnknown &&
            ////X509VerificationFlags.IgnoreCertificateAuthorityRevocationUnknown &&
            ////X509VerificationFlags.IgnoreCtlNotTimeValid;

            chain.Build(cert);

            ShowCertAndChain(cert, chain);
        }

        public static void ShowCertAndChain(X509Certificate cert, X509Chain chain)
        {
            StringBuilder sb = new StringBuilder();
            if (null != cert)
            {
                ShowX509Certificate(sb, cert);
            }

            if (null != chain)
            {
                sb.Append("-X509Chain(Start)-" + System.Environment.NewLine);
                ////sb.Append(string.Format("Cert.ChainStatus='{0}'", string.Join(",", chain.ChainStatus.ToList())) + System.Environment.NewLine);

                foreach (X509ChainStatus cstat in chain.ChainStatus)
                {
                    sb.Append(string.Format("X509ChainStatus::'{0}'-'{1}'", cstat.Status.ToString(), cstat.StatusInformation) + System.Environment.NewLine);
                }

                X509ChainElementCollection ces = chain.ChainElements;
                ShowX509ChainElementCollection(sb, ces);
                sb.Append("-X509Chain(End)-" + System.Environment.NewLine);
            }

            string result = sb.ToString();
            Console.WriteLine(result);
        }

        private static void ShowX509Extension(StringBuilder sb, int x509ExtensionCount, X509Extension ext)
        {
            sb.Append(string.Empty + System.Environment.NewLine);
            sb.Append(string.Format("--------X509ExtensionNumber(Start):{0}", x509ExtensionCount) + System.Environment.NewLine);
            sb.Append(string.Format("X509Extension.Critical='{0}'", ext.Critical) + System.Environment.NewLine);

            AsnEncodedData asndata = new AsnEncodedData(ext.Oid, ext.RawData);
            sb.Append(string.Format("Extension type: {0}", ext.Oid.FriendlyName) + System.Environment.NewLine);
            sb.Append(string.Format("Oid value: {0}", asndata.Oid.Value) + System.Environment.NewLine);
            sb.Append(string.Format("Raw data length: {0} {1}", asndata.RawData.Length, Environment.NewLine) + System.Environment.NewLine);
            sb.Append(asndata.Format(true) + System.Environment.NewLine);

            X509BasicConstraintsExtension basicEx = ext as X509BasicConstraintsExtension;
            if (null != basicEx)
            {
                sb.Append("-X509BasicConstraintsExtension-" + System.Environment.NewLine);
                sb.Append(string.Format("X509Extension.X509BasicConstraintsExtension.CertificateAuthority='{0}'", basicEx.CertificateAuthority) + System.Environment.NewLine);
            }

            X509EnhancedKeyUsageExtension keyEx = ext as X509EnhancedKeyUsageExtension;
            if (null != keyEx)
            {
                sb.Append("-X509EnhancedKeyUsageExtension-" + System.Environment.NewLine);
                sb.Append(string.Format("X509Extension.X509EnhancedKeyUsageExtension.EnhancedKeyUsages='{0}'", keyEx.EnhancedKeyUsages) + System.Environment.NewLine);
                foreach (Oid oi in keyEx.EnhancedKeyUsages)
                {
                    sb.Append(string.Format("------------EnhancedKeyUsages.Oid.FriendlyName='{0}'", oi.FriendlyName) + System.Environment.NewLine);
                    sb.Append(string.Format("------------EnhancedKeyUsages.Oid.Value='{0}'", oi.Value) + System.Environment.NewLine);
                }
            }

            X509KeyUsageExtension usageEx = ext as X509KeyUsageExtension;
            if (null != usageEx)
            {
                sb.Append("-X509KeyUsageExtension-" + System.Environment.NewLine);
                sb.Append(string.Format("X509Extension.X509KeyUsageExtension.KeyUsages='{0}'", usageEx.KeyUsages) + System.Environment.NewLine);
                sb.Append(string.Format("X509KeyUsageExtension.KeyUsages.X509KeyUsageFlags.CrlSign='{0}'", (usageEx.KeyUsages & X509KeyUsageFlags.CrlSign) != 0) + System.Environment.NewLine);
                sb.Append(string.Format("X509KeyUsageExtension.KeyUsages.X509KeyUsageFlags.DataEncipherment='{0}'", (usageEx.KeyUsages & X509KeyUsageFlags.DataEncipherment) != 0) + System.Environment.NewLine);
                sb.Append(string.Format("X509KeyUsageExtension.KeyUsages.X509KeyUsageFlags.DecipherOnly='{0}'", (usageEx.KeyUsages & X509KeyUsageFlags.DecipherOnly) != 0) + System.Environment.NewLine);
                sb.Append(string.Format("X509KeyUsageExtension.KeyUsages.X509KeyUsageFlags.DigitalSignature='{0}'", (usageEx.KeyUsages & X509KeyUsageFlags.DigitalSignature) != 0) + System.Environment.NewLine);
                sb.Append(string.Format("X509KeyUsageExtension.KeyUsages.X509KeyUsageFlags.EncipherOnly='{0}'", (usageEx.KeyUsages & X509KeyUsageFlags.EncipherOnly) != 0) + System.Environment.NewLine);
                sb.Append(string.Format("X509KeyUsageExtension.KeyUsages.X509KeyUsageFlags.KeyAgreement='{0}'", (usageEx.KeyUsages & X509KeyUsageFlags.KeyAgreement) != 0) + System.Environment.NewLine);
                sb.Append(string.Format("X509KeyUsageExtension.KeyUsages.X509KeyUsageFlags.KeyCertSign='{0}'", (usageEx.KeyUsages & X509KeyUsageFlags.KeyCertSign) != 0) + System.Environment.NewLine);
                sb.Append(string.Format("X509KeyUsageExtension.KeyUsages.X509KeyUsageFlags.KeyEncipherment='{0}'", (usageEx.KeyUsages & X509KeyUsageFlags.KeyEncipherment) != 0) + System.Environment.NewLine);
                sb.Append(string.Format("X509KeyUsageExtension.KeyUsages.X509KeyUsageFlags.None='{0}'", (usageEx.KeyUsages & X509KeyUsageFlags.None) != 0) + System.Environment.NewLine);
                sb.Append(string.Format("X509KeyUsageExtension.KeyUsages.X509KeyUsageFlags.NonRepudiation='{0}'", (usageEx.KeyUsages & X509KeyUsageFlags.NonRepudiation) != 0) + System.Environment.NewLine);
            }

            X509SubjectKeyIdentifierExtension skIdEx = ext as X509SubjectKeyIdentifierExtension;
            if (null != skIdEx)
            {
                sb.Append("-X509SubjectKeyIdentifierExtension-" + System.Environment.NewLine);
                sb.Append(string.Format("X509Extension.X509SubjectKeyIdentifierExtension.Oid='{0}'", skIdEx.Oid) + System.Environment.NewLine);
                sb.Append(string.Format("X509Extension.X509SubjectKeyIdentifierExtension.SubjectKeyIdentifier='{0}'", skIdEx.SubjectKeyIdentifier) + System.Environment.NewLine);
            }

            sb.Append(string.Format("--------X509ExtensionNumber(End):{0}", x509ExtensionCount) + System.Environment.NewLine);
        }

        private static void ShowX509Extensions(StringBuilder sb, string cert2SubjectName, X509ExtensionCollection extColl)
        {
            int x509ExtensionCount = 0;
            sb.Append(string.Format("--------ShowX509Extensions(Start):for:{0}", cert2SubjectName) + System.Environment.NewLine);
            foreach (X509Extension ext in extColl)
            {
                ShowX509Extension(sb, ++x509ExtensionCount, ext);
            }

            sb.Append(string.Format("--------ShowX509Extensions(End):for:{0}", cert2SubjectName) + System.Environment.NewLine);
        }

        private static void ShowX509Certificate2(StringBuilder sb, X509Certificate2 cert2)
        {
            if (null != cert2)
            {
                sb.Append(string.Format("X509Certificate2.SubjectName.Name='{0}'", cert2.SubjectName.Name) + System.Environment.NewLine);
                sb.Append(string.Format("X509Certificate2.Subject='{0}'", cert2.Subject) + System.Environment.NewLine);
                sb.Append(string.Format("X509Certificate2.Thumbprint='{0}'", cert2.Thumbprint) + System.Environment.NewLine);
                sb.Append(string.Format("X509Certificate2.HasPrivateKey='{0}'", cert2.HasPrivateKey) + System.Environment.NewLine);
                sb.Append(string.Format("X509Certificate2.Version='{0}'", cert2.Version) + System.Environment.NewLine);
                sb.Append(string.Format("X509Certificate2.NotBefore='{0}'", cert2.NotBefore) + System.Environment.NewLine);
                sb.Append(string.Format("X509Certificate2.NotAfter='{0}'", cert2.NotAfter) + System.Environment.NewLine);
                sb.Append(string.Format("X509Certificate2.PublicKey.Key.KeySize='{0}'", cert2.PublicKey.Key.KeySize) + System.Environment.NewLine);

                ////List<X509KeyUsageExtension> keyUsageExtensions = cert2.Extensions.OfType<X509KeyUsageExtension>().ToList();
                ////List<X509Extension> extensions = cert2.Extensions.OfType<X509Extension>().ToList();

                ShowX509Extensions(sb, cert2.Subject, cert2.Extensions);
            }
        }

        private static void ShowX509ChainElementCollection(StringBuilder sb, X509ChainElementCollection ces)
        {
            int x509ChainElementCount = 0;
            foreach (X509ChainElement ce in ces)
            {
                sb.Append(string.Empty + System.Environment.NewLine);
                sb.Append(string.Format("----X509ChainElementNumber:{0}", ++x509ChainElementCount) + System.Environment.NewLine);
                sb.Append(string.Format("X509ChainElement.Cert.SubjectName.Name='{0}'", ce.Certificate.SubjectName.Name) + System.Environment.NewLine);
                sb.Append(string.Format("X509ChainElement.Cert.Issuer='{0}'", ce.Certificate.Issuer) + System.Environment.NewLine);
                sb.Append(string.Format("X509ChainElement.Cert.Thumbprint='{0}'", ce.Certificate.Thumbprint) + System.Environment.NewLine);
                sb.Append(string.Format("X509ChainElement.Cert.HasPrivateKey='{0}'", ce.Certificate.HasPrivateKey) + System.Environment.NewLine);

                X509Certificate2 cert2 = ce.Certificate as X509Certificate2;
                ShowX509Certificate2(sb, cert2);

                ShowX509Extensions(sb, cert2.Subject, ce.Certificate.Extensions);
            }
        }

        private static void ShowX509Certificate(StringBuilder sb, X509Certificate cert)
        {
            sb.Append("-----------------------------------------------" + System.Environment.NewLine);
            sb.Append(string.Format("Cert.Subject='{0}'", cert.Subject) + System.Environment.NewLine);
            sb.Append(string.Format("Cert.Issuer='{0}'", cert.Issuer) + System.Environment.NewLine);

            sb.Append(string.Format("Cert.GetPublicKey().Length='{0}'", cert.GetPublicKey().Length) + System.Environment.NewLine);

            X509Certificate2 cert2 = cert as X509Certificate2;
            ShowX509Certificate2(sb, cert2);
        }
    }
}

How do you execute SQL from within a bash script?

If you do not want to install sqlplus on your server/machine then the following command-line tool can be your friend. It is a simple Java application, only Java 8 that you need in order to you can execute this tool.

The tool can be used to run any SQL from the Linux bash or Windows command line.

Example:

java -jar sql-runner-0.2.0-with-dependencies.jar \
     -j jdbc:oracle:thin:@//oracle-db:1521/ORCLPDB1.localdomain \
     -U "SYS as SYSDBA" \
     -P Oradoc_db1 \
      "select 1 from dual"

Documentation is here.

You can download the binary file from here.

Running CMake on Windows

There is a vcvars32.bat in your Visual Studio installation directory. You can add call cmd.exe at the end of that batch program and launch it. From that shell you can use CMake or cmake-gui and cl.exe would be known to CMake.

How to send a JSON object using html form data

HTML provides no way to generate JSON from form data.

If you really want to handle it from the client, then you would have to resort to using JavaScript to:

  1. gather your data from the form via DOM
  2. organise it in an object or array
  3. generate JSON with JSON.stringify
  4. POST it with XMLHttpRequest

You'd probably be better off sticking to application/x-www-form-urlencoded data and processing that on the server instead of JSON. Your form doesn't have any complicated hierarchy that would benefit from a JSON data structure.


Update in response to major rewrite of the question…

  • Your JS has no readystatechange handler, so you do nothing with the response
  • You trigger the JS when the submit button is clicked without cancelling the default behaviour. The browser will submit the form (in the regular way) as soon as the JS function is complete.

How do I create a SQL table under a different schema?

  1. Right-click on the tables node and choose New Table...
  2. With the table designer open, open the properties window (view -> Properties Window).
  3. You can change the schema that the table will be made in by choosing a schema in the properties window.

How to echo (or print) to the js console with php

There are much better ways to print variable's value in PHP. One of them is to use buildin var_dump() function. If you want to use var_dump(), I would also suggest to install Xdebug (from https://xdebug.org) since it generates much more readable printouts.

The idea of printing values to browser console is somewhat bizarre, but if you really want to use it, there is very useful Google Chrome extension, PHP Console, which should satisfy all your needs. You can find it at consle.com It works well also in Vivaldi and in Opera (though you will need "Download Chrome Extension" extension to install it). The extension is accompanied by PHP library you use in your code.

Refresh Part of Page (div)

Let's assume that you have 2 divs inside of your html file.

<div id="div1">some text</div>
<div id="div2">some other text</div>

The java program itself can't update the content of the html file because the html is related to the client, meanwhile java is related to the back-end.

You can, however, communicate between the server (the back-end) and the client.

What we're talking about is AJAX, which you achieve using JavaScript, I recommend using jQuery which is a common JavaScript library.

Let's assume you want to refresh the page every constant interval, then you can use the interval function to repeat the same action every x time.

setInterval(function()
{
    alert("hi");
}, 30000);

You could also do it like this:

setTimeout(foo, 30000);

Whereea foo is a function.

Instead of the alert("hi") you can perform the AJAX request, which sends a request to the server and receives some information (for example the new text) which you can use to load into the div.

A classic AJAX looks like this:

var fetch = true;
var url = 'someurl.java';
$.ajax(
{
    // Post the variable fetch to url.
    type : 'post',
    url : url,
    dataType : 'json', // expected returned data format.
    data : 
    {
        'fetch' : fetch // You might want to indicate what you're requesting.
    },
    success : function(data)
    {
        // This happens AFTER the backend has returned an JSON array (or other object type)
        var res1, res2;

        for(var i = 0; i < data.length; i++)
        {
            // Parse through the JSON array which was returned.
            // A proper error handling should be added here (check if
            // everything went successful or not)

            res1 = data[i].res1;
            res2 = data[i].res2;

            // Do something with the returned data
            $('#div1').html(res1);
        }
    },
    complete : function(data)
    {
        // do something, not critical.
    }
});

Wherea the backend is able to receive POST'ed data and is able to return a data object of information, for example (and very preferrable) JSON, there are many tutorials out there with how to do so, GSON from Google is something that I used a while back, you could take a look into it.

I'm not professional with Java POST receiving and JSON returning of that sort so I'm not going to give you an example with that but I hope this is a decent start.

Convert NSArray to NSString in Objective-C

The way I know is easy.

var NSArray_variable = NSArray_Object[n]
var stringVarible = NSArray_variable as String

n is the inner position in the array This in SWIFT Language. It might work in Objective C

Set initially selected item in Select list in Angular2

The easiest way to solve this problem in Angular is to do:

In Template:

<select [ngModel]="selectedObjectIndex">
  <option [value]="i" *ngFor="let object of objects; let i = index;">{{object.name}}</option>
</select>

In your class:

this.selectedObjectIndex = 1/0/your number wich item should be selected

What's the difference between deadlock and livelock?

I just planned to share some knowledge.

Deadlocks A set of threads/processes is deadlocked, if each thread/process in the set is waiting for an event that only another process in the set can cause.

The important thing here is another process is also in the same set. that means another process also blocked and no one can proceed.

Deadlocks occur when processes are granted exclusive access to resources.

These four conditions should be satisfied to have a deadlock.

  1. Mutual exclusion condition (Each resource is assigned to 1 process)
  2. Hold and wait condition (Process holding resources and at the same time it can ask other resources).
  3. No preemption condition (Previously granted resources can not forcibly be taken away) #This condition depends on the application
  4. Circular wait condition (Must be a circular chain of 2 or more processes and each is waiting for resource held by the next member of the chain) # It will happen dynamically

If we found these conditions then we can say there may be occurred a situation like a deadlock.

LiveLock

Each thread/process is repeating the same state again and again but doesn't progress further. Something similar to a deadlock since the process can not enter the critical section. However in a deadlock, processes are wait without doing anything but in livelock, the processes are trying to proceed but processes are repeated to the same state again and again.

(In a deadlocked computation there is no possible execution sequence which succeeds. but In a livelocked computation, there are successful computations, but there are one or more execution sequences in which no process enters its critical section.)

Difference from deadlock and livelock

When deadlock happens, No execution will happen. but in livelock, some executions will happen but those executions are not enough to enter the critical section.

Facebook API "This app is in development mode"

  • Development mode is for testing
  • Go to https://developers.facebook.com/apps, then App Review -> Select No for Your app is in development and unavailable to the public
  • Go to Roles -> Testers, enter the Facebook user Id of the users you want to enable testing

Add User to Role ASP.NET Identity

I found good answer here Adding Role dynamically in new VS 2013 Identity UserManager

But in case to provide an example so you can check it I am gonna share some default code.

First make sure you have Roles inserted.

enter image description here

And second test it on user register method.

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
    if (ModelState.IsValid)
    {
        var user = new ApplicationUser() { UserName = model.UserName  };

        var result = await UserManager.CreateAsync(user, model.Password);
        if (result.Succeeded)
        {
            var currentUser = UserManager.FindByName(user.UserName); 

            var roleresult = UserManager.AddToRole(currentUser.Id, "Superusers");

            await SignInAsync(user, isPersistent: false);
            return RedirectToAction("Index", "Home");
        }
        else
        {
            AddErrors(result);
        }
    }

    // If we got this far, something failed, redisplay form
    return View(model);
}

And finally you have to get "Superusers" from the Roles Dropdown List somehow.

How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?

You can call the get() method of AsyncTask (or the overloaded get(long, TimeUnit)). This method will block until the AsyncTask has completed its work, at which point it will return you the Result.

It would be wise to be doing other work between the creation/start of your async task and calling the get method, otherwise you aren't utilizing the async task very efficiently.

Iterating through a List Object in JSP

change the code to the following

<%! List eList = (ArrayList)session.getAttribute("empList");%>
....
<table>
    <%
    for(int i=0; i<eList.length;i++){%>
        <tr>
            <td><%= ((Employee)eList[i]).getEid() %></td>
            <td><%= ((Employee)eList[i]).getEname() %></td>  
        </tr>
      <%}%>
</table>

What is the boundary in multipart/form-data?

The exact answer to the question is: yes, you can use an arbitrary value for the boundary parameter, given it does not exceed 70 bytes in length and consists only of 7-bit US-ASCII (printable) characters.

If you are using one of multipart/* content types, you are actually required to specify the boundary parameter in the Content-Type header, otherwise the server (in the case of an HTTP request) will not be able to parse the payload.

You probably also want to set the charset parameter to UTF-8 in your Content-Type header, unless you can be absolutely sure that only US-ASCII charset will be used in the payload data.

A few relevant excerpts from the RFC2046:

  • 4.1.2. Charset Parameter:

    Unlike some other parameter values, the values of the charset parameter are NOT case sensitive. The default character set, which must be assumed in the absence of a charset parameter, is US-ASCII.

  • 5.1. Multipart Media Type

    As stated in the definition of the Content-Transfer-Encoding field [RFC 2045], no encoding other than "7bit", "8bit", or "binary" is permitted for entities of type "multipart". The "multipart" boundary delimiters and header fields are always represented as 7bit US-ASCII in any case (though the header fields may encode non-US-ASCII header text as per RFC 2047) and data within the body parts can be encoded on a part-by-part basis, with Content-Transfer-Encoding fields for each appropriate body part.

    The Content-Type field for multipart entities requires one parameter, "boundary". The boundary delimiter line is then defined as a line consisting entirely of two hyphen characters ("-", decimal value 45) followed by the boundary parameter value from the Content-Type header field, optional linear whitespace, and a terminating CRLF.

    Boundary delimiters must not appear within the encapsulated material, and must be no longer than 70 characters, not counting the two leading hyphens.

    The boundary delimiter line following the last body part is a distinguished delimiter that indicates that no further body parts will follow. Such a delimiter line is identical to the previous delimiter lines, with the addition of two more hyphens after the boundary parameter value.

Here is an example using an arbitrary boundary:

Content-Type: multipart/form-data; charset=utf-8; boundary="another cool boundary"

--another cool boundary
Content-Disposition: form-data; name="foo"

bar
--another cool boundary
Content-Disposition: form-data; name="baz"

quux
--another cool boundary--

How to force IE to reload javascript?

In javascript I think that it is not possible, because modern browsers have a policy on security in javascripts.. and clearing the cache is a very violating one.

You can try to add

<META HTTP-EQUIV="Pragma" CONTENT="no-cache">

In your header, but you will have performance loss.

Android Studio - How to increase Allocated Heap Size

Note: I now this is not the answer for the post, but maybe this will be helpful for some one that is looking.

If Nothing of this works for you, try on a Mac this to see if helps you, in the last version of Android Studio, the studio.vmoptions is inside the AndroidStudio.app in your Applications folder.

So right click or ctrl click on your AndroidStudio.App and then select show package content the studio.vmoptions is in:

Contents/bin/studio.vmoptions

Replace or change it and you will get all the RAM you need.

enter image description here enter image description here

Regards.

How to prettyprint a JSON file?

I think that's better to parse the json before, to avoid errors:

def format_response(response):
    try:
        parsed = json.loads(response.text)
    except JSONDecodeError:
        return response.text
    return json.dumps(parsed, ensure_ascii=True, indent=4)

Exposing the current state name with ui router

I wrapped around $state around $timeout and it worked for me.

For example,

(function() {
  'use strict';

  angular
    .module('app')
    .controller('BodyController', BodyController);

  BodyController.$inject = ['$state', '$timeout'];

  /* @ngInject */
  function BodyController($state, $timeout) {
    $timeout(function(){
      console.log($state.current);
    });

  }
})();

How to format date with hours, minutes and seconds when using jQuery UI Datepicker?

Try this fiddle

$(function() {
    $('#datepicker').datepicker({
        dateFormat: 'yy-dd-mm',
        onSelect: function(datetext) {
            var d = new Date(); // for now

            var h = d.getHours();
            h = (h < 10) ? ("0" + h) : h ;

            var m = d.getMinutes();
            m = (m < 10) ? ("0" + m) : m ;

            var s = d.getSeconds();
            s = (s < 10) ? ("0" + s) : s ;

            datetext = datetext + " " + h + ":" + m + ":" + s;

            $('#datepicker').val(datetext);
        }
    });
});

About catching ANY exception

There are multiple ways to do this in particular with Python 3.0 and above

Approach 1

This is simple approach but not recommended because you would not know exactly which line of code is actually throwing the exception:

def bad_method():
    try:
        sqrt = 0**-1
    except Exception as e:
        print(e)

bad_method()

Approach 2

This approach is recommended because it provides more detail about each exception. It includes:

  • Line number for your code
  • File name
  • The actual error in more verbose way

The only drawback is tracback needs to be imported.

import traceback

def bad_method():
    try:
        sqrt = 0**-1
    except Exception:
        print(traceback.print_exc())

bad_method()

How do you print in Sublime Text 2

Still no print no native print function, but outside the installing the suggested package, you can go the autohotkey way, as the that app can actually help you run macros for other stuff as well. So you can do something like create a macro that with one click does:

  1. Select all the text
  2. Copies all the text
  3. Opens your other edit of choice
  4. pastes text
  5. Prints text

No the most glamorous of options but could also work if the receiving app has can accept code-formatting.

How to write header row with csv.DictWriter?

A few options:

(1) Laboriously make an identity-mapping (i.e. do-nothing) dict out of your fieldnames so that csv.DictWriter can convert it back to a list and pass it to a csv.writer instance.

(2) The documentation mentions "the underlying writer instance" ... so just use it (example at the end).

dw.writer.writerow(dw.fieldnames)

(3) Avoid the csv.Dictwriter overhead and do it yourself with csv.writer

Writing data:

w.writerow([d[k] for k in fieldnames])

or

w.writerow([d.get(k, restval) for k in fieldnames])

Instead of the extrasaction "functionality", I'd prefer to code it myself; that way you can report ALL "extras" with the keys and values, not just the first extra key. What is a real nuisance with DictWriter is that if you've verified the keys yourself as each dict was being built, you need to remember to use extrasaction='ignore' otherwise it's going to SLOWLY (fieldnames is a list) repeat the check:

wrong_fields = [k for k in rowdict if k not in self.fieldnames]

============

>>> f = open('csvtest.csv', 'wb')
>>> import csv
>>> fns = 'foo bar zot'.split()
>>> dw = csv.DictWriter(f, fns, restval='Huh?')
# dw.writefieldnames(fns) -- no such animal
>>> dw.writerow(fns) # no such luck, it can't imagine what to do with a list
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\python26\lib\csv.py", line 144, in writerow
    return self.writer.writerow(self._dict_to_list(rowdict))
  File "C:\python26\lib\csv.py", line 141, in _dict_to_list
    return [rowdict.get(key, self.restval) for key in self.fieldnames]
AttributeError: 'list' object has no attribute 'get'
>>> dir(dw)
['__doc__', '__init__', '__module__', '_dict_to_list', 'extrasaction', 'fieldnam
es', 'restval', 'writer', 'writerow', 'writerows']
# eureka
>>> dw.writer.writerow(dw.fieldnames)
>>> dw.writerow({'foo':'oof'})
>>> f.close()
>>> open('csvtest.csv', 'rb').read()
'foo,bar,zot\r\noof,Huh?,Huh?\r\n'
>>>

How are zlib, gzip and zip related? What do they have in common and how are they different?

ZIP is a file format used for storing an arbitrary number of files and folders together with lossless compression. It makes no strict assumptions about the compression methods used, but is most frequently used with DEFLATE.

Gzip is both a compression algorithm based on DEFLATE but less encumbered with potential patents et al, and a file format for storing a single compressed file. It supports compressing an arbitrary number of files and folders when combined with tar. The resulting file has an extension of .tgz or .tar.gz and is commonly called a tarball.

zlib is a library of functions encapsulating DEFLATE in its most common LZ77 incarnation.

Error 1053 the service did not respond to the start or control request in a timely fashion

In my case, I was publishing service while it was in debug mode.

Solution was:

  • Changing solution to release mode
  • Uninstall old service with command InstallUtil -u WindowsServiceName.exe
  • installing service again InstallUtil -i WindowsServiceName.exe

It worked perfectly after.

How to implement a ConfigurationSection with a ConfigurationElementCollection

If you are looking for a custom configuration section like following

<CustomApplicationConfig>
        <Credentials Username="itsme" Password="mypassword"/>
        <PrimaryAgent Address="10.5.64.26" Port="3560"/>
        <SecondaryAgent Address="10.5.64.7" Port="3570"/>
        <Site Id="123" />
        <Lanes>
          <Lane Id="1" PointId="north" Direction="Entry"/>
          <Lane Id="2" PointId="south" Direction="Exit"/>
        </Lanes> 
</CustomApplicationConfig>

then you can use my implementation of configuration section so to get started add System.Configuration assembly reference to your project

Look at the each nested elements I used, First one is Credentials with two attributes so lets add it first

Credentials Element

public class CredentialsConfigElement : System.Configuration.ConfigurationElement
    {
        [ConfigurationProperty("Username")]
        public string Username
        {
            get 
            {
                return base["Username"] as string;
            }
        }

        [ConfigurationProperty("Password")]
        public string Password
        {
            get
            {
                return base["Password"] as string;
            }
        }
    }

PrimaryAgent and SecondaryAgent

Both has the same attributes and seem like a Address to a set of servers for a primary and a failover, so you just need to create one element class for both of those like following

public class ServerInfoConfigElement : ConfigurationElement
    {
        [ConfigurationProperty("Address")]
        public string Address
        {
            get
            {
                return base["Address"] as string;
            }
        }

        [ConfigurationProperty("Port")]
        public int? Port
        {
            get
            {
                return base["Port"] as int?;
            }
        }
    }

I'll explain how to use two different element with one class later in this post, let us skip the SiteId as there is no difference in it. You just have to create one class same as above with one property only. let us see how to implement Lanes collection

it is splitted in two parts first you have to create an element implementation class then you have to create collection element class

LaneConfigElement

public class LaneConfigElement : ConfigurationElement
    {
        [ConfigurationProperty("Id")]
        public string Id
        {
            get
            {
                return base["Id"] as string;
            }
        }

        [ConfigurationProperty("PointId")]
        public string PointId
        {
            get
            {
                return base["PointId"] as string;
            }
        }

        [ConfigurationProperty("Direction")]
        public Direction? Direction
        {
            get
            {
                return base["Direction"] as Direction?;
            }
        }
    }

    public enum Direction
    { 
        Entry,
        Exit
    }

you can notice that one attribute of LanElement is an Enumeration and if you try to use any other value in configuration which is not defined in Enumeration application will throw an System.Configuration.ConfigurationErrorsException on startup. Ok lets move on to Collection Definition

[ConfigurationCollection(typeof(LaneConfigElement), AddItemName = "Lane", CollectionType = ConfigurationElementCollectionType.BasicMap)]
    public class LaneConfigCollection : ConfigurationElementCollection
    {
        public LaneConfigElement this[int index]
        {
            get { return (LaneConfigElement)BaseGet(index); }
            set
            {
                if (BaseGet(index) != null)
                {
                    BaseRemoveAt(index);
                }
                BaseAdd(index, value);
            }
        }

        public void Add(LaneConfigElement serviceConfig)
        {
            BaseAdd(serviceConfig);
        }

        public void Clear()
        {
            BaseClear();
        }

        protected override ConfigurationElement CreateNewElement()
        {
            return new LaneConfigElement();
        }

        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((LaneConfigElement)element).Id;
        }

        public void Remove(LaneConfigElement serviceConfig)
        {
            BaseRemove(serviceConfig.Id);
        }

        public void RemoveAt(int index)
        {
            BaseRemoveAt(index);
        }

        public void Remove(String name)
        {
            BaseRemove(name);
        }

    }

you can notice that I have set the AddItemName = "Lane" you can choose whatever you like for your collection entry item, i prefer to use "add" the default one but i changed it just for the sake of this post.

Now all of our nested Elements have been implemented now we should aggregate all of those in a class which has to implement System.Configuration.ConfigurationSection

CustomApplicationConfigSection

public class CustomApplicationConfigSection : System.Configuration.ConfigurationSection
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(CustomApplicationConfigSection));
        public const string SECTION_NAME = "CustomApplicationConfig";

        [ConfigurationProperty("Credentials")]
        public CredentialsConfigElement Credentials
        {
            get
            {
                return base["Credentials"] as CredentialsConfigElement;
            }
        }

        [ConfigurationProperty("PrimaryAgent")]
        public ServerInfoConfigElement PrimaryAgent
        {
            get
            {
                return base["PrimaryAgent"] as ServerInfoConfigElement;
            }
        }

        [ConfigurationProperty("SecondaryAgent")]
        public ServerInfoConfigElement SecondaryAgent
        {
            get
            {
                return base["SecondaryAgent"] as ServerInfoConfigElement;
            }
        }

        [ConfigurationProperty("Site")]
        public SiteConfigElement Site
        {
            get
            {
                return base["Site"] as SiteConfigElement;
            }
        }

        [ConfigurationProperty("Lanes")]
        public LaneConfigCollection Lanes
        {
            get { return base["Lanes"] as LaneConfigCollection; }
        }
    }

Now you can see that we have two properties with name PrimaryAgent and SecondaryAgent both have the same type now you can easily understand why we had only one implementation class against these two element.

Before you can use this newly invented configuration section in your app.config (or web.config) you just need to tell you application that you have invented your own configuration section and give it some respect, to do so you have to add following lines in app.config (may be right after start of root tag).

<configSections>
    <section name="CustomApplicationConfig" type="MyNameSpace.CustomApplicationConfigSection, MyAssemblyName" />
  </configSections>

NOTE: MyAssemblyName should be without .dll e.g. if you assembly file name is myDll.dll then use myDll instead of myDll.dll

to retrieve this configuration use following line of code any where in your application

CustomApplicationConfigSection config = System.Configuration.ConfigurationManager.GetSection(CustomApplicationConfigSection.SECTION_NAME) as CustomApplicationConfigSection;

I hope above post would help you to get started with a bit complicated kind of custom config sections.

Happy Coding :)

****Edit**** To Enable LINQ on LaneConfigCollection you have to implement IEnumerable<LaneConfigElement>

And Add following implementation of GetEnumerator

public new IEnumerator<LaneConfigElement> GetEnumerator()
        {
            int count = base.Count;
            for (int i = 0; i < count; i++)
            {
                yield return base.BaseGet(i) as LaneConfigElement;
            }
        }

for the people who are still confused about how yield really works read this nice article

Two key points taken from above article are

it doesn’t really end the method’s execution. yield return pauses the method execution and the next time you call it (for the next enumeration value), the method will continue to execute from the last yield return call. It sounds a bit confusing I think… (Shay Friedman)

Yield is not a feature of the .Net runtime. It is just a C# language feature which gets compiled into simple IL code by the C# compiler. (Lars Corneliussen)

How to find which version of Oracle is installed on a Linux server (In terminal)

Enter in sqlplus (you'll see the version number)

# su - oracle

oracle# sqlplus

OR

echo $ORAHOME

Will give you the path where Oracle installed and path will include version number.

OR

Connect to Oracle DB and run

select * from v$version where banner like 'oracle%';

android set button background programmatically

Old thread, but learned something new, hope this might help someone.

If you want to change the background color but retain other styles, then below might help.

button.getBackground().setColorFilter(ContextCompat.getColor(this, R.color.colorAccent), PorterDuff.Mode.MULTIPLY);

Typescript empty object for a typed variable

user: USER

this.user = ({} as USER)

How can I get query string values in JavaScript?

Get all querystring parameters including checkbox values (arrays).

Considering the correct & normal use of GET parameters, the things I see it's missing, on most functions, is the support for arrays and removing the hash data.

So I wrote this function:

function qs(a){
 if(!a)return {};
 a=a.split('#')[0].split('&');
 var b=a.length,c={},d,k,v;
 while(b--){
  d=a[b].split('=');
  k=d[0].replace('[]',''),v=decodeURIComponent(d[1]||'');
  c[k]?typeof c[k]==='string'?(c[k]=[v,c[k]]):(c[k].unshift(v)):c[k]=v;
 }
 return c
}

Using shorthand operators & while-- loop, the performance should be very good to.

Support:

  1. Empty values (key= / key)
  2. Key value (key=value)
  3. Arrays (key[]=value)
  4. Hash (the hash tag is split out)

Notes:

It does not support object arrays (key[key]=value)

If the space is + it remains a +.

Add .replace(/\+/g, " ") if you need.

Usage:

qs('array[]=1&array[]=2&key=value&empty=&empty2#hash')

Return:

{
    "empty": "",
    "key": "value",
    "array": [
        "1",
        "2"
    ]
}

Demo:

http://jsfiddle.net/ZQMrt/1/

Info

If you don't understand something or you can't read the function just ask. I'm happy to explain what I did here.

If you think the function is unreadable and unmaintainable I'm happy to rewrite the function for you, but consider that shorthand & bitwise operators are always faster than a standard syntax (maybe read about shorthands and bitwise operators in the ECMA-262 book or use your favorite search engine). Rewriting the code in a standard readable syntax means performance loss.

How to store an output of shell script to a variable in Unix?

export a=$(script.sh)

Hope this helps. Note there are no spaces between variable and =. To echo the output

echo $a

EF Code First "Invalid column name 'Discriminator'" but no inheritance

I just encountered this and my problem was caused by having two entities both with the System.ComponentModel.DataAnnotations.Schema.TableAttribute referring to the same table.

for example:

[Table("foo")]
public class foo
{
    // some stuff here
}

[Table("foo")]
public class fooExtended
{
    // more stuff here
}

changing the second one from foo to foo_extended fixed this for me and I'm now using Table Per Type (TPT)

Zip folder in C#

ComponentPro ZIP can help you achieve that task. The following code snippet compress files and dirs in a folder. You can use wilcard mask as well.

using ComponentPro.Compression;
using ComponentPro.IO;

...

// Create a new instance.
Zip zip = new Zip();
// Create a new zip file.
zip.Create("test.zip");

zip.Add(@"D:\Temp\Abc"); // Add entire D:\Temp\Abc folder to the archive.

// Add all files and subdirectories from 'c:\test' to the archive.
zip.AddFiles(@"c:\test");
// Add all files and subdirectories from 'c:\my folder' to the archive.
zip.AddFiles(@"c:\my folder", "");
// Add all files and subdirectories from 'c:\my folder' to '22' folder within the archive.
zip.AddFiles(@"c:\my folder2", "22");
// Add all .dat files from 'c:\my folder' to '22' folder within the archive.
zip.AddFiles(@"c:\my folder2", "22", "*.dat");
// Or simply use this to add all .dat files from 'c:\my folder' to '22' folder within the archive.
zip.AddFiles(@"c:\my folder2\*.dat", "22");
// Add *.dat and *.exe files from 'c:\my folder' to '22' folder within the archive.
zip.AddFiles(@"c:\my folder2\*.dat;*.exe", "22");

TransferOptions opt = new TransferOptions();
// Donot add empty directories.
opt.CreateEmptyDirectories = false;
zip.AddFiles(@"c:\abc", "/", opt);

// Close the zip file.
zip.Close();

http://www.componentpro.com/doc/zip has more examples

Enable UTF-8 encoding for JavaScript

thanks friends, after trying all and not getting desired result i think to use a hidden div with that arabic message and with jQuery fading affects solved the problem. Script I wrote is: .js file

$('#enterOpeningPrice').fadeIn();
$('#enterOpeningPrice').fadeOut(10000);

.html file

<div id="enterOpeningPrice">
    <p>???? ??? ????????</p>
</div>

Thanks to all..

How do I convert a list into a string with spaces in Python?

Why don't you add a space in the items of the list itself, like :
list = ["how ", "are ", "you "]

Passing multiple variables to another page in url

Use the ampersand & to glue variables together:

$url = "http://localhost/main.php?email=$email_address&event_id=$event_id";
//                               ^ start of vars      ^next var

Date ticks and rotation in matplotlib

Simply use

ax.set_xticklabels(label_list, rotation=45)

Create an instance of a class from a string

For instance, if you store values of various types in a database field (stored as string) and have another field with the type name (i.e., String, bool, int, MyClass), then from that field data, you could, conceivably, create a class of any type using the above code, and populate it with the value from the first field. This of course depends on the type you are storing having a method to parse strings into the correct type. I've used this many times to store user preference settings in a database.

Which passwordchar shows a black dot (•) in a winforms textbox?

Below are some different ways to achieve this. Pick the one suits you

  1. In fonts like 'Tahoma' and 'Times new Roman' this common password character '?' which is called 'Black circle' has a unicode value 0x25CF. Set the PasswordChar property with either the value 0x25CF or copy paste the actual character itself.

  2. If you want to display the Black Circle by default then enable visual styles which should replace the default password character from '*' to '?' by default irrespective of the font.

  3. Another alternative is to use 'Wingdings 2' font on the TextBox and set the password character to 0x97. This should work even if the application is not unicoded. Refer to charMap.exe to get better idea on different fonts and characters supported.

How to put/get multiple JSONObjects to JSONArray?

Once you have put the values into the JSONObject then put the JSONObject into the JSONArray staright after.

Something like this maybe:

jsonObj.put("value1", 1);
jsonObj.put("value2", 900);
jsonObj.put("value3", 1368349);
jsonArray.put(jsonObj);

Then create new JSONObject, put the other values into it and add it to the JSONArray:

jsonObj.put("value1", 2);
jsonObj.put("value2", 1900);
jsonObj.put("value3", 136856);
jsonArray.put(jsonObj);

How can I show figures separately in matplotlib?

Sure. Add an Axes using add_subplot. (Edited import.) (Edited show.)

import matplotlib.pyplot as plt
f1 = plt.figure()
f2 = plt.figure()
ax1 = f1.add_subplot(111)
ax1.plot(range(0,10))
ax2 = f2.add_subplot(111)
ax2.plot(range(10,20))
plt.show()

Alternatively, use add_axes.

ax1 = f1.add_axes([0.1,0.1,0.8,0.8])
ax1.plot(range(0,10))
ax2 = f2.add_axes([0.1,0.1,0.8,0.8])
ax2.plot(range(10,20))

Get all mysql selected rows into an array

you can call mysql_fetch_array() for no_of_row time

How to make <label> and <input> appear on the same line on an HTML form?

This thing works well.It put radio button or checkbox with label in same line without any css. <label><input type="radio" value="new" name="filter">NEW</label> <label><input type="radio" value="wow" name="filter">WOW</label>

Convert unix time to readable date in pandas dataframe

Assuming we imported pandas as pd and df is our dataframe

pd.to_datetime(df['date'], unit='s')

works for me.

Unresolved external symbol on static class members

If you are using C++ 17 you can just use the inline specifier (see https://stackoverflow.com/a/11711082/55721)


If using older versions of the C++ standard, you must add the definitions to match your declarations of X and Y

unsigned char test::X;
unsigned char test::Y;

somewhere. You might want to also initialize a static member

unsigned char test::X = 4;

and again, you do that in the definition (usually in a CXX file) not in the declaration (which is often in a .H file)

How can I change the version of npm using nvm?

What about npm i -g npm? Did you try to run this as well?

PostgreSQL Crosstab Query

Crosstab function is available under the tablefunc extension. You'll have to create this extension one time for the database.

CREATE EXTENSION tablefunc;

You can use the below code to create pivot table using cross tab:

create table test_Crosstab( section text,
<br/>status text,
<br/>count numeric)

<br/>insert into test_Crosstab values ( 'A','Active',1)
                <br/>,( 'A','Inactive',2)
                <br/>,( 'B','Active',4)
                <br/>,( 'B','Inactive',5)

select * from crosstab(
<br/>'select section
    <br/>,status
    <br/>,count
    <br/>from test_crosstab'
    <br/>)as ctab ("Section" text,"Active" numeric,"Inactive" numeric)

MySQL select with CONCAT condition

Use CONCAT_WS().

SELECT CONCAT_WS(' ',firstname,lastname) as firstlast FROM users 
WHERE firstlast = "Bob Michael Jones";

The first argument is the separator for the rest of the arguments.

Build unsigned APK file with Android Studio

For unsigned APK: Simply set signingConfig null. It will give you appName-debug-unsigned.apk

debug {
     signingConfig null
}

And build from Build menu. Enjoy

For signed APK:

signingConfigs {
        def keyProps = new Properties()
        keyProps.load(rootProject.file('keystore.properties').newDataInputStream())
        internal {
            storeFile file(keyProps.getProperty('CERTIFICATE_PATH'))
            storePassword keyProps.getProperty('STORE_PASSWORD')
            keyAlias keyProps.getProperty('KEY_ALIAS')
            keyPassword keyProps.getProperty('KEY_PASSWORD')
        }
    }
    buildTypes {
        debug {
            signingConfig signingConfigs.internal
            minifyEnabled false
        }
        release {
            signingConfig signingConfigs.internal
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

keystore.properties file

CERTIFICATE_PATH=./../keystore.jks
STORE_PASSWORD=password
KEY_PASSWORD=password
KEY_ALIAS=key0

How can you create multiple cursors in Visual Studio Code

Press Alt and click. This works on Windows and Linux*, and it should work on Mac, too.

More multi-cursor features are now available in Visual Studio Code 0.2:

Multi cursor improvements
Ctrl+D (Cmd+D on Mac) selects next occurrence of word under cursor or of the current selection
Ctrl+K Ctrl+D moves last added cursor to next occurrence of word under cursor or of the current selection
The commands use matchCase by default. If the find widget is open, then the find widget settings (matchCase / matchWholeWord) will be used for determining the next occurrence
Ctrl+U (Cmd+U on Mac) undoes the last cursor action, so if you added a cursor too many or made a mistake, you can press Ctrl+U (Cmd+U on Mac) to go back to the previous cursor state. Adding cursor up or down (Ctrl+Alt+Up / Ctrl+Alt+Down) (Cmd+Alt+Up / Cmd+Alt+Down on Mac) now reveals the last added cursor to make it easier to work with multiple cursors on more than 1 viewport height at a time (i.e. select 300 lines and only 80 fit in the viewport).

This makes it a lot easier to introduce multiple cursors

* Linux drag-window conflict:

Some distros (e.g. Ubuntu) assign window dragging to Alt+LeftMouse, which will conflict with VSCode.

So, recent versions of VSCode let you toggle between Alt+LeftMouse and Ctrl+LeftMouse under the Selection menu, as detailed in another answer.

Alternately, you could change your OS key bindings using gsettings as mentioned in another answer.

How to rotate x-axis tick labels in Pandas barplot

You can use set_xticklabels()

ax.set_xticklabels(df['Names'], rotation=90, ha='right')

Check if string begins with something?

First, lets extend the string object. Thanks to Ricardo Peres for the prototype, I think using the variable 'string' works better than 'needle' in the context of making it more readable.

String.prototype.beginsWith = function (string) {
    return(this.indexOf(string) === 0);
};

Then you use it like this. Caution! Makes the code extremely readable.

var pathname = window.location.pathname;
if (pathname.beginsWith('/sub/1')) {
    // Do stuff here
}

Python group by

Do it in 2 steps. First, create a dictionary.

>>> input = [('11013331', 'KAT'), ('9085267', 'NOT'), ('5238761', 'ETH'), ('5349618', 'ETH'), ('11788544', 'NOT'), ('962142', 'ETH'), ('7795297', 'ETH'), ('7341464', 'ETH'), ('9843236', 'KAT'), ('5594916', 'ETH'), ('1550003', 'ETH')]
>>> from collections import defaultdict
>>> res = defaultdict(list)
>>> for v, k in input: res[k].append(v)
...

Then, convert that dictionary into the expected format.

>>> [{'type':k, 'items':v} for k,v in res.items()]
[{'items': ['9085267', '11788544'], 'type': 'NOT'}, {'items': ['5238761', '5349618', '962142', '7795297', '7341464', '5594916', '1550003'], 'type': 'ETH'}, {'items': ['11013331', '9843236'], 'type': 'KAT'}]

It is also possible with itertools.groupby but it requires the input to be sorted first.

>>> sorted_input = sorted(input, key=itemgetter(1))
>>> groups = groupby(sorted_input, key=itemgetter(1))
>>> [{'type':k, 'items':[x[0] for x in v]} for k, v in groups]
[{'items': ['5238761', '5349618', '962142', '7795297', '7341464', '5594916', '1550003'], 'type': 'ETH'}, {'items': ['11013331', '9843236'], 'type': 'KAT'}, {'items': ['9085267', '11788544'], 'type': 'NOT'}]

Note both of these do not respect the original order of the keys. You need an OrderedDict if you need to keep the order.

>>> from collections import OrderedDict
>>> res = OrderedDict()
>>> for v, k in input:
...   if k in res: res[k].append(v)
...   else: res[k] = [v]
... 
>>> [{'type':k, 'items':v} for k,v in res.items()]
[{'items': ['11013331', '9843236'], 'type': 'KAT'}, {'items': ['9085267', '11788544'], 'type': 'NOT'}, {'items': ['5238761', '5349618', '962142', '7795297', '7341464', '5594916', '1550003'], 'type': 'ETH'}]

How do I iterate through table rows and cells in JavaScript?

This solution worked perfectly for me

var table = document.getElementById("myTable").rows;
var y;
for(i = 0; i < # of rows; i++)
{    for(j = 0; j < # of columns; j++)
     {
         y = table[i].cells;
         //do something with cells in a row
         y[j].innerHTML = "";
     }
}

Can't include C++ headers like vector in Android NDK

It is possible. Here is some step by step:

In $PROJECT_DIR/jni/Application.mk:

APP_STL                 := stlport_static

I tried using stlport_shared, but no luck. Same with libstdc++.

In $PROJECT_DIR/jni/Android.mk:

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

LOCAL_MODULE    := hello-jni
LOCAL_SRC_FILES := hello-jni.cpp
LOCAL_LDLIBS    := -llog

include $(BUILD_SHARED_LIBRARY)

Nothing special here, but make sure your files are .cpp.

In $PROJECT_DIR/jni/hello-jni.cpp:

#include <string.h>
#include <jni.h>
#include <android/log.h>

#include <iostream>
#include <vector>


#define  LOG_TAG    "hellojni"
#define  LOGI(...)  __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__)
#define  LOGE(...)  __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__)


#ifdef __cplusplus
extern "C" {
#endif

// Comments omitted.    
void
Java_com_example_hellojni_HelloJni_stringFromJNI( JNIEnv* env,
                                                  jobject thiz )
{
    std::vector<std::string> vec;

    // Go ahead and do some stuff with this vector of strings now.
}

#ifdef __cplusplus
}
#endif

The only thing that bite me here was #ifdef __cplusplus.

Watch the directories.

To compile, use ndk-build clean && ndk-build.

Controlling Spacing Between Table Cells

table.test td {
    background-color: lime;
    padding: 12px;
    border:2px solid #fff;border-collapse:separate;
}

Uses for the '&quot;' entity in HTML

In my experience it may be the result of auto-generation by a string-based tools, where the author did not understand the rules of HTML.

When some developers generate HTML without the use of special XML-oriented tools, they may try to be sure the resulting HTML is valid by taking the approach that everything must be escaped.

Referring to your example, the reason why every occurrence of " is represented by &quot; could be because using that approach, you can safely use such "special" characters in both attributes and values.

Another motivation I've seen is where people believe, "We must explicitly show that our symbols are not part of the syntax." Whereas, valid HTML can be created by using the proper string-manipulation tools, see the previous paragraph again.

Here is some pseudo-code loosely based on C#, although it is preferred to use valid methods and tools:

public class HtmlAndXmlWriter
{
    private string Escape(string badString)
    {
        return badString.Replace("&", "&amp;").Replace("\"", "&quot;").Replace("'", "&apos;").Replace(">", "&gt;").Replace("<", "&lt;");

    }

    public string GetHtmlFromOutObject(Object obj)
    {
        return "<div class='type_" + Escape(obj.Type) + "'>" + Escape(obj.Value) + "</div>";    

    }

}

It's really very common to see such approaches taken to generate HTML.

QR Code encoding and decoding using zxing

For what it's worth, my groovy spike seems to work with both UTF-8 and ISO-8859-1 character encodings. Not sure what will happen when a non zxing decoder tries to decode the UTF-8 encoded image though... probably varies depending on the device.

// ------------------------------------------------------------------------------------
// Requires: groovy-1.7.6, jdk1.6.0_03, ./lib with zxing core-1.7.jar, javase-1.7.jar 
// Javadocs: http://zxing.org/w/docs/javadoc/overview-summary.html
// Run with: groovy -cp "./lib/*" zxing.groovy
// ------------------------------------------------------------------------------------

import com.google.zxing.*
import com.google.zxing.common.*
import com.google.zxing.client.j2se.*

import java.awt.image.BufferedImage
import javax.imageio.ImageIO

def class zxing {
    def static main(def args) {
        def filename = "./qrcode.png"
        def data = "This is a test to see if I can encode and decode this data..."
        def charset = "UTF-8" //"ISO-8859-1" 
        def hints = new Hashtable<EncodeHintType, String>([(EncodeHintType.CHARACTER_SET): charset])

        writeQrCode(filename, data, charset, hints, 100, 100)

        assert data == readQrCode(filename, charset, hints)
    }

    def static writeQrCode(def filename, def data, def charset, def hints, def width, def height) {
        BitMatrix matrix = new MultiFormatWriter().encode(new String(data.getBytes(charset), charset), BarcodeFormat.QR_CODE, width, height, hints)
        MatrixToImageWriter.writeToFile(matrix, filename.substring(filename.lastIndexOf('.')+1), new File(filename))
    }

    def static readQrCode(def filename, def charset, def hints) {
        BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(ImageIO.read(new FileInputStream(filename)))))
        Result result = new MultiFormatReader().decode(binaryBitmap, hints)

        result.getText()        
    }

}

A fast way to delete all rows of a datatable at once

Here is a clean and modern way to do it using Entity FW and without SQL Injection or TSQL..

using (Entities dbe = new Entities())
{
    dbe.myTable.RemoveRange(dbe.myTable.ToList());
    dbe.SaveChanges();
}

PHP: Read Specific Line From File

I like daggett answer but there is another solution you can get try if your file is not big enough.

$file = __FILE__; // Let's take the current file just as an example.

$start_line = __LINE__ -1; // The same with the line what we look for. Take the line number where $line variable is declared as the start.

$lines_to_display = 5; // The number of lines to display. Displays only the $start_line if set to 1. If $lines_to_display argument is omitted displays all lines starting from the $start_line.

echo implode('', array_slice(file($file), $start_line, lines_to_display));

How to add conditional attribute in Angular 2?

null removes it:

[attr.checked]="value ? '' : null"

or

[attr.checked]="value ? 'checked' : null"

Hint:

Attribute vs property

When the HTML element where you add this binding does not have a property with the name used in the binding (checked in this case) and also no Angular component or directive is applied to the same element that has an @Input() checked;, then [xxx]="..." can not be used.

See also What is the difference between properties and attributes in HTML?

What to bind to when there is no such property

Alternatives are [style.xxx]="...", [attr.xxx]="...", [class.xxx]="..." depending on what you try to accomplish.

Because <input> only has a checked attribute, but no checked property [attr.checked]="..." is the right way for this specific case.

Attributes can only handle string values

A common pitfall is also that for [attr.xxx]="..." bindings the value (...) is always stringified. Only properties and @Input()s can receive other value types like boolean, number, object, ...

Most properties and attributes of elements are connected and have the same name.

Property-attribute connection

When bound to the attribute the property also only receives the stringified value from the attribute.
When bound to the property the property receives the value bound to it (boolean, number, object, ...) and the attribute again the stringified value.

Two cases where attribute and property names do not match.

Angular was changed since then and knows about these special cases and handles them so that you can bind to <label [for]=" even though no such property exists (same for colspan)

How to make <input type="file"/> accept only these types?

Use Like below

<input type="file" accept=".xlsx,.xls,image/*,.doc, .docx,.ppt, .pptx,.txt,.pdf" />

How do you see the entire command history in interactive Python?

Rehash of Doogle's answer that doesn't printline numbers, but does allow specifying the number of lines to print.

def history(lastn=None):
    """
    param: lastn Defaults to None i.e full history. If specified then returns lastn records from history.
           Also takes -ve sequence for first n history records.
    """
    import readline
    assert lastn is None or isinstance(lastn, int), "Only integers are allowed."
    hlen = readline.get_current_history_length()
    is_neg = lastn is not None and lastn < 0
    if not is_neg:
        for r in range(1,hlen+1) if not lastn else range(1, hlen+1)[-lastn:]:
            print(readline.get_history_item(r))
    else:
        for r in range(1, -lastn + 1):
            print(readline.get_history_item(r))

Run Executable from Powershell script with parameters

Here is an alternative method for doing multiple args. I use it when the arguments are too long for a one liner.

$app = 'C:\Program Files\MSBuild\test.exe'
$arg1 = '/genmsi'
$arg2 = '/f'
$arg3 = '$MySourceDirectory\src\Deployment\Installations.xml'

& $app $arg1 $arg2 $arg3

Depend on a branch or tag using a git URL in a package.json?

If it helps anyone, I tried everything above (https w/token mode) - and still nothing was working. I got no errors, but nothing would be installed in node_modules or package_lock.json. If I changed the token or any letter in the repo name or user name, etc. - I'd get an error. So I knew I had the right token and repo name.

I finally realized it's because the name of the dependency I had in my package.json didn't match the name in the package.json of the repo I was trying to pull. Even npm install --verbose doesn't say there's any problem. It just seems to ignore the dependency w/o error.

How to Deserialize JSON data?

You can deserialize this really easily. The data's structure in C# is just List<string[]> so you could just do;

  List<string[]> data = JsonConvert.DeserializeObject<List<string[]>>(jsonString);

The above code is assuming you're using json.NET.

EDIT: Note the json is technically an array of string arrays. I prefer to use List<string[]> for my own declaration because it's imo more intuitive. It won't cause any problems for json.NET, if you want it to be an array of string arrays then you need to change the type to (I think) string[][] but there are some funny little gotcha's with jagged and 2D arrays in C# that I don't really know about so I just don't bother dealing with it here.

How do I force git to checkout the master branch and remove carriage returns after I've normalized files using the "text" attribute?

Ahah! Checkout the previous commit, then checkout the master.

git checkout HEAD^
git checkout -f master

Python: Select subset from list based on index set

Use the built in function zip

property_asel = [a for (a, truth) in zip(property_a, good_objects) if truth]

EDIT

Just looking at the new features of 2.7. There is now a function in the itertools module which is similar to the above code.

http://docs.python.org/library/itertools.html#itertools.compress

itertools.compress('ABCDEF', [1,0,1,0,1,1]) =>
  A, C, E, F

How to replace DOM element in place using Javascript?

var a = A.parentNode.replaceChild(document.createElement("span"), A);

a is the replaced A element.

How to include "zero" / "0" results in COUNT aggregate?

You must use LEFT JOIN instead of INNER JOIN

SELECT person.person_id, COUNT(appointment.person_id) AS "number_of_appointments"
FROM person 
LEFT JOIN appointment ON person.person_id = appointment.person_id
GROUP BY person.person_id;

Asus Zenfone 5 not detected by computer

driver Asus for Windows: http://www.asus.com/sa-en/support/Download/39/1/0/2/32/

Choose target device: USB device

enter image description here (open image in new tab for bigger)

What's is the difference between train, validation and test set, in neural networks?

In simple words define Training set, Test set, Validation set

Training set: Is used for finding Nearest neighbors. Validation set: Is for finding different k which is applying to train set. Test set: Is used for finding the maximum accuracy and unseen data in future.

What are queues in jQuery?

The uses of jQuery .queue() and .dequeue()

Queues in jQuery are used for animations. You can use them for any purpose you like. They are an array of functions stored on a per element basis, using jQuery.data(). They are First-In-First-Out (FIFO). You can add a function to the queue by calling .queue(), and you remove (by calling) the functions using .dequeue().

To understand the internal jQuery queue functions, reading the source and looking at examples helps me out tremendously. One of the best examples of a queue function I've seen is .delay():

$.fn.delay = function( time, type ) {
  time = jQuery.fx ? jQuery.fx.speeds[time] || time : time;
  type = type || "fx";

  return this.queue( type, function() {
    var elem = this;
    setTimeout(function() {
      jQuery.dequeue( elem, type );
    }, time );
  });
};

The default queue - fx

The default queue in jQuery is fx. The default queue has some special properties that are not shared with other queues.

  1. Auto Start: When calling $(elem).queue(function(){}); the fx queue will automatically dequeue the next function and run it if the queue hasn't started.
  2. 'inprogress' sentinel: Whenever you dequeue() a function from the fx queue, it will unshift() (push into the first location of the array) the string "inprogress" - which flags that the queue is currently being run.
  3. It's the default! The fx queue is used by .animate() and all functions that call it by default.

NOTE: If you are using a custom queue, you must manually .dequeue() the functions, they will not auto start!

Retrieving/Setting the queue

You can retrieve a reference to a jQuery queue by calling .queue() without a function argument. You can use the method if you want to see how many items are in the queue. You can use push, pop, unshift, shift to manipulate the queue in place. You can replace the entire queue by passing an array to the .queue() function.

Quick Examples:

// lets assume $elem is a jQuery object that points to some element we are animating.
var queue = $elem.queue();
// remove the last function from the animation queue.
var lastFunc = queue.pop(); 
// insert it at the beginning:    
queue.unshift(lastFunc);
// replace queue with the first three items in the queue
$elem.queue(queue.slice(0,3)); 

An animation (fx) queue example:

Run example on jsFiddle

$(function() {
    // lets do something with google maps:
    var $map = $("#map_canvas");
    var myLatlng = new google.maps.LatLng(-34.397, 150.644);
    var myOptions = {zoom: 8, center: myLatlng, mapTypeId: google.maps.MapTypeId.ROADMAP};
    var geocoder = new google.maps.Geocoder();
    var map = new google.maps.Map($map[0], myOptions);
    var resized = function() {
        // simple animation callback - let maps know we resized
        google.maps.event.trigger(map, 'resize');
    };

    // wait 2 seconds
    $map.delay(2000);
    // resize the div:
    $map.animate({
        width: 250,
        height: 250,
        marginLeft: 250,
        marginTop:250
    }, resized);
    // geocode something
    $map.queue(function(next) {
        // find stackoverflow's whois address:
      geocoder.geocode({'address': '55 Broadway New York NY 10006'},handleResponse);

      function handleResponse(results, status) {
          if (status == google.maps.GeocoderStatus.OK) {
              var location = results[0].geometry.location;
              map.setZoom(13);
              map.setCenter(location);
              new google.maps.Marker({ map: map, position: location });
          }
          // geocoder result returned, continue with animations:
          next();
      }
    });
    // after we find stack overflow, wait 3 more seconds
    $map.delay(3000);
    // and resize the map again
    $map.animate({
        width: 500,
        height: 500,
        marginLeft:0,
        marginTop: 0
    }, resized);
});

Another custom queue example

Run example on jsFiddle

var theQueue = $({}); // jQuery on an empty object - a perfect queue holder

$.each([1,2,3],function(i, num) {
  // lets add some really simple functions to a queue:
  theQueue.queue('alerts', function(next) { 
    // show something, and if they hit "yes", run the next function.
    if (confirm('index:'+i+' = '+num+'\nRun the next function?')) {
      next();
    }
  }); 
});

// create a button to run the queue:
$("<button>", {
  text: 'Run Queue', 
  click: function() { 
    theQueue.dequeue('alerts'); 
  }
}).appendTo('body');

// create a button to show the length:
$("<button>", {
  text: 'Show Length', 
  click: function() { 
    alert(theQueue.queue('alerts').length); 
  }
}).appendTo('body');

Queueing Ajax Calls:

I developed an $.ajaxQueue() plugin that uses the $.Deferred, .queue(), and $.ajax() to also pass back a promise that is resolved when the request completes. Another version of $.ajaxQueue that still works in 1.4 is posted on my answer to Sequencing Ajax Requests

/*
* jQuery.ajaxQueue - A queue for ajax requests
* 
* (c) 2011 Corey Frang
* Dual licensed under the MIT and GPL licenses.
*
* Requires jQuery 1.5+
*/ 
(function($) {

// jQuery on an empty object, we are going to use this as our Queue
var ajaxQueue = $({});

$.ajaxQueue = function( ajaxOpts ) {
    var jqXHR,
        dfd = $.Deferred(),
        promise = dfd.promise();

    // queue our ajax request
    ajaxQueue.queue( doRequest );

    // add the abort method
    promise.abort = function( statusText ) {

        // proxy abort to the jqXHR if it is active
        if ( jqXHR ) {
            return jqXHR.abort( statusText );
        }

        // if there wasn't already a jqXHR we need to remove from queue
        var queue = ajaxQueue.queue(),
            index = $.inArray( doRequest, queue );

        if ( index > -1 ) {
            queue.splice( index, 1 );
        }

        // and then reject the deferred
        dfd.rejectWith( ajaxOpts.context || ajaxOpts,
            [ promise, statusText, "" ] );

        return promise;
    };

    // run the actual query
    function doRequest( next ) {
        jqXHR = $.ajax( ajaxOpts )
            .done( dfd.resolve )
            .fail( dfd.reject )
            .then( next, next );
    }

    return promise;
};

})(jQuery);

I have now added this as an article on learn.jquery.com, there are other great articles on that site about queues, go look.

How to ssh connect through python Paramiko with ppk public key

@VonC's answer to a duplicate question:

If, as commented, Paraminko does not support PPK key, the official solution, as seen here, would be to use PuTTYgen.

But you can also use the Python library CkSshKey to make that same conversion directly in your program.

See "Convert PuTTY Private Key (ppk) to OpenSSH (pem)"

import sys
import chilkat

key = chilkat.CkSshKey()

#  Load an unencrypted or encrypted PuTTY private key.

#  If  your PuTTY private key is encrypted, set the Password
#  property before calling FromPuttyPrivateKey.
#  If your PuTTY private key is not encrypted, it makes no diffference
#  if Password is set or not set.
key.put_Password("secret")

#  First load the .ppk file into a string:

keyStr = key.loadText("putty_private_key.ppk")

#  Import into the SSH key object:
success = key.FromPuttyPrivateKey(keyStr)
if (success != True):
    print(key.lastErrorText())
    sys.exit()

#  Convert to an encrypted or unencrypted OpenSSH key.

#  First demonstrate converting to an unencrypted OpenSSH key

bEncrypt = False
unencryptedKeyStr = key.toOpenSshPrivateKey(bEncrypt)
success = key.SaveText(unencryptedKeyStr,"unencrypted_openssh.pem")
if (success != True):
    print(key.lastErrorText())
    sys.exit()

How to update values using pymongo?

Something I did recently, hope it helps. I have a list of dictionaries and wanted to add a value to some existing documents.

for item in my_list:
    my_collection.update({"_id" : item[key] }, {"$set" : {"New_col_name" :item[value]}})

Thymeleaf using path variables to th:href

I was trying to go through a list of objects, display them as rows in a table, with each row being a link. This worked for me. Hope it helps.

// CUSTOMER_LIST is a model attribute
<table>
    <th:block th:each="customer : ${CUSTOMER_LIST}">
        <tr>
            <td><a th:href="@{'/main?id=' + ${customer.id}}" th:text="${customer.fullName}" /></td>
        </tr>
    </th:block>
</table>

Download data url file

For anyone having issues in IE:

Please upvote the answer here by Yetti: saving canvas locally in IE

dataURItoBlob = function(dataURI) {
    var binary = atob(dataURI.split(',')[1]);
    var array = [];
    for(var i = 0; i < binary.length; i++) {
        array.push(binary.charCodeAt(i));
    }
    return new Blob([new Uint8Array(array)], {type: 'image/png'});
}

var blob = dataURItoBlob(uri);
window.navigator.msSaveOrOpenBlob(blob, "my-image.png");

Rounding float in Ruby

If you just need to display it, I would use the number_with_precision helper. If you need it somewhere else I would use, as Steve Weet pointed, the round method

Show MySQL host via SQL Command

I think you try to get the remote host of the conneting user...

You can get a String like 'myuser@localhost' from the command:

SELECT USER()

You can split this result on the '@' sign, to get the parts:

-- delivers the "remote_host" e.g. "localhost" 
SELECT SUBSTRING_INDEX(USER(), '@', -1) 

-- delivers the user-name e.g. "myuser"
SELECT SUBSTRING_INDEX(USER(), '@', 1)

if you are conneting via ip address you will get the ipadress instead of the hostname.

How can I send large messages with Kafka (over 15MB)?

For people using landoop kafka: You can pass the config values in the environment variables like:

docker run -d --rm -p 2181:2181 -p 3030:3030 -p 8081-8083:8081-8083  -p 9581-9585:9581-9585 -p 9092:9092
 -e KAFKA_TOPIC_MAX_MESSAGE_BYTES=15728640 -e KAFKA_REPLICA_FETCH_MAX_BYTES=15728640  landoop/fast-data-dev:latest `

And if you're usind rdkafka then pass the message.max.bytes in the producer config like:

  const producer = new Kafka.Producer({
        'metadata.broker.list': 'localhost:9092',
        'message.max.bytes': '15728640',
        'dr_cb': true
    });

Similarly, for the consumer,

  const kafkaConf = {
   "group.id": "librd-test",
   "fetch.message.max.bytes":"15728640",
   ... .. }                                                                                                                                                                                                                                                      

Can regular expressions be used to match nested patterns?

Using regular expressions to check for nested patterns is very easy.

'/(\((?>[^()]+|(?1))*\))/'

How to convert milliseconds to seconds with precision

Surely you just need:

double seconds = milliseconds / 1000.0;

There's no need to manually do the two parts separately - you just need floating point arithmetic, which the use of 1000.0 (as a double literal) forces. (I'm assuming your milliseconds value is an integer of some form.)

Note that as usual with double, you may not be able to represent the result exactly. Consider using BigDecimal if you want to represent 100ms as 0.1 seconds exactly. (Given that it's a physical quantity, and the 100ms wouldn't be exact in the first place, a double is probably appropriate, but...)

$("#form1").validate is not a function

I had this same issue. It turned out that I was loading the jQuery JavaScript file more than once on the page. This was due to included pages (or JSPs, in my case). Once I removed the duplicate reference to the jQuery js file, this error went away.

pip install - locale.Error: unsupported locale setting

[This answer is target on linux platform only]

The first thing you should know is most of the locale config file located path can be get from localedef --help :

$ localedef --help | tail -n 5
System's directory for character maps : /usr/share/i18n/charmaps
                       repertoire maps: /usr/share/i18n/repertoiremaps
                       locale path    : /usr/lib/locale:/usr/share/i18n
For bug reporting instructions, please see:
<https://bugs.launchpad.net/ubuntu/+source/glibc/+bugs>

See the last /usr/share/i18n ? This is where your xx_XX.UTF-8 config file located:

$ ls /usr/share/i18n/locales/zh_*
/usr/share/i18n/locales/zh_CN  /usr/share/i18n/locales/zh_HK  /usr/share/i18n/locales/zh_SG  /usr/share/i18n/locales/zh_TW

Now what ? We need to compile them into archive binary. One of the way, e.g. assume I have /usr/share/i18n/locales/en_LOVE, I can add it into compile list, i.e. /etc/locale-gen file:

$ tail -1 /etc/locale.gen 
en_LOVE.UTF-8 UTF-8

And compile it to binary with sudo locale-gen:

$ sudo locale-gen 
Generating locales (this might take a while)...
  en_AG.UTF-8... done
  en_AU.UTF-8... done
  en_BW.UTF-8... done
  ...
  en_LOVE.UTF-8... done
Generation complete.

And now update the system default locale with desired LANG, LC_ALL ...etc with this update-locale:

sudo update-locale LANG=en_LOVE.UTF-8

update-locale actually also means to update this /etc/default/locale file which will source by system on login to setup environment variables:

$ head /etc/default/locale 
#  File generated by update-locale
LANG=en_LOVE.UTF-8
LC_NUMERIC="en_US.UTF-8"
...

But we may not want to reboot to take effect, so we can just source it to environment variable in current shell session:

$ . /etc/default/locale

How about sudo dpkg-reconfigure locales ? If you play around it you will know this command basically act as GUI to simplify the above steps, i.e. Edit /etc/locale.gen -> sudo locale-gen -> sudo update-locale LANG=en_LOVE.UTF-8

For python, as long as /etc/locale.gen contains that locale candidate and locale.gen get compiled, setlocale(category, locale) should work without throws locale.Error: unsupoorted locale setting. You can check the correct string en_US.UTF-8/en_US/....etc to be set in setlocale(), by observing /etc/locale.gen file, and then uncomment and compile it as desired. zh_CN GB2312 without dot in that file means the correct string is zh_CN and zh_CN.GB2312.

Eclipse executable launcher error: Unable to locate companion shared library

This happened to me when I tried to open eclipse.exe before the .zip file finished extracting. Make sure all dependencies are unzipped or unpacked before opening the .exe.

Understanding the results of Execute Explain Plan in Oracle SQL Developer

The output of EXPLAIN PLAN is a debug output from Oracle's query optimiser. The COST is the final output of the Cost-based optimiser (CBO), the purpose of which is to select which of the many different possible plans should be used to run the query. The CBO calculates a relative Cost for each plan, then picks the plan with the lowest cost.

(Note: in some cases the CBO does not have enough time to evaluate every possible plan; in these cases it just picks the plan with the lowest cost found so far)

In general, one of the biggest contributors to a slow query is the number of rows read to service the query (blocks, to be more precise), so the cost will be based in part on the number of rows the optimiser estimates will need to be read.

For example, lets say you have the following query:

SELECT emp_id FROM employees WHERE months_of_service = 6;

(The months_of_service column has a NOT NULL constraint on it and an ordinary index on it.)

There are two basic plans the optimiser might choose here:

  • Plan 1: Read all the rows from the "employees" table, for each, check if the predicate is true (months_of_service=6).
  • Plan 2: Read the index where months_of_service=6 (this results in a set of ROWIDs), then access the table based on the ROWIDs returned.

Let's imagine the "employees" table has 1,000,000 (1 million) rows. Let's further imagine that the values for months_of_service range from 1 to 12 and are fairly evenly distributed for some reason.

The cost of Plan 1, which involves a FULL SCAN, will be the cost of reading all the rows in the employees table, which is approximately equal to 1,000,000; but since Oracle will often be able to read the blocks using multi-block reads, the actual cost will be lower (depending on how your database is set up) - e.g. let's imagine the multi-block read count is 10 - the calculated cost of the full scan will be 1,000,000 / 10; Overal cost = 100,000.

The cost of Plan 2, which involves an INDEX RANGE SCAN and a table lookup by ROWID, will be the cost of scanning the index, plus the cost of accessing the table by ROWID. I won't go into how index range scans are costed but let's imagine the cost of the index range scan is 1 per row; we expect to find a match in 1 out of 12 cases, so the cost of the index scan is 1,000,000 / 12 = 83,333; plus the cost of accessing the table (assume 1 block read per access, we can't use multi-block reads here) = 83,333; Overall cost = 166,666.

As you can see, the cost of Plan 1 (full scan) is LESS than the cost of Plan 2 (index scan + access by rowid) - which means the CBO would choose the FULL scan.

If the assumptions made here by the optimiser are true, then in fact Plan 1 will be preferable and much more efficient than Plan 2 - which disproves the myth that FULL scans are "always bad".

The results would be quite different if the optimiser goal was FIRST_ROWS(n) instead of ALL_ROWS - in which case the optimiser would favour Plan 2 because it will often return the first few rows quicker, at the cost of being less efficient for the entire query.