Programs & Examples On #Alasset

Publish to IIS, setting Environment Variable

I know a lot of answers has been given but in my case I added web.{Environment}.config versions in my project and when publishing for a particular environment the value gets replaced.

For example, for Staging (web.Staging.config)

<?xml version="1.0"?>
<configuration xmlns:xdt="">
                <environmentVariables xdt:Transform="InsertIfMissing">
                    <environmentVariable name="ASPNETCORE_ENVIRONMENT"
                                         xdt:Transform="InsertIfMissing" />

For Release or Production I will do this (web.Release.config)

<?xml version="1.0"?>
<configuration xmlns:xdt="">
                <environmentVariables xdt:Transform="InsertIfMissing">
                    <environmentVariable name="ASPNETCORE_ENVIRONMENT"
                                         xdt:Transform="InsertIfMissing" />

Then when publishing I will choose or set the environment name. And this will replace the value of the environment in the eventual web.config file.

how to change onclick event with jquery?

(2019) I used $('#'+id).removeAttr().off('click').on('click', function(){...});

I tried $('#'+id).off().on(...), but it wouldn't work to reset the onClick attribute every time it was called to be reset.

I use .on('click',function(){...}); to stay away from having to quote block all my javascript functions.

The O.P. could now use:

$(this).removeAttr('onclick').off('click').on('click', function(){ displayCalendar(document.prjectFrm[ia + 'dtSubDate'],'yyyy-mm-dd', this); });

Where this came through for me is when my div was set with the onClick attribute set statically:

<div onclick = '...'>

Otherwise, if I only had a dynamically attached a listener to it, I would have used the $('#'+id).off().on('click', function(){...});.

Without the off('click') my onClick listeners were being appended not replaced.

MySQL ORDER BY multiple column ASC and DESC

i think u miss understand about table relation..

users : scores = 1 : *

just join is not a solution.

is this your intention?

SELECT users.username, avg(scores.point), avg(scores.avg_time)
FROM scores, users
WHERE scores.user_id =
GROUP BY users.username
ORDER BY avg(scores.point) DESC, avg(scores.avg_time)
LIMIT 0, 20

(this query to get each users average point and average avg_time by desc point, asc )avg_time

if you want to get each scores ranking? use left outer join

SELECT users.username, scores.point, scores.avg_time
FROM scores left outer join users on scores.user_id =
ORDER BY scores.point DESC, scores.avg_time
LIMIT 0, 20

Change column type in pandas

When I've only needed to specify specific columns, and I want to be explicit, I've used (per DOCS LOCATION):

dataframe = dataframe.astype({'col_name_1':'int','col_name_2':'float64', etc. ...})

So, using the original question, but providing column names to it ...

a = [['a', '1.2', '4.2'], ['b', '70', '0.03'], ['x', '5', '0']]
df = pd.DataFrame(a, columns=['col_name_1', 'col_name_2', 'col_name_3'])
df = df.astype({'col_name_2':'float64', 'col_name_3':'float64'})

Sort a list of tuples by 2nd item (integer value)

From python wiki:

>>> from operator import itemgetter, attrgetter    
>>> sorted(student_tuples, key=itemgetter(2))
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]    
>>> sorted(student_objects, key=attrgetter('age'))
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

Convert/cast an stdClass object to another class

I have a very similar problem. Simplified reflection solution worked just fine for me:

public static function cast($destination, \stdClass $source)
    $sourceReflection = new \ReflectionObject($source);
    $sourceProperties = $sourceReflection->getProperties();
    foreach ($sourceProperties as $sourceProperty) {
        $name = $sourceProperty->getName();
        $destination->{$name} = $source->$name;
    return $destination;

How do I catch a PHP fatal (`E_ERROR`) error?

I developed this function to make it possible to "sandbox" code that could cause a fatal error. Since exceptions thrown from the closure register_shutdown_function don't get emitted from the pre-fatal error call stack, I'm forced to exit after this function to provide a uniform way of using it.

function superTryCatchFinallyAndExit( Closure $try, Closure $catch = NULL, Closure $finally )
    $finished = FALSE;
    register_shutdown_function( function() use ( &$finished, $catch, $finally ) {
        if( ! $finished ) {
            $finished = TRUE;
            print "EXPLODE!".PHP_EOL;
            if( $catch ) {
                superTryCatchFinallyAndExit( function() use ( $catch ) {
                    $catch( new Exception( "Fatal Error!!!" ) );
                }, NULL, $finally );                
            } else {
    } );
    try {
    } catch( Exception $e ) {
        if( $catch ) {
            try {
                $catch( $e );
            } catch( Exception $e ) {}
    $finished = TRUE;

Relative paths based on file location instead of current working directory

What you want to do is get the absolute path of the script (available via ${BASH_SOURCE[0]}) and then use this to get the parent directory and cd to it at the beginning of the script.

parent_path=$( cd "$(dirname "${BASH_SOURCE[0]}")" ; pwd -P )

cd "$parent_path"
cat ../some.text

This will make your shell script work independent of where you invoke it from. Each time you run it, it will be as if you were running ./ inside dir.

Note that this script only works if you're invoking the script directly (i.e. not via a symlink), otherwise the finding the current location of the script gets a little more tricky)

How to disable horizontal scrolling of UIScrollView?

Use this single line.

self.automaticallyAdjustsScrollViewInsets = NO;

How can I convert String[] to ArrayList<String>

List<String> list = Arrays.asList(array);

The list returned will be backed by the array, it acts like a bridge, so it will be fixed-size.

error_log per Virtual Host?

Don't set error_log to where your syslog stuff goes, eg /var/log/apache2, because they errors will get intercepted by ErrorLog. Instead, create a subdir in your project folder for logs and do php_value error_log "/path/to/project/logs". This goes for both .htaccess files and vhosts. Also make sure you put php_flag log_errors on

ASP.NET - How to write some html in the page? With Response.Write?

why don't you give LiteralControl a try?

 myLitCtrl.Text="<h2><p>Notify:</p> Alert</h2>";

What is a callback?

If you referring to ASP.Net callbacks:

In the default model for ASP.NET Web pages, the user interacts with a page and clicks a button or performs some other action that results in a postback. The page and its controls are re-created, the page code runs on the server, and a new version of the page is rendered to the browser. However, in some situations, it is useful to run server code from the client without performing a postback. If the client script in the page is maintaining some state information (for example, local variable values), posting the page and getting a new copy of it destroys that state. Additionally, page postbacks introduce processing overhead that can decrease performance and force the user to wait for the page to be processed and re-created.

To avoid losing client state and not incur the processing overhead of a server roundtrip, you can code an ASP.NET Web page so that it can perform client callbacks. In a client callback, a client-script function sends a request to an ASP.NET Web page. The Web page runs a modified version of its normal life cycle. The page is initiated and its controls and other members are created, and then a specially marked method is invoked. The method performs the processing that you have coded and then returns a value to the browser that can be read by another client script function. Throughout this process, the page is live in the browser.


If you are referring to callbacks in code:

Callbacks are often delegates to methods that are called when the specific operation has completed or performs a sub-action. You'll often find them in asynchronous operations. It is a programming principle that you can find in almost every coding language.

More info here:

How to extract text from an existing docx file using python-docx

you can try this also

from docx import Document

document = Document('demo.docx')
for para in document.paragraphs:

List files committed for a revision

svn log --verbose -r 42

Performing SQL queries on an Excel Table within a Workbook with VBA Macro

Hi recently looked into this and had issues referencing the named table (list object) within excel

if you place a suffix '$' on the table name all is well in the world

Sub testSQL()

    Dim cn As ADODB.Connection
    Dim rs As ADODB.Recordset

    ' Declare variables
    strFile = ThisWorkbook.FullName

    ' construct connection string
    strCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strFile _
    & ";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=1"";"

    ' create connection and recordset objects
    Set cn = CreateObject("ADODB.Connection")
    Set rs = CreateObject("ADODB.Recordset")

    ' open connection
    cn.Open strCon

    ' construct SQL query
    strSQL = "SELECT * FROM [TableName$] where [ColumnHeader] = 'wibble';"

    ' execute SQL query
    rs.Open strSQL, cn

    Debug.Print rs.GetString

    ' close connection
    Set rs = Nothing
    Set cn = Nothing
End Sub

How can I find out if I have Xcode commandline tools installed?

/usr/bin/xcodebuild -version

will give you the xcode version, run it via Terminal command

How to center the text in a JLabel?

The following constructor, JLabel(String, int), allow you to specify the horizontal alignment of the label.

JLabel label = new JLabel("The Label", SwingConstants.CENTER);

How to get a div to resize its height to fit container?

You probably are going to want to use the following declaration:

height: 100%;

This will set the div's height to 100% of its containers height, which will make it fill the parent div.

Python mock multiple return values

You can assign an iterable to side_effect, and the mock will return the next value in the sequence each time it is called:

>>> from unittest.mock import Mock
>>> m = Mock()
>>> m.side_effect = ['foo', 'bar', 'baz']
>>> m()
>>> m()
>>> m()

Quoting the Mock() documentation:

If side_effect is an iterable then each call to the mock will return the next value from the iterable.

How do I get the time of day in javascript/Node.js?

Both prior answers are definitely good solutions. If you're amenable to a library, I like moment.js - it does a lot more than just getting/formatting the date.

Python convert object to float

  • You can use pandas.Series.astype
  • You can do something like this :

    weather["Temp"] = weather.Temp.astype(float)
  • You can also use pd.to_numeric that will convert the column from object to float

  • For details on how to use it checkout this link :
  • Example :

    s = pd.Series(['apple', '1.0', '2', -3])
    print(pd.to_numeric(s, errors='ignore'))
    print(pd.to_numeric(s, errors='coerce'))
  • Output:

    0    apple
    1      1.0
    2        2
    3       -3
    dtype: object
    0    NaN
    1    1.0
    2    2.0
    3   -3.0
    dtype: float64
  • In your case you can do something like this:

    weather["Temp"] = pd.to_numeric(weather.Temp, errors='coerce')
  • Other option is to use convert_objects
  • Example is as follows

    >> pd.Series([1,2,3,4,'.']).convert_objects(convert_numeric=True)
    0     1
    1     2
    2     3
    3     4
    4   NaN
    dtype: float64
  • You can use this as follows:

    weather["Temp"] = weather.Temp.convert_objects(convert_numeric=True)
  • I have showed you examples because if any of your column won't have a number then it will be converted to NaN... so be careful while using it.

Get name of currently executing test in JUnit 4

Try this instead:

public class MyTest {
        public TestName testName = new TestName();

        public TestWatcher testWatcher = new TestWatcher() {
            protected void starting(final Description description) {
                String methodName = description.getMethodName();
                String className = description.getClassName();
                className = className.substring(className.lastIndexOf('.') + 1);
                System.err.println("Starting JUnit-test: " + className + " " + methodName);

        public void testA() {
                assertEquals("testA", testName.getMethodName());

        public void testB() {
                assertEquals("testB", testName.getMethodName());

The output looks like this:

Starting JUnit-test: MyTest testA
Starting JUnit-test: MyTest testB

NOTE: This DOES NOT work if your test is a subclass of TestCase! The test runs but the @Rule code just never runs.

How to rebase local branch onto remote master

Step 1:

git fetch origin

Step 2:

git rebase origin/master

Step 3:(Fix if any conflicts)

git add .

Step 4:

git rebase --continue

Step 5:

git push --force

What is the difference between "screen" and "only screen" in media queries?

Let's break down your examples one by one.

@media (max-width:632px)

This one is saying for a window with a max-width of 632px that you want to apply these styles. At that size you would be talking about anything smaller than a desktop screen in most cases.

@media screen and (max-width:632px)

This one is saying for a device with a screen and a window with max-width of 632px apply the style. This is almost identical to the above except you are specifying screen as opposed to the other available media types the most common other one being print.

@media only screen and (max-width:632px)

Here is a quote straight from W3C to explain this one.

The keyword ‘only’ can also be used to hide style sheets from older user agents. User agents must process media queries starting with ‘only’ as if the ‘only’ keyword was not present.

As there is no such media type as "only", the style sheet should be ignored by older browsers.

Here's the link to that quote that is shown in example 9 on that page.

Hopefully this sheds some light on media queries.


Be sure to check out @hybrids excellent answer on how the only keyword is really handled.

UITextField text change event

You should use the notification to solve this problem,because the other method will listen to the input box not the actually input,especially when you use the Chinese input method. In viewDidload

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFiledEditChanged:)


- (void)textFiledEditChanged:(NSNotification *)obj {
UITextField *textField = (UITextField *)obj.object;
NSString *toBestring = textField.text;
NSArray *currentar = [UITextInputMode activeInputModes];
UITextInputMode *currentMode = [currentar firstObject];
if ([currentMode.primaryLanguage isEqualToString:@"zh-Hans"]) {
    UITextRange *selectedRange = [textField markedTextRange];
    UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
    if (!position) {
        if (toBestring.length > kMaxLength)
            textField.text =  toBestring;


finally,you run,will done.

Rounding numbers to 2 digits after comma

Previous answers forgot to type the output as an Number again. There is several ways to do this, depending on your tastes.




How to align a <div> to the middle (horizontally/width) of the page

body, html {
    display: table;
    height: 100%;
    width: 100%;
.container {
    display: table-cell;
    vertical-align: middle;
.container .box {
    width: 100px;
    height: 100px;
    background: red;
    margin: 0 auto;

"width:100%" for the "body" tag is only for an example. In a real project you may remove this property.

SQL Connection Error: System.Data.SqlClient.SqlException (0x80131904)

i had the same issue. go to Sql Server Configuration management->SQL Server network config->protocols for 'servername' and check named pipes is enabled.

UIView frame, bounds and center

I think if you think it from the point of CALayer, everything is more clear.

Frame is not really a distinct property of the view or layer at all, it is a virtual property, computed from the bounds, position(UIView's center), and transform.

So basically how the layer/view layouts is really decided by these three property(and anchorPoint), and either of these three property won't change any other property, like changing transform doesn't change bounds.

IPC performance: Named Pipe vs Socket

Best results you'll get with Shared Memory solution.

Named pipes are only 16% better than TCP sockets.

Results are get with IPC benchmarking:

  • System: Linux (Linux ubuntu 4.4.0 x86_64 i7-6700K 4.00GHz)
  • Message: 128 bytes
  • Messages count: 1000000

Pipe benchmark:

Message size:       128
Message count:      1000000
Total duration:     27367.454 ms
Average duration:   27.319 us
Minimum duration:   5.888 us
Maximum duration:   15763.712 us
Standard deviation: 26.664 us
Message rate:       36539 msg/s

FIFOs (named pipes) benchmark:

Message size:       128
Message count:      1000000
Total duration:     38100.093 ms
Average duration:   38.025 us
Minimum duration:   6.656 us
Maximum duration:   27415.040 us
Standard deviation: 91.614 us
Message rate:       26246 msg/s

Message Queue benchmark:

Message size:       128
Message count:      1000000
Total duration:     14723.159 ms
Average duration:   14.675 us
Minimum duration:   3.840 us
Maximum duration:   17437.184 us
Standard deviation: 53.615 us
Message rate:       67920 msg/s

Shared Memory benchmark:

Message size:       128
Message count:      1000000
Total duration:     261.650 ms
Average duration:   0.238 us
Minimum duration:   0.000 us
Maximum duration:   10092.032 us
Standard deviation: 22.095 us
Message rate:       3821893 msg/s

TCP sockets benchmark:

Message size:       128
Message count:      1000000
Total duration:     44477.257 ms
Average duration:   44.391 us
Minimum duration:   11.520 us
Maximum duration:   15863.296 us
Standard deviation: 44.905 us
Message rate:       22483 msg/s

Unix domain sockets benchmark:

Message size:       128
Message count:      1000000
Total duration:     24579.846 ms
Average duration:   24.531 us
Minimum duration:   2.560 us
Maximum duration:   15932.928 us
Standard deviation: 37.854 us
Message rate:       40683 msg/s

ZeroMQ benchmark:

Message size:       128
Message count:      1000000
Total duration:     64872.327 ms
Average duration:   64.808 us
Minimum duration:   23.552 us
Maximum duration:   16443.392 us
Standard deviation: 133.483 us
Message rate:       15414 msg/s

What is the `zero` value for time.Time in Go?

Invoking an empty time.Time struct literal will return Go's zero date. Thus, for the following print statement:


The output is:

0001-01-01 00:00:00 +0000 UTC

For the sake of completeness, the official documentation explicitly states:

The zero value of type Time is January 1, year 1, 00:00:00.000000000 UTC.

AngularJS - convert dates in controller

All solutions here doesn't really bind the model to the input because you will have to change back the dateAsString to be saved as date in your object (in the controller after the form will be submitted).

If you don't need the binding effect, but just to show it in the input,

a simple could be:

<input type="date" value="{{ | date: 'yyyy-MM-dd' }}" id="item_date" />

Then, if you like, in the controller, you can save the edited date in this way:

  $ = new Date(document.getElementById('item_date').value).getTime();

be aware: in your controller, you have to declare your item variable as $scope.item in order for this to work.

TypeError: Router.use() requires middleware function but got a Object

You are missing router exports module and that is the reason why this error is present.

use module.exports = router; and that would work

How to checkout a specific Subversion revision from the command line?


svn checkout url://repository/path@1234


svn checkout -r 1234 url://repository/path

Should URL be case sensitive?

URL characters are converted into hex code (if you've ever noticed spaces in URLs being displayed as %20, etc.), and since lower and upper case have different hex values, it makes perfect sense that URLs are most definitely case sensitive. However the spirit of the question seems to be SHOULD that be the standard and I say no, but they are. Its up to the developer/provider to account for this in their code if they want it to work regardless for an end user.

Error "can't use subversion command line client : svn" when opening android project checked out from svn

I have fixed the issue after upgrading existing svn client on mac OS X with following link:(1.7.x to 1.9.x)

  1. Open Android Studio
  2. Go to Settings -> Version Control -> Subversion -> General -> User command line client ( Marked checkbox)

replace ‘svn’ with your svn installed path like ‘/usr/local/bin/svn’

How to delete a character from a string using Python

To delete a char or a sub-string once (only the first occurrence):

main_string = main_string.replace(sub_str, replace_with, 1)

NOTE: Here 1 can be replaced with any int for the number of occurrence you want to replace.

'Framework not found' in Xcode

Please after adding both framework also open each Bolts and Parse framework and add Parse and Bolts to the project then problem will be solve

Parsing GET request parameters in a URL that contains another URL

I had a similar problem and ended up using parse_url and parse_str, which as long as the URL in the parameter is correctly url encoded (which it definitely should) allows you to access both all the parameters of the actual URL, as well as the parameters of the encoded URL in the query parameter, like so:

$get_url = "";
$my_url = "http://localhost/test.php?id=" . urlencode($get_url);

function so_5645412_url_params($url) {
    $url_comps = parse_url($url);
    $query = $url_comps['query'];

    $args = array();
    parse_str($query, $args);

    return $args;

$my_url_args = so_5645412_url_params($my_url); // Array ( [id] => )
$get_url_args = so_5645412_url_params($my_url_args['id']); // Array ( [var] => 234, [key] => 234 )

How to fix: "No suitable driver found for jdbc:mysql://localhost/dbname" error when using pools?

if you are using netbeans you must add Mysql JDBC driver in the library list of the project, in the properties of your project

Why Choose Struct Over Class?

One point not getting attention in these answers is that a variable holding a class vs a struct can be a let while still allowing changes on the object's properties, while you cannot do this with a struct.

This is useful if you don't want the variable to ever point to another object, but still need to modify the object, i.e. in the case of having many instance variables that you wish to update one after another. If it is a struct, you must allow the variable to be reset to another object altogether using var in order to do this, since a constant value type in Swift properly allows zero mutation, while reference types (classes) don't behave this way.

How do you run a SQL Server query from PowerShell?

This function will return the results of a query as an array of powershell objects so you can use them in filters and access columns easily:

function sql($sqlText, $database = "master", $server = ".")
    $connection = new-object System.Data.SqlClient.SQLConnection("Data Source=$server;Integrated Security=SSPI;Initial Catalog=$database");
    $cmd = new-object System.Data.SqlClient.SqlCommand($sqlText, $connection);

    $reader = $cmd.ExecuteReader()

    $results = @()
    while ($reader.Read())
        $row = @{}
        for ($i = 0; $i -lt $reader.FieldCount; $i++)
            $row[$reader.GetName($i)] = $reader.GetValue($i)
        $results += new-object psobject -property $row            


Removing whitespace between HTML elements when using line breaks

Flexbox can easily fix this old problem:

.image-wrapper {
  display: flex;

More information about flexbox:

Excel VBA Run Time Error '424' object required

You have two options,

-If you want the value:

Dim MyValue as Variant ' or string/date/long/...
MyValue = ThisWorkbook.Sheets(1).Range("A1").Value

-if you want the cell object:

Dim oCell as Range  ' or object (but then you'll miss out on intellisense), and both can also contain more than one cell.
Set oCell = ThisWorkbook.Sheets(1).Range("A1")

Angular 2 - Checking for server errors from subscribe

You can achieve with following way

        result => {
        error => {
            this.errors = error

if (!this.errors) {
    //route to new page

Asp.Net WebApi2 Enable CORS not working with AspNet.WebApi.Cors 5.2.3

None of these answers really work. As others noted the Cors package will only use the Access-Control-Allow-Origin header if the request had an Origin header. But you can't generally just add an Origin header to the request because browsers may try to regulate that too.

If you want a quick and dirty way to allow cross site requests to a web api, it's really a lot easier to just write a custom filter attribute:

public class AllowCors : ActionFilterAttribute
    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        if (actionExecutedContext == null)
            throw new ArgumentNullException("actionExecutedContext");
            actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");

Then just use it on your Controller action:

public IHttpActionResult Get()
    return Ok("value");

I won't vouch for the security of this in general, but it's probably a lot safer than setting the headers in the web.config since this way you can apply them only as specifically as you need them.

And of course it is simple to modify the above to allow only certain origins, methods etc.

Check if Cell value exists in Column, and then get the value of the NEXT Cell

How about this?


The "3" at the end means for column C.

How to have EditText with border in Android Lollipop

A quick and dirty solution I have used is to place the EditText inside of a FrameLayout. The margins of the EditText control the thickness of the border and the border color is determined by the background color of the FrameLayout.



        android:textSize="24sp" />

But I would recommend, and the vast majority of the time I do, drawables for borders. Elite's answer is what I would go for in that case.

In nodeJs is there a way to loop through an array without using array size?

In ES5 there is no efficient way to iterate over a sparse array without using the length property. In ES6 you can use for...of. Take this examples:

'use strict';_x000D_
var arr = ['one', 'two', undefined, 3, 4],_x000D_
arr[6] = 'five';_x000D_
output = '';_x000D_
arr.forEach(function (val) {_x000D_
    output += val + ' ';_x000D_
output = '';_x000D_
for (var i = 0; i < arr.length; i++) {_x000D_
    output += arr[i] + ' ';_x000D_
output = '';_x000D_
for (var val of arr) {_x000D_
    output += val + ' ';_x000D_
<!-- results pane console output; see -->_x000D_
<script src="//"></script>

All array methods which you can use to iterate safely over dense arrays use the length property of an object created by calling ToObject internaly. See for instance the algorithm used in the forEach method: However in es6, you can use for...of safely for iterating over sparse arrays.

See also Are Javascript arrays sparse?.

C Programming: How to read the whole file contents into a buffer

Portability between Linux and Windows is a big headache, since Linux is a POSIX-conformant system with - generally - a proper, high quality toolchain for C, whereas Windows doesn't even provide a lot of functions in the C standard library.

However, if you want to stick to the standard, you can write something like this:

#include <stdio.h>
#include <stdlib.h>

FILE *f = fopen("textfile.txt", "rb");
fseek(f, 0, SEEK_END);
long fsize = ftell(f);
fseek(f, 0, SEEK_SET);  /* same as rewind(f); */

char *string = malloc(fsize + 1);
fread(string, 1, fsize, f);

string[fsize] = 0;

Here string will contain the contents of the text file as a properly 0-terminated C string. This code is just standard C, it's not POSIX-specific (although that it doesn't guarantee it will work/compile on Windows...)

How to create an object property from a variable value in JavaScript?

Dot notation and the properties are equivalent. So you would accomplish like so:

var myObj = new Object;
var a = 'string1';
myObj[a] = 'whatever';

(alerts "whatever")

How to compare objects by multiple fields

I think it'd be more confusing if your comparison algorithm were "clever". I'd go with the numerous comparison methods you suggested.

The only exception for me would be equality. For unit testing, it's been useful to me to override the .Equals (in .net) in order to determine if several fields are equal between two objects (and not that the references are equal).

Restore DB — Error RESTORE HEADERONLY is terminating abnormally.

This type of error will come when you try to upload backup data from a higher version to lower version. Like you have backup of SQL server 2008 and you trying to upload data into SQL server 2005 then you will get this kind of error. Please try to upload in a higher version.

Splitting dataframe into multiple dataframes

Can I ask why not just do it by slicing the data frame. Something like

#create some data with Names column
data = pd.DataFrame({'Names': ['Joe', 'John', 'Jasper', 'Jez'] *4, 'Ob1' : np.random.rand(16), 'Ob2' : np.random.rand(16)})

#create unique list of names
UniqueNames = data.Names.unique()

#create a data frame dictionary to store your data frames
DataFrameDict = {elem : pd.DataFrame for elem in UniqueNames}

for key in DataFrameDict.keys():
    DataFrameDict[key] = data[:][data.Names == key]

Hey presto you have a dictionary of data frames just as (I think) you want them. Need to access one? Just enter


Hope that helps

Read file from line 2 or skip header row

To generalize the task of reading multiple header lines and to improve readability I'd use method extraction. Suppose you wanted to tokenize the first three lines of coordinates.txt to use as header information.


Name,Longitude,Latitude,Elevation, Comments
String, Decimal Deg., Decimal Deg., Meters, String
Euler's Town,7.58857,47.559537,0, "Blah"
Faneuil Hall,-71.054773,42.360217,0
Yellowstone National Park,-110.588455,44.427963,0

Then method extraction allows you to specify what you want to do with the header information (in this example we simply tokenize the header lines based on the comma and return it as a list but there's room to do much more).

def __readheader(filehandle, numberheaderlines=1):
    """Reads the specified number of lines and returns the comma-delimited 
    strings on each line as a list"""
    for _ in range(numberheaderlines):
        yield map(str.strip, filehandle.readline().strip().split(','))

with open('coordinates.txt', 'r') as rh:
    # Single header line
    #print next(__readheader(rh))

    # Multiple header lines
    for headerline in __readheader(rh, numberheaderlines=2):
        print headerline  # Or do other stuff with headerline tokens


['Name', 'Longitude', 'Latitude', 'Elevation', 'Comments']
['String', 'Decimal Deg.', 'Decimal Deg.', 'Meters', 'String']

If coordinates.txt contains another headerline, simply change numberheaderlines. Best of all, it's clear what __readheader(rh, numberheaderlines=2) is doing and we avoid the ambiguity of having to figure out or comment on why author of the the accepted answer uses next() in his code.

Confused about __str__ on list in Python

It provides human readable version of output rather "Object": Example:

class Pet(object):

    def __init__(self, name, species): = name
        self.species = species

    def getName(self):

    def getSpecies(self):
        return self.species

    def Norm(self):
        return "%s is a %s" % (, self.species)

if __name__=='__main__':
    a = Pet("jax", "human")
    print a 


<__main__.Pet object at 0x029E2F90>

while code with "str" return something different

class Pet(object):

    def __init__(self, name, species): = name
        self.species = species

    def getName(self):

    def getSpecies(self):
        return self.species

    def __str__(self):
        return "%s is a %s" % (, self.species)

if __name__=='__main__':
    a = Pet("jax", "human")
    print a 


jax is a human

How to set time to 24 hour format in Calendar

use SimpleDateFormat df = new SimpleDateFormat("HH:mm"); instead


@Ingo is right. is's better use setTime(d1);

first method getHours() and getMinutes() is now deprecated

I test this code

SimpleDateFormat df = new SimpleDateFormat("hh:mm");
  Date d1 = df.parse("23:30");
  Calendar c1 = GregorianCalendar.getInstance();

and output is ok Thu Jan 01 23:30:00 FET 1970

try this

SimpleDateFormat df = new SimpleDateFormat("KK:mm aa");
  Date d1 = df.parse("10:30 PM");
  Calendar c1 = GregorianCalendar.getInstance(Locale.US);
  SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");  
  String str = sdf.format(c1.getTime());

MySQL search and replace some text in a field

I used the above command line as follow: update TABLE-NAME set FIELD = replace(FIELD, 'And', 'and'); the purpose was to replace And with and ("A" should be lowercase). The problem is it cannot find the "And" in database, but if I use like "%And%" then it can find it along with many other ands that are part of a word or even the ones that are already lowercase.

How do I concatenate a string with a variable?

Your code is correct. Perhaps your problem is that you are not passing an ID to the AddBorder function, or that an element with that ID does not exist. Or you might be running your function before the element in question is accessible through the browser's DOM.

To identify the first case or determine the cause of the second case, add these as the first lines inside the function:

alert('ID number: ' + id);
alert('Return value of gEBI: ' + document.getElementById('horseThumb_' + id));

That will open pop-up windows each time the function is called, with the value of id and the return value of document.getElementById. If you get undefined for the ID number pop-up, you are not passing an argument to the function. If the ID does not exist, you would get your (incorrect?) ID number in the first pop-up but get null in the second.

The third case would happen if your web page looks like this, trying to run AddBorder while the page is still loading:

<title>My Web Page</title>
    function AddBorder(id) {
    AddBorder(42);    // Won't work; the page hasn't completely loaded yet!

To fix this, put all the code that uses AddBorder inside an onload event handler:

// Can only have one of these per page
window.onload = function() {

// Or can have any number of these on a page
function doWhatever() {

if(window.addEventListener) window.addEventListener('load', doWhatever, false);
else window.attachEvent('onload', doWhatever);

SQL Plus change current directory

Have you tried creating a windows shortcut for sql plus and set the working directory?

Finding Android SDK on Mac and adding to PATH

The default path of Android SDK is /Users/<username>/Library/Android/sdk, you can refer to this post.

add this to your .bash_profile to add the environment variable

export PATH="/Users/<username>/Library/Android/sdk/tools:/Users/<username>/Library/Android/sdk/build-tools:${PATH}"

Then save the file.

load it

source ./.bash_profile 

How do I add a newline to a TextView in Android?

One way of doing this is using Html tags::

txtTitlevalue.setText(Html.fromHtml("Line1"+"<br>"+"Line2" + " <br>"+"Line3"));

Declare variable in SQLite and use it

I appreciate that the other solutions do not depend on any other software tool, but why not just use another programming language that can interface to SQLite such as C#, C++, Go, Haskell, Java, Lua, Python, or Rust?

How do I print an IFrame from javascript in Safari/Chrome

Put a print function in the iframe and call it from the parent.


function printMe() {



How do I look inside a Python object?

If this is for exploration to see what's going on, I'd recommend looking at IPython. This adds various shortcuts to obtain an objects documentation, properties and even source code. For instance appending a "?" to a function will give the help for the object (effectively a shortcut for "help(obj)", wheras using two ?'s ("func??") will display the sourcecode if it is available.

There are also a lot of additional conveniences, like tab completion, pretty printing of results, result history etc. that make it very handy for this sort of exploratory programming.

For more programmatic use of introspection, the basic builtins like dir(), vars(), getattr etc will be useful, but it is well worth your time to check out the inspect module. To fetch the source of a function, use "inspect.getsource" eg, applying it to itself:

>>> print inspect.getsource(inspect.getsource)
def getsource(object):
    """Return the text of the source code for an object.

    The argument may be a module, class, method, function, traceback, frame,
    or code object.  The source code is returned as a single string.  An
    IOError is raised if the source code cannot be retrieved."""
    lines, lnum = getsourcelines(object)
    return string.join(lines, '')

inspect.getargspec is also frequently useful if you're dealing with wrapping or manipulating functions, as it will give the names and default values of function parameters.

Android ADB doesn't see device

Uninstalling all old "Android ADB Interface" drivers that were installed previously and then installing the new one worked for me.

How to export JavaScript array info to csv (on client side)?

I use this function to convert an string[][] to a csv file. It quotes a cell, if it contains a ", a , or other whitespace (except blanks):

 * Takes an array of arrays and returns a `,` sparated csv file.
 * @param {string[][]} table
 * @returns {string}
function toCSV(table) {
    return table
        .map(function(row) {
            return row
                .map(function(cell) {
                    // We remove blanks and check if the column contains
                    // other whitespace,`,` or `"`.
                    // In that case, we need to quote the column.
                    if (cell.replace(/ /g, '').match(/[\s,"]/)) {
                        return '"' + cell.replace(/"/g, '""') + '"';
                    return cell;
        .join('\n'); // or '\r\n' for windows


Note: does not work on Internet Explorer < 11 unless map is polyfilled.

Note: If the cells contain numbers, you can add cell=''+cell before if (cell.replace... to convert numbers to strings.

Or you can write it in one line using ES6:>>c.replace(/ /g, '').match(/[\s,"]/)?'"'+c.replace(/"/g,'""')+'"':c).join(',')).join('\n')

How to access random item in list?

Or simple extension class like this:

public static class CollectionExtension
    private static Random rng = new Random();

    public static T RandomElement<T>(this IList<T> list)
        return list[rng.Next(list.Count)];

    public static T RandomElement<T>(this T[] array)
        return array[rng.Next(array.Length)];

Then just call:


Works for arrays as well.

I would avoid calling OrderBy() as it can be expensive for larger collections. Use indexed collections like List<T> or arrays for this purpose.

Get the last day of the month in SQL

WinSQL: I wanted to return all records for last month:

where DATE01 between dateadd(month,-1,dateadd(day,1,dateadd(day,-day(today()),today()))) and dateadd(day,-day(today()),today())

This does the same thing:

where month(DATE01) = month(dateadd(month,-1,today())) and year(DATE01) = year(dateadd(month,-1,today()))

jQuery $(".class").click(); - multiple elements, click event once

Hi sorry for bump this post just face this problem and i would like to show my case.

My code look like this.

<button onClick="product.delete('1')" class="btn btn-danger">Delete</button>
<button onClick="product.delete('2')" class="btn btn-danger">Delete</button>
<button onClick="product.delete('3')" class="btn btn-danger">Delete</button>
<button onClick="product.delete('4')" class="btn btn-danger">Delete</button>

Javascript code

 var product = {
     //  Define your function
          //  Do some thing here

         //  Do some thig here

Trying to Validate URL Using JavaScript

I checked a lot of url validators in google and no one works for me. For example I'd like to see valid on links like ''. I like silly check for dot sign in string.

function isValidUri(str) {
  var dotIndex = str.indexOf('.');
  return (dotIndex > 0 && dotIndex < str.length - 2);

It should not stay on beginning and end of string (for now we don't have top level domain names with one character).

Declaring and initializing arrays in C

This is an addendum to the accepted answer by AndreyT, with Nyan's comment on mismatched array sizes. I disagree with their automatic setting of the fifth element to zero. It should likely be 5 --the number after 1,2,3,4. So I would suggest a wrapper to memcpy() to produce a compile-time error when we try to copy arrays of different sizes:

#define Memcpy(a,b) do {                    /* copy arrays */       \
    ASSERT(sizeof(a) == sizeof(b) &&        /* a static assert */   \
           sizeof(a) != sizeof((a) + 0));   /* no pointers */       \
    memcpy((a), (b), sizeof (b));           /* & unnecesary */      \
    } while (0)                             /* no return value */

This macro will generate a compile-time error if your array is of length 1. Which is perhaps a feature.

Because we are using a macro, the C99 compound literal seems to need an extra pair of parentheses:

Memcpy(myarray, ((int[]) { 1, 2, 3, 4 }));

Here ASSERT() is a 'static assert'. If you don't already have your own, I use the following on a number of platforms:

#define CONCAT_TOKENS(a, b) a ## b
#define ASSERT(e) enum {EXPAND_THEN_CONCAT(ASSERT_line_,__LINE__) = 1/!!(e)}
#define ASSERTM(e,m) /* version of ASSERT() with message */ \

Removing element from array in component state

You can use this function, if you want to remove the element (without index)

removeItem(item) {
  this.setState(prevState => {
    data: => i !== item)

How to save a new sheet in an existing excel file, using Pandas?

Thank you. I believe that a complete example could be good for anyone else who have the same issue:

import pandas as pd
import numpy as np

path = r"C:\Users\fedel\Desktop\excelData\PhD_data.xlsx"

x1 = np.random.randn(100, 2)
df1 = pd.DataFrame(x1)

x2 = np.random.randn(100, 2)
df2 = pd.DataFrame(x2)

writer = pd.ExcelWriter(path, engine = 'xlsxwriter')
df1.to_excel(writer, sheet_name = 'x1')
df2.to_excel(writer, sheet_name = 'x2')

Here I generate an excel file, from my understanding it does not really matter whether it is generated via the "xslxwriter" or the "openpyxl" engine.

When I want to write without loosing the original data then

import pandas as pd
import numpy as np
from openpyxl import load_workbook

path = r"C:\Users\fedel\Desktop\excelData\PhD_data.xlsx"

book = load_workbook(path)
writer = pd.ExcelWriter(path, engine = 'openpyxl') = book

x3 = np.random.randn(100, 2)
df3 = pd.DataFrame(x3)

x4 = np.random.randn(100, 2)
df4 = pd.DataFrame(x4)

df3.to_excel(writer, sheet_name = 'x3')
df4.to_excel(writer, sheet_name = 'x4')

this code do the job!

Function to calculate distance between two coordinates

Try this. It is in and you need to convert it to Javascript. This function accepts parameters in decimal minutes.

    Private Function calculateDistance(ByVal long1 As String, ByVal lat1 As String, ByVal long2 As String, ByVal lat2 As String) As Double
    long1 = Double.Parse(long1)
    lat1 = Double.Parse(lat1)
    long2 = Double.Parse(long2)
    lat2 = Double.Parse(lat2)

    'conversion to radian
    lat1 = (lat1 * 2.0 * Math.PI) / 60.0 / 360.0
    long1 = (long1 * 2.0 * Math.PI) / 60.0 / 360.0
    lat2 = (lat2 * 2.0 * Math.PI) / 60.0 / 360.0
    long2 = (long2 * 2.0 * Math.PI) / 60.0 / 360.0

    ' use to different earth axis length
    Dim a As Double = 6378137.0        ' Earth Major Axis (WGS84)
    Dim b As Double = 6356752.3142     ' Minor Axis
    Dim f As Double = (a - b) / a        ' "Flattening"
    Dim e As Double = 2.0 * f - f * f      ' "Eccentricity"

    Dim beta As Double = (a / Math.Sqrt(1.0 - e * Math.Sin(lat1) * Math.Sin(lat1)))
    Dim cos As Double = Math.Cos(lat1)
    Dim x As Double = beta * cos * Math.Cos(long1)
    Dim y As Double = beta * cos * Math.Sin(long1)
    Dim z As Double = beta * (1 - e) * Math.Sin(lat1)

    beta = (a / Math.Sqrt(1.0 - e * Math.Sin(lat2) * Math.Sin(lat2)))
    cos = Math.Cos(lat2)
    x -= (beta * cos * Math.Cos(long2))
    y -= (beta * cos * Math.Sin(long2))
    z -= (beta * (1 - e) * Math.Sin(lat2))

    Return Math.Sqrt((x * x) + (y * y) + (z * z))
End Function

Edit The converted function in javascript

function calculateDistance(lat1, long1, lat2, long2)

      lat1 = (lat1 * 2.0 * Math.PI) / 60.0 / 360.0;      
      long1 = (long1 * 2.0 * Math.PI) / 60.0 / 360.0;    
      lat2 = (lat2 * 2.0 * Math.PI) / 60.0 / 360.0;   
      long2 = (long2 * 2.0 * Math.PI) / 60.0 / 360.0;       

      // use to different earth axis length    
      var a = 6378137.0;        // Earth Major Axis (WGS84)    
      var b = 6356752.3142;     // Minor Axis    
      var f = (a-b) / a;        // "Flattening"    
      var e = 2.0*f - f*f;      // "Eccentricity"      

      var beta = (a / Math.sqrt( 1.0 - e * Math.sin( lat1 ) * Math.sin( lat1 )));    
      var cos = Math.cos( lat1 );    
      var x = beta * cos * Math.cos( long1 );    
      var y = beta * cos * Math.sin( long1 );    
      var z = beta * ( 1 - e ) * Math.sin( lat1 );      

      beta = ( a / Math.sqrt( 1.0 -  e * Math.sin( lat2 ) * Math.sin( lat2 )));    
      cos = Math.cos( lat2 );   
      x -= (beta * cos * Math.cos( long2 ));    
      y -= (beta * cos * Math.sin( long2 ));    
      z -= (beta * (1 - e) * Math.sin( lat2 ));       

      return (Math.sqrt( (x*x) + (y*y) + (z*z) )/1000);  

How to force ViewPager to re-instantiate its items

public class DayFlipper extends ViewPager {

private Flipperadapter adapter;
public class FlipperAdapter extends PagerAdapter {

    public int getCount() {
        return DayFlipper.DAY_HISTORY;

    public void startUpdate(View container) {

    public Object instantiateItem(View container, int position) {
        Log.d(TAG, "instantiateItem(): " + position);

        Date d = DateHelper.getBot();
        for (int i = 0; i < position; i++) {
            d = DateHelper.getTomorrow(d);

        d = DateHelper.normalize(d);

        CubbiesView cv = new CubbiesView(mContext);
        ((ViewPager) container).addView(cv, 0);
        // add map
adpter = FlipperAdapter.this;
        return cv;

    public void destroyItem(View container, int position, Object object) {
        ((ViewPager) container).removeView((CubbiesView) object);

    public void finishUpdate(View container) {


    public boolean isViewFromObject(View view, Object object) {
        return view == ((CubbiesView) object);

    public Parcelable saveState() {
        return null;

    public void restoreState(Parcelable state, ClassLoader loader) {




    public void refresh() {

try this.

Extracting jar to specified directory

Current working version as of Oct 2020, updated to use maven-antrun-plugin 3.0.0.

                            <unzip src="target/shaded-jar/shade-test.jar"

Laravel Redirect Back with() Message

Alternative approach would be


use Session;
Session::flash('message', "Special message goes here");
return Redirect::back();


@if (Session::has('message'))
   <div class="alert alert-info">{{ Session::get('message') }}</div>

Owl Carousel Won't Autoplay

Changing autoplay to autoPlay alone did not work for me. What did the trick was to add autoplaySpeed and autoplayTimeout properties and set them to the same value, like this:

    var owl = $(".owl-carousel");
        items: 1,
        autoplay: true,
        autoPlaySpeed: 5000,
        autoPlayTimeout: 5000,
        autoplayHoverPause: true

Here's a working demo: JS Bin

More info about this can be found here:

Converting Dictionary to List?

Converting from dict to list is made easy in Python. Three examples:

>> d = {'a': 'Arthur', 'b': 'Belling'}

>> d.items()
[('a', 'Arthur'), ('b', 'Belling')]

>> d.keys()
['a', 'b']

>> d.values()
['Arthur', 'Belling']

Parse error: syntax error, unexpected T_ECHO in

Missing ; after var_dump($row)

Is this a good way to clone an object in ES6?

We can do that with two way:
1- First create a new object and replicate the structure of the existing one by iterating 
 over its properties and copying them on the primitive level.

let user = {
     name: "John",
     age: 30

    let clone = {}; // the new empty object

    // let's copy all user properties into it
    for (let key in user) {
      clone[key] = user[key];

    // now clone is a fully independant clone = "Pete"; // changed the data in it

    alert( ); // still John in the original object

2- Second we can use the method Object.assign for that 
    let user = { name: "John" };
    let permissions1 = { canView: true };
    let permissions2 = { canEdit: true };

    // copies all properties from permissions1 and permissions2 into user
    Object.assign(user, permissions1, permissions2);

  -Another example

    let user = {
      name: "John",
      age: 30

    let clone = Object.assign({}, user);
It copies all properties of user into the empty object and returns it. Actually, the same as the loop, but shorter.

But Object.assign() not create a deep clone

let user = {
  name: "John",
  sizes: {
    height: 182,
    width: 50

let clone = Object.assign({}, user);

alert( user.sizes === clone.sizes ); // true, same object

// user and clone share sizes
user.sizes.width++;       // change a property from one place
alert(clone.sizes.width); // 51, see the result from the other one

To fix that, we should use the cloning loop that examines each value of user[key] and, if it’s an object, then replicate its structure as well. That is called a “deep cloning”.

There’s a standard algorithm for deep cloning that handles the case above and more complex cases, called the Structured cloning algorithm. In order not to reinvent the wheel, we can use a working implementation of it from the JavaScript library lodash the method is called _.cloneDeep(obj).

Show a leading zero if a number is less than 10

There's no built-in JavaScript function to do this, but you can write your own fairly easily:

function pad(n) {
    return (n < 10) ? ("0" + n) : n;


Meanwhile there is a native JS function that does that. See String#padStart

console.log(String(5).padStart(2, '0'));

jQuery table sort

If you want to avoid all the bells and whistles then may I suggest this simple sortElements plugin. Usage:

var table = $('table');

$('.sortable th')
    .wrapInner('<span title="sort this column"/>')

        var th = $(this),
            thIndex = th.index(),
            inverse = false;{


                return $(this).index() === thIndex;

            }).sortElements(function(a, b){

                if( $.text([a]) == $.text([b]) )
                    return 0;

                return $.text([a]) > $.text([b]) ?
                    inverse ? -1 : 1
                    : inverse ? 1 : -1;

            }, function(){

                // parentNode is the element we want to move
                return this.parentNode; 


            inverse = !inverse;



And a demo. (click the "city" and "facility" column-headers to sort)

How can I make an "are you sure" prompt in a Windows batchfile?

There are two commands available for user prompts on Windows command line:

  • set with option /P available on all Windows NT versions with enabled command extensions and
  • choice.exe available by default on Windows Vista and later Windows versions for PC users and on Windows Server 2003 and later server versions of Windows.

set is an internal command of Windows command processor cmd.exe. The option /P to prompt a user for a string is available only with enabled command extensions which are enabled by default as otherwise nearly no batch file would work anymore nowadays.

choice.exe is a separate console application (external command) located in %SystemRoot%\System32. File choice.exe of Windows Server 2003 can be copied into directory %SystemRoot%\System32 on a Windows XP machine for usage on Windows XP like many other commands not available by default on Windows XP, but available by default on Windows Server 2003.

It is best practice to favor usage of CHOICE over usage of SET /P because of the following reasons:

  1. CHOICE accepts only keys (respectively characters read from STDIN) specified after option /C (and Ctrl+C and Ctrl+Break) and outputs an error beep if the user presses a wrong key.
  2. CHOICE does not require pressing any other key than one of the acceptable ones. CHOICE exits immediately once an acceptable key is pressed while SET /P requires that the user finishes input with RETURN or ENTER.
  3. It is possible with CHOICE to define a default option and a timeout to automatically continue with default option after some seconds without waiting for the user.
  4. The output is better on answering the prompt automatically from another batch file which calls the batch file with the prompt using something like echo Y | call PromptExample.bat on using CHOICE.
  5. The evaluation of the user's choice is much easier with CHOICE because of CHOICE exits with a value according to pressed key (character) which is assigned to ERRORLEVEL which can be easily evaluated next.
  6. The environment variable used on SET /P is not defined if the user hits just key RETURN or ENTER and it was not defined before prompting the user. The used environment variable on SET /P command line keeps its current value if defined before and user presses just RETURN or ENTER.
  7. The user has the freedom to enter anything on being prompted with SET /P including a string which results later in an exit of batch file execution by cmd because of a syntax error, or in execution of commands not included at all in the batch file on not good coded batch file. It needs some efforts to get SET /P secure against by mistake or intentionally wrong user input.

Here is a prompt example using preferred CHOICE and alternatively SET /P on choice.exe not available on used computer running Windows.

@echo off
setlocal EnableExtensions DisableDelayedExpansion
echo This is an example for prompting a user.
if exist "%SystemRoot%\System32\choice.exe" goto UseChoice

setlocal EnableExtensions EnableDelayedExpansion
set "UserChoice="
set /P "UserChoice=Are you sure [Y/N]? "
set "UserChoice=!UserChoice: =!"
if /I "!UserChoice!" == "N" endlocal & goto :EOF
if /I not "!UserChoice!" == "Y" goto UseSetPrompt
goto Continue

%SystemRoot%\System32\choice.exe /C YN /N /M "Are you sure [Y/N]?"
if not errorlevel 1 goto UseChoice
if errorlevel 2 goto :EOF

echo So your are sure. Okay, let's go ...
rem More commands can be added here.

Note: This batch file uses command extensions which are not available on Windows 95/98/ME using instead of cmd.exe as command interpreter.

The command line set "UserChoice=!UserChoice: =!" is added to make it possible to call this batch file with echo Y | call PromptExample.bat on Windows NT4/2000/XP and do not require the usage of echo Y| call PromptExample.bat. It deletes all spaces from string read from STDIN before running the two string comparisons.

echo Y | call PromptExample.bat results in YSPACE getting assigned to environment variable UserChoice. That would result on processing the prompt twice because of "Y " is neither case-insensitive equal "N" nor "Y" without deleting first all spaces. So UserChoice with YSPACE as value would result in running the prompt a second time with option N as defined as default in the batch file on second prompt execution which next results in an unexpected exit of batch file processing. Yes, secure usage of SET /P is really tricky, isn't it?

choice.exe exits with 0 in case of the user presses Ctrl+C or Ctrl+Break and answers next the question output by cmd.exe to exit batch file processing with N for no. For that reason the condition if not errorlevel 1 goto UserChoice is added to prompt the user once again for a definite answer on the prompt by batch file code with Y or N. Thanks to dialer for the information about this possible special use case.

The first line below the batch label :UseSetPrompt could be written also as:

set "UserChoice=N"

In this case the user choice input is predefined with N which means the user can hit just RETURN or ENTER (or Ctrl+C or Ctrl+Break and next N) to use the default choice.

The prompt text is output by command SET as written in the batch file. So the prompt text should end usually with a space character. The command CHOICE removes from prompt text all trailing normal spaces and horizontal tabs and then adds itself a space to the prompt text. Therefore the prompt text of command CHOICE can be written without or with a space at end. That does not make a difference on displayed prompt text on execution.

The order of user prompt evaluation could be also changed completely as suggested by dialer.

@echo off
setlocal EnableExtensions DisableDelayedExpansion
echo This is an example for prompting a user.
if exist "%SystemRoot%\System32\choice.exe" goto UseChoice

setlocal EnableExtensions EnableDelayedExpansion
set "UserChoice="
set /P "UserChoice=Are you sure [Y/N]? "
set "UserChoice=!UserChoice: =!"
if /I not "!UserChoice!" == "Y" endlocal & goto :EOF
goto Continue

%SystemRoot%\System32\choice.exe /C YN /N /M "Are you sure [Y/N]?"
if not errorlevel 2 if errorlevel 1 goto Continue
goto :EOF

echo So your are sure. Okay, let's go ...

This code results in continuation of batch file processing below the batch label :Continue if the user pressed definitely key Y. In all other cases the code for N is executed resulting in an exit of batch file processing with this code independent on user pressed really that key, or entered something different intentionally or by mistake, or pressed Ctrl+C or Ctrl+Break and decided next on prompt output by cmd to not cancel the processing of the batch file.

For even more details on usage of SET /P and CHOICE for prompting user for a choice from a list of options see answer on How to stop Windows command interpreter from quitting batch file execution on an incorrect user input?

Some more hints:

  1. IF compares the two strings left and right of the comparison operator with including the double quotes. So case-insensitive compared is not the value of UserChoice with N and Y, but the value of UserChoice surrounded by " with "N" and "Y".
  2. The IF comparison operators EQU and NEQ are designed primary for comparing two integers in range -2147483648 to 2147483647 and not for comparing two strings. EQU and NEQ work also for strings comparisons, but result on comparing strings in double quotes after a useless attempt to convert left string to an integer. EQU and NEQ can be used only with enabled command extensions. The comparison operators for string comparisons are == and not ... == which work even with disabled command extensions as even of MS-DOS and Windows 95/98/ME already supported them. For more details on IF comparison operators see Symbol equivalent to NEQ, LSS, GTR, etc. in Windows batch files.
  3. The command goto :EOF requires enabled command extensions to really exit batch file processing. For more details see Where does GOTO :EOF return to?

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

  • choice /?
  • echo /?
  • endlocal /?
  • goto /?
  • if /?
  • set /?
  • setlocal /?

See also:

Why do we use $rootScope.$broadcast in AngularJS?

  1. What does $rootScope.$broadcast do?

    $rootScope.$broadcast is sending an event through the application scope. Any children scope of that app can catch it using a simple: $scope.$on().

    It is especially useful to send events when you want to reach a scope that is not a direct parent (A branch of a parent for example)

    !!! One thing to not do however is to use $rootScope.$on from a controller. $rootScope is the application, when your controller is destroyed that event listener will still exist, and when your controller will be created again, it will just pile up more event listeners. (So one broadcast will be caught multiple times). Use $scope.$on() instead, and the listeners will also get destroyed.

  2. What is the difference between $rootScope.$broadcast & $rootScope.$broadcast.apply?

    Sometimes you have to use apply(), especially when working with directives and other JS libraries. However since I don't know that code base, I wouldn't be able to tell if that's the case here.

How do I use NSTimer?

Something like this:

NSTimer *timer;

    timer = [NSTimer scheduledTimerWithTimeInterval: 0.5
                     target: self
                     selector: @selector(handleTimer:)
                     userInfo: nil
                     repeats: YES];

xcode-select active developer directory error

XCode2: sudo xcode-select -s /Applications/Xcode\

Pay attention to the "\" to escape the space

CURL ERROR: Recv failure: Connection reset by peer - PHP Curl

This is a firewall issue, if you are using a VMware application, make sure the firewall on the antivirus is turned off or allowing connections.

If this server is on a secure network, please have a look at firewall rules of the server.

Thanks Ganesh PNS

jQuery selector for the label of a checkbox

This should do it:


If you have non alphanumeric characters in your id then you must surround the attr value with quotes:


Java enum - why use toString instead of name

While most people blindly follow the advice of the javadoc, there are very specific situations where you want to actually avoid toString(). For example, I'm using enums in my Java code, but they need to be serialized to a database, and back again. If I used toString() then I would technically be subject to getting the overridden behavior as others have pointed out.

Additionally one can also de-serialize from the database, for example, this should always work in Java:

MyEnum taco = MyEnum.valueOf(;

Whereas this is not guaranteed:

MyEnum taco = MyEnum.valueOf(MyEnum.TACO.toString());

By the way, I find it very odd for the Javadoc to explicitly say "most programmers should". I find very little use-case in the toString of an enum, if people are using that for a "friendly name" that's clearly a poor use-case as they should be using something more compatible with i18n, which would, in most cases, use the name() method.

Open source PDF library for C/C++ application?

It depends a bit on your needs. Some toolkits are better at drawing, others are better for writing text. Cairo has a pretty good for drawing (it support a wide range of screen and file types, including pdf), but it may not be ideal for good typography.

MIT vs GPL license

You are correct that the GPL is more restrictive than the MIT license.

You cannot include GPL code in a MIT licensed product. If you distribute a combined work that combines GPL and MIT code (except in some particular situations, e.g. 'mere aggregation'), that distribution must be compliant with the GPL.

You can include MIT licensed code in a GPL product. The whole combined work must be distributed in a way compliant with the GPL. If you have made changes to the MIT parts of the code, you would be required to publish the source for those changes if you distribute an application that contains GPL and MIT code.

If you are the copyright owner of the GPL code, you can of course choose to release that code under the MIT license instead - in that case it's your code and you can publish it under as many licenses as you want.

Code coverage for Jest built on top of Jasmine

If you are having trouble with --coverage not working it may also be due to having coverageReporters enabled without 'text' or 'text-summary' being added. From the docs: "Note: Setting this option overwrites the default values. Add "text" or "text-summary" to see a coverage summary in the console output." Source

How to add MVC5 to Visual Studio 2013?

You can look into Windows installed folder from here of your pc path:

C:\Program Files (x86)\Microsoft ASP.NET

View of Opened file where showing installed MVC 3, MVC 4

enter image description here

Node.js + Nginx - What now?

The best and simpler setup with Nginx and Nodejs is to use Nginx as an HTTP and TCP load balancer with proxy_protocol enabled. In this context, Nginx will be able to proxy incoming requests to nodejs, and also terminate SSL connections to the backend Nginx server(s), and not to the proxy server itself. (SSL-PassThrough)

In my opinion, there is no point in giving non-SSL examples, since all web apps are (or should be) using secure environments.

Example config for the proxy server, in /etc/nginx/nginx.conf

user  nginx;
worker_processes  1;
error_log  /var/log/nginx/error.log warn;
pid        /var/run/;
events {
    worker_connections  1024;
http {
  upstream webserver-http {
    server; #use a host port instead if using docker
    server; #use a host port instead if using docker
  upstream nodejs-http {
    server; #nodejs listening port
    server; #nodejs listening port
  server {
    location / {
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header X-Forwarded-Proto $scheme;
      proxy_set_header Host $http_host;
      proxy_set_header X-Forwarded-Host $server_name;
      proxy_set_header Connection "";
      add_header       X-Upstream $upstream_addr;
      proxy_redirect     off;
      proxy_connect_timeout  300;
      proxy_http_version 1.1;
      proxy_buffers 16 16k;
      proxy_buffer_size 16k;
      proxy_cache_background_update on;
      proxy_pass http://webserver-http$request_uri;
  server {
    location / {
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header X-Forwarded-Proto $scheme;
      proxy_set_header Host $http_host;
      proxy_set_header X-Forwarded-Host $server_name;
      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection "Upgrade";
      add_header       X-Upstream $upstream_addr;
      proxy_redirect     off;
      proxy_connect_timeout  300;
      proxy_http_version 1.1;
      proxy_buffers 16 16k;
      proxy_buffer_size 16k;
      proxy_cache_background_update on;
      proxy_pass http://nodejs-http$request_uri;
stream {
  upstream webserver-https {
    server; #use a host port instead if using docker
    server; #use a host port instead if using docker

  server {
    proxy_protocol on;
    tcp_nodelay on;
    listen 443;
    proxy_pass webserver-https;
  log_format proxy 'Protocol: $protocol - $status $bytes_sent $bytes_received $session_time';
  access_log  /var/log/nginx/access.log proxy;
  error_log /var/log/nginx/error.log debug;

Now, let's handle the backend webserver. /etc/nginx/nginx.conf:

user  nginx;
worker_processes  1;
error_log  /var/log/nginx/error.log warn;
pid        /var/run/;
load_module /etc/nginx/modules/; # GeoIP2
events {
    worker_connections  1024;
http {
    variables_hash_bucket_size 64;
    variables_hash_max_size 2048;
    server_tokens off;
    sendfile    on;
    tcp_nopush  on;
    tcp_nodelay on;
    autoindex off;
    keepalive_timeout  30;
    types_hash_bucket_size 256;
    client_max_body_size 100m;
    server_names_hash_bucket_size 256;
    include         mime.types;
    default_type    application/octet-stream;
    index  index.php index.html index.htm;
    # GeoIP2
    log_format  main    'Proxy Protocol Address: [$proxy_protocol_addr] '
                        '"$request" $remote_addr - $remote_user [$time_local] "$request" '
                        '$status $body_bytes_sent "$http_referer" '
                        '"$http_user_agent" "$http_x_forwarded_for"';

    # GeoIP2
    log_format  main_geo    'Original Client Address: [$realip_remote_addr]- Proxy Protocol Address: [$proxy_protocol_addr] '
                            'Proxy Protocol Server Address:$proxy_protocol_server_addr - '
                            '"$request" $remote_addr - $remote_user [$time_local] "$request" '
                            '$status $body_bytes_sent "$http_referer" '
                            '$geoip2_data_country_iso $geoip2_data_country_name';

    access_log  /var/log/nginx/access.log  main_geo; # GeoIP2
#===================== GEOIP2 =====================#
    geoip2 /usr/share/geoip/GeoLite2-Country.mmdb {
        $geoip2_metadata_country_build  metadata build_epoch;
        $geoip2_data_country_geonameid  country geoname_id;
        $geoip2_data_country_iso        country iso_code;
        $geoip2_data_country_name       country names en;
        $geoip2_data_country_is_eu      country is_in_european_union;
    #geoip2 /usr/share/geoip/GeoLite2-City.mmdb {
    #   $geoip2_data_city_name city names en;
    #   $geoip2_data_city_geonameid city geoname_id;
    #   $geoip2_data_continent_code continent code;
    #   $geoip2_data_continent_geonameid continent geoname_id;
    #   $geoip2_data_continent_name continent names en;
    #   $geoip2_data_location_accuracyradius location accuracy_radius;
    #   $geoip2_data_location_latitude location latitude;
    #   $geoip2_data_location_longitude location longitude;
    #   $geoip2_data_location_metrocode location metro_code;
    #   $geoip2_data_location_timezone location time_zone;
    #   $geoip2_data_postal_code postal code;
    #   $geoip2_data_rcountry_geonameid registered_country geoname_id;
    #   $geoip2_data_rcountry_iso registered_country iso_code;
    #   $geoip2_data_rcountry_name registered_country names en;
    #   $geoip2_data_rcountry_is_eu registered_country is_in_european_union;
    #   $geoip2_data_region_geonameid subdivisions 0 geoname_id;
    #   $geoip2_data_region_iso subdivisions 0 iso_code;
    #   $geoip2_data_region_name subdivisions 0 names en;

#=================Basic Compression=================#
    gzip on;
    gzip_disable "msie6";
    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 6;
    gzip_buffers 16 8k;
    gzip_http_version 1.1;
    gzip_types text/css text/xml text/plain application/javascript image/jpeg image/png image/gif image/x-icon image/svg+xml image/webp application/font-woff application/json application/ application/;
    gzip_static on;
    include /etc/nginx/sites-enabled/;

Now, let's configure the virtual host with this SSL and proxy_protocol enabled config at /etc/nginx/sites-available/

server {
    real_ip_header proxy_protocol;
    set_real_ip_from; #proxy server ip address
    #set_real_ip_from proxy; #proxy container hostname if you are using docker
    server_name; #Your current server ip address. It will redirect to the domain name.
    listen 80;
    listen 443 ssl http2;
    listen [::]:80;
    listen [::]:443 ssl http2;
    ssl_certificate     /etc/nginx/certs/;
    ssl_certificate_key /etc/nginx/certs/;
    ssl_dhparam /etc/nginx/ssl/dhparam.pem;
    return 301$request_uri;
server {
    real_ip_header proxy_protocol;
    set_real_ip_from; #proxy server ip address
    #set_real_ip_from proxy; #proxy container hostname if you are using docker
    listen       *:80;
    return 301$request_uri;
server {
    real_ip_header proxy_protocol;
    set_real_ip_from; #proxy server ip address
    #set_real_ip_from proxy; #proxy container hostname if you are using docker
    listen 80;
    listen 443 http2;
    listen [::]:80;
    listen [::]:443 ssl http2 ;
    ssl_certificate     /etc/nginx/certs/;
    ssl_certificate_key /etc/nginx/certs/;
    ssl_dhparam /etc/nginx/ssl/dhparam.pem;
    return 301$request_uri;
server {
    real_ip_header proxy_protocol;
    set_real_ip_from; #proxy server ip address
    #set_real_ip_from proxy; #proxy container hostname if you are using docker
    listen 443 proxy_protocol ssl http2;
    listen [::]:443 proxy_protocol ssl http2;
    root /var/www/html;
    charset UTF-8;
    add_header Strict-Transport-Security 'max-age=31536000; includeSubDomains; preload';
    add_header X-Frame-Options SAMEORIGIN;
    add_header X-Content-Type-Options nosniff;
    add_header X-XSS-Protection "1; mode=block";
    add_header Referrer-Policy no-referrer;
    ssl_prefer_server_ciphers on;
    ssl_protocols TLSv1.2 TLSv1.1 TLSv1;
    ssl_session_cache   shared:SSL:10m;
    ssl_session_timeout 10m;
    keepalive_timeout   70;
    ssl_buffer_size 1400;
    ssl_dhparam /etc/nginx/ssl/dhparam.pem;
    ssl_stapling on;
    ssl_stapling_verify on;
    resolver valid=86400;
    resolver_timeout 10;
    ssl_certificate     /etc/nginx/certs/;
    ssl_certificate_key /etc/nginx/certs/;
    ssl_trusted_certificate /etc/nginx/certs/;
location ~* \.(jpg|jpe?g|gif|png|ico|cur|gz|svgz|mp4|ogg|ogv|webm|htc|css|js|otf|eot|svg|ttf|woff|woff2)(\?ver=[0-9.]+)?$ {
    expires modified 1M;
    add_header Access-Control-Allow-Origin '*';
    add_header Pragma public;
    add_header Cache-Control "public, must-revalidate, proxy-revalidate";
    access_log off;
    location ~ /.well-known { #For issuing LetsEncrypt Certificates
        allow all;
location / {
    index index.php;
    try_files $uri $uri/ /index.php?$args;
error_page  404    /404.php;

location ~ \.php$ {
    try_files       $uri =404;
    fastcgi_index   index.php;
    fastcgi_pass    unix:/tmp/php7-fpm.sock;
    #fastcgi_pass    php-container-hostname:9000; (if using docker)
    fastcgi_pass_request_headers on;
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    fastcgi_param   SCRIPT_FILENAME  $document_root$fastcgi_script_name;
    fastcgi_intercept_errors on;
    fastcgi_ignore_client_abort off;
    fastcgi_connect_timeout 60;
    fastcgi_send_timeout 180;
    fastcgi_read_timeout 180;
    fastcgi_request_buffering on;
    fastcgi_buffer_size 128k;
    fastcgi_buffers 4 256k;
    fastcgi_busy_buffers_size 256k;
    fastcgi_temp_file_write_size 256k;
    include fastcgi_params;
location = /robots.txt {
    access_log off;
    log_not_found off;
location ~ /\. {
    deny  all;
    access_log off;
    log_not_found off;

And lastly, a sample of 2 nodejs webservers: First server:

var http = require('http');

http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello From Nodejs\n');
}).listen(8080, "");
console.log('Server running at');

Second server:

var http = require('http');

http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello From Nodejs\n');
}).listen(8080, "");
console.log('Server running at');

Now everything should be perfectly working and load-balanced.

A while back i wrote about How to set up Nginx as a TCP load balancer in Docker. Check it out if you are using Docker.

Chart won't update in Excel (2007)

As i tried pretty much ALL the presented solutions and since none worked in my case, I'll add my two cents here as well. Hopefully it helps someone else.

The consensus on this issue seems to be that we need to somehow force excel to redraw the graph since it is not doing it when it should.

My solution was to kill the X-Axis data and replace it with nothing, before changing it to what i wanted. Here my code:

With wsReport
    ActiveChart.FullSeriesCollection(1).XValues = "=" 'Kill data here
        .Range("A1").Select 'Forwhatever reason a Select statement was needed
        ActiveChart.FullSeriesCollection(1).XValues = "=tblRef[Secs]"
End With
End Sub

split python source code into multiple files?

Python has importing and namespacing, which are good. In Python you can import into the current namespace, like:

>>> from test import disp
>>> disp('World!')

Or with a namespace:

>>> import test
>>> test.disp('World!')

Is it possible to format an HTML tooltip (title attribute)?

No. But there are other options out there like Overlib, and jQuery that allow you this freedom.

Personally, I would suggest jQuery as the route to take. It's typically very unobtrusive, and requires no additional setup in the markup of your site (with the exception of adding the jquery script tag in your <head>).

What is the difference between Sprint and Iteration in Scrum and length of each Sprint?

"___ is largely an organizational issue caused by long hours, little down time, and continual peer, customer, and superior surveillance"

No this is not the definition of scrum, it is the wikipedia excerpt on the definition of burnout.

Dont do too many short 10 days sprints. You will burnout your team eventually. Use short sprints where you really need them, and don't do too many in a row. Think long-term. A distance runner always paces themselves for the full race and does sprints in short distances only where it matters.

If you burnout your team you can toss out all them fancy scrum charts, they won't do a thing for your team's plummeting productivity.

fatal: early EOF fatal: index-pack failed

Tangentially related and only useful in case you have no root access and manually extract Git from an RPM (with rpm2cpio) or other package (.deb, ..) into a subfolder. Typical use case: you try to use a newer version of Git over the outdated one on a corporate server.

If git clone fails with fatal: index-pack failed without early EOF mention but instead a help message about usage: git index-pack, there is a version mismatch and you need to run git with the --exec-path parameter:

git --exec-path=path/to/subfoldered/git/usr/bin/git clone <repo>

In order to have this happen automatically, specify in your ~/.bashrc:

export GIT_EXEC_PATH=path/to/subfoldered/git/usr/libexec

Get filename from input [type='file'] using jQuery

There is no jQuery function for this. You have to access the DOM element and check the files property.




GCC: array type has incomplete element type

The compiler needs to know the size of the second dimension in your two dimensional array. For example:

void print_graph(g_node graph_node[], double weight[][5], int nodes);

C# Regex for Guid

For C# .Net to find and replace any guid looking string from the given text,

Use this RegEx:


Example C# code:

var result = Regex.Replace(
      @"${ __UUID}", 

Surely works! And it matches & replaces the following styles, which are all equivalent and acceptable formats for a GUID.


Simulate Keypress With jQuery

You could try this SendKeys jQuery plugin:

$(element).sendkeys(string) inserts string at the insertion point in an input, textarea or other element with contenteditable=true. If the insertion point is not currently in the element, it remembers where the insertion point was when sendkeys was last called (if the insertion point was never in the element, it appends to the end).

How to retrieve the hash for the current commit in Git?

If you need to store the hash in a variable during a script, you can use

last_commit=$(git rev-parse HEAD);

Or, if you only want the first 10 characters (like does)

last_commit=$(git rev-parse --short=10 HEAD);

Private class declaration

private modifier will make your class inaccessible from outside, so there wouldn't be any advantage of this and I think that is why it is illegal and only public, abstract & final are permitted.

Note : Even you can not make it protected.

What is the difference between logical data model and conceptual data model?

Logical Database Model

Logical database modeling is required for compiling business requirements and representing the requirements as a model. It is mainly associated with the gathering of business needs rather than the database design. The information that needs to be gathered is about organizational units, business entities, and business processes.

Once the information is compiled, reports and diagrams are made, including these:

ERD–Entity relationship diagram shows the relationship between different categories of data and shows the different categories of data required for the development of a database. Business process diagram–It shows the activities of individuals within the company. It shows how the data moves within the organization based on which application interface can be designed. Feedback documentation by users.

Logical database models basically determine if all the requirements of the business have been gathered. It is reviewed by developers, management, and finally the end users to see if more information needs to be gathered before physical modeling starts.

Physical Database Model Physical database modeling deals with designing the actual database based on the requirements gathered during logical database modeling. All the information gathered is converted into relational models and business models. During physical modeling, objects are defined at a level called a schema level. A schema is considered a group of objects which are related to each other in a database. Tables and columns are made according to the information provided during logical modeling. Primary keys, unique keys, and foreign keys are defined in order to provide constraints. Indexes and snapshots are defined. Data can be summarized, and users are provided with an alternative perspective once the tables have been created.

Physical database modeling depends upon the software already being used in the organization. It is software specific. Physical modeling includes:

Server model diagram–It includes tables and columns and different relationships that exist within a database. Database design documentation. Feedback documentation of users.


1.Logical database modeling is mainly for gathering information about business needs and does not involve designing a database; whereas physical database modeling is mainly required for actual designing of the database. 2.Logical database modeling does not include indexes and constraints; the logical database model for an application can be used across various database software and implementations; whereas physical database modeling is software and hardware specific and has indexes and constraints. 3.Logical database modeling includes; ERD, business process diagrams, and user feedback documentation; whereas physical database modeling includes; server model diagram, database design documentation, and user feedback documentation.

Read more: Difference Between Logical and Physical Database Model | Difference Between | Logical vs Physical Database Model

Check that a variable is a number in UNIX shell


if echo "$var" | egrep -q '^\-?[0-9]+$'; then 
    echo "$var is an integer"
    echo "$var is not an integer"

tests (with var=2 etc.):

2 is an integer
-2 is an integer
2.5 is not an integer 
2b is not an integer


if echo "$var" | egrep -q '^\-?[0-9]*\.?[0-9]+$'; then 
    echo "$var is a number"
    echo "$var is not a number"

tests (with var=2 etc.):

2 is a number
-2 is a number
-2.6 is a number
-2.c6 is not a number
2. is not a number
2.0 is a number

How to set a ripple effect on textview or imageview on Android?

Ref :,



In python, how do I cast a class object to a dict

It's hard to say without knowing the whole context of the problem, but I would not override __iter__.

I would implement __what_goes_here__ on the class.

    d = {...whatever you need...}
    return d

How can I switch themes in Visual Studio 2012

Slightly off topic, but for those of you that want to modify the built-in colors of the Dark/Light themes you can use this little tool I wrote for Visual Studio 2012.

More info here:

Modify Visual Studio 2012 Dark (and Light) Themes

Source Code

Subtracting 1 day from a timestamp date

Use the INTERVAL type to it. E.g:


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

Then you can do the following on your query:

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


Tip 1

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


Tip 2

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

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

More info:

Date/Time Functions and Operators

datatype-datetime (Especial values).

check if "it's a number" function in Oracle

I'm against using when others so I would use (returning an "boolean integer" due to SQL not suppporting booleans)

create or replace function is_number(param in varchar2) return integer
   ret number;
    ret := to_number(param);
    return 1; --true
    when invalid_number then return 0;

In the SQL call you would use something like

select case when ( is_number( and ( >'0') ) 
            then 'Is a number greater than 0' 
            else 'it is not a number or is not greater than 0' 
       end as valuetype  
  from table myTable

Reading an integer from user input

Use this simple line:

int x = int.Parse(Console.ReadLine());

Finish an activity from another activity

See my answer to Stack Overflow question Finish All previous activities.

What you need is to add the Intent.FLAG_CLEAR_TOP. This flag makes sure that all activities above the targeted activity in the stack are finished and that one is shown.

Another thing that you need is the SINGLE_TOP flag. With this one you prevent Android from creating a new activity if there is one already created in the stack.

Just be wary that if the activity was already created, the intent with these flags will be delivered in the method called onNewIntent(intent) (you need to overload it to handle it) in the target activity.

Then in onNewIntent you have a method called restart or something that will call finish() and launch a new intent toward itself, or have a repopulate() method that will set the new data. I prefer the second approach, it is less expensive and you can always extract the onCreate logic into a separate method that you can call for populate.

String.Format not work in TypeScript

If you are using NodeJS, you can use the build-in util function:

import * as util from "util";
util.format('My string: %s', 'foo');

Document can be found here:

When to encode space to plus (+) or %20?

What's the difference: See other answers.

When use + instead of %20? Use + if, for some reason, you want to make the URL query string (?.....) or hash fragment (#....) more readable. Example: You can actually read this: (%2B = +)

But the following is a lot harder to read: (at least to me)

I would think + is unlikely to break anything, since Google uses + (see the 1st link above) and they've probably thought about this. I'm going to use + myself just because readable + Google thinks it's OK.

org.xml.sax.SAXParseException: Content is not allowed in prolog

If all else fails, open the file in binary to make sure there are no funny characters [3 non printable characters at the beginning of the file that identify the file as utf-8] at the beginning of the file. We did this and found some. so we converted the file from utf-8 to ascii and it worked.

How can I see the size of files and directories in linux?

Use ls command for files and du command for directories.

Checking File Sizes

ls -l filename   #Displays Size of the specified file
ls -l *          #Displays Size of All the files in the current directory
ls -al *         #Displays Size of All the files including hidden files in the current directory
ls -al dir/      #Displays Size of All the files including hidden files in the 'dir' directory

ls command will not list the actual size of directories(why?). Therefore, we use du for this purpose.

Checking Directory sizes

du -sh directory_name    #Gives you the summarized(-s) size of the directory in human readable(-h) format
du -bsh *                #Gives you the apparent(-b) summarized(-s) size of all the files and directories in the current directory in human readable(-h) format

Including -h option in any of the above commands (for Ex: ls -lh * or du -sh) will give you size in human readable format (kb, mb,gb, ...)

For more information see man ls and man du

How to mount the android img file under linux?

In Android file system, "system.img" and "userdata.img" are VMS Alpha executable. "system.img" and "userdata.img" have the contents of /system and /data directory on root file system. They are mapped on NAND devices with yaffs2 file system. Now, yaffs2 image file can not be mounted on linux PC. If you can, maybe you got some rom that not packed in yaffs2 file system. You can check those rom file by execute the command:

file <system.img/userdata.img>

If it show "VMS Alpha executable" then you can use "unyaffs" to extract it.

Regular expression to detect semi-colon terminated C++ for & while loops

I don't know that regex would handle something like that very well. Try something like this

line = line.Trim();
if(line.StartsWith("for") && line.EndsWith(";")){
    //your code here

How do you loop in a Windows batch file?

Conditionally perform a command several times.

  • syntax-FOR-Files

    FOR %%parameter IN (set) DO command 
  • syntax-FOR-Files-Rooted at Path

    FOR /R [[drive:]path] %%parameter IN (set) DO command 
  • syntax-FOR-Folders

    FOR /D %%parameter IN (folder_set) DO command 
  • syntax-FOR-List of numbers

    FOR /L %%parameter IN (start,step,end) DO command 
  • syntax-FOR-File contents

    FOR /F ["options"] %%parameter IN (filenameset) DO command 


    FOR /F ["options"] %%parameter IN ("Text string to process") DO command
  • syntax-FOR-Command Results

    FOR /F ["options"] %%parameter IN ('command to process') DO command


  • Take a set of data
  • Make a FOR Parameter %%G equal to some part of that data
  • Perform a command (optionally using the parameter as part of the command).
  • --> Repeat for each item of data

If you are using the FOR command at the command line rather than in a batch program, use just one percent sign: %G instead of %%G.

FOR Parameters

  • The first parameter has to be defined using a single character, for example the letter G.

  • FOR %%G IN ...

    In each iteration of a FOR loop, the IN ( ....) clause is evaluated and %%G set to a different value

    If this clause results in a single value then %%G is set equal to that value and the command is performed.

    If the clause results in a multiple values then extra parameters are implicitly defined to hold each. These are automatically assigned in alphabetical order %%H %%I %%J ...(implicit parameter definition)

    If the parameter refers to a file, then enhanced variable reference can be used to extract the filename/path/date/size.

    You can of course pick any letter of the alphabet other than %%G. but it is a good choice because it does not conflict with any of the pathname format letters (a, d, f, n, p, s, t, x) and provides the longest run of non-conflicting letters for use as implicit parameters.

jQuery AJAX form data serialize using PHP

Try this its working..

      $(function () {
          $('form').on('submit', function (e) {
                  type: 'post',
                  url: '<?php echo base_url();?>student_ajax/insert',
                  data: $('form').serialize(),
                  success: function (response) {
                      alert('form was submitted');
                  error:function() {

Using CSS for a fade-in effect on page load

In response to @A.M.K's question about how to do transitions without jQuery. A very simple example I threw together. If I had time to think this through some more, I might be able to eliminate the JavaScript code altogether:

    body {
        background-color: red;
        transition: background-color 2s ease-in;

    window.onload = function() { = '#00f';


youtube: link to display HD video by default

via Is there a way to link someone to a YouTube Video in HD 1080p quality?

Yes there is:

options are:

default|none: vq=auto;
Code for auto: vq=auto;
Code for 2160p: vq=hd2160;
Code for 1440p: vq=hd1440;
Code for 1080p: vq=hd1080;
Code for 720p: vq=hd720;
Code for 480p: vq=large;
Code for 360p: vq=medium;
Code for 240p: vq=small;

As mentioned, you have to use the /embed/ or /v/ URL.

Note: Some copyrighted content doesn't support be played in this way

Creating runnable JAR with Gradle

Thank you Konstantin, it worked like a charm with few nuances. For some reason, specifying main class as part of jar manifest did not quite work and it wanted the mainClassName attribute instead. Here is a snippet from build.gradle that includes everything to make it work:

plugins {
  id 'java' 
  id 'com.github.johnrengelman.shadow' version '1.2.2'
apply plugin: 'application'
apply plugin: 'com.github.johnrengelman.shadow'
mainClassName = 'com.acme.myapp.MyClassMain'
shadowJar {
    baseName = 'myapp'

After running gradle shadowJar you get myapp-{version}-all.jar in your build folder which can be run as java -jar myapp-{version}-all.jar.

Can't change z-index with JQuery


Return a "NULL" object if search result not found

There are several possible answers here. You want to return something that might exist. Here are some options, ranging from my least preferred to most preferred:

  • Return by reference, and signal can-not-find by exception.

    Attr& getAttribute(const string& attribute_name) const 
       //search collection
       //if found at i
            return attributes[i];
       //if not found
            throw no_such_attribute_error;

It's likely that not finding attributes is a normal part of execution, and hence not very exceptional. The handling for this would be noisy. A null value cannot be returned because it's undefined behaviour to have null references.

  • Return by pointer

    Attr* getAttribute(const string& attribute_name) const 
       //search collection
       //if found at i
            return &attributes[i];
       //if not found
            return nullptr;

It's easy to forget to check whether a result from getAttribute would be a non-NULL pointer, and is an easy source of bugs.

  • Use Boost.Optional

    boost::optional<Attr&> getAttribute(const string& attribute_name) const 
       //search collection
       //if found at i
            return attributes[i];
       //if not found
            return boost::optional<Attr&>();

A boost::optional signifies exactly what is going on here, and has easy methods for inspecting whether such an attribute was found.

Side note: std::optional was recently voted into C++17, so this will be a "standard" thing in the near future.

use video as background for div

Pure CSS method

It is possible to center a video inside an element just like a cover sized background-image without JS using the object-fit attribute or CSS Transforms.

2021 answer: object-fit

As pointed in the comments, it is possible to achieve the same result without CSS transform, but using object-fit, which I think it's an even better option for the same result:

.video-container {
    height: 300px;
    width: 300px;
    position: relative;

.video-container video {
  width: 100%;
  height: 100%;
  position: absolute;
  object-fit: cover;
  z-index: 0;

/* Just styling the content of the div, the *magic* in the previous rules */
.video-container .caption {
  z-index: 1;
  position: relative;
  text-align: center;
  color: #dc0000;
  padding: 10px;
<div class="video-container">
    <video autoplay muted loop>
        <source src="" type="video/mp4" />
    <div class="caption">
      <h2>Your caption here</h2>

Previous answer: CSS Transform

You can set a video as a background to any HTML element easily thanks to transform CSS property.

Note that you can use the transform technique to center vertically and horizontally any HTML element.

.video-container {
  height: 300px;
  width: 300px;
  overflow: hidden;
  position: relative;

.video-container video {
  min-width: 100%;
  min-height: 100%;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translateX(-50%) translateY(-50%);

/* Just styling the content of the div, the *magic* in the previous rules */
.video-container .caption {
  z-index: 1;
  position: relative;
  text-align: center;
  color: #dc0000;
  padding: 10px;
<div class="video-container">
  <video autoplay muted loop>
    <source src="" type="video/mp4" />
  <div class="caption">
    <h2>Your caption here</h2>

How to disable all <input > inside a form with jQuery?

To disable all form, as easy as write:

jQuery 1.6+

$("#form :input").prop("disabled", true);

jQuery 1.5 and below

$("#form :input").attr('disabled','disabled');

How to set an environment variable only for the duration of the script?

Just put

export HOME=/blah/whatever

at the point in the script where you want the change to happen. Since each process has its own set of environment variables, this definition will automatically cease to have any significance when the script terminates (and with it the instance of bash that has a changed environment).

How to implement reCaptcha for ASP.NET MVC?

For anybody else looking, here is a decent set of steps.

Don't forget to manually add your key in OnActionExecuting() like I did.

Python popen command. Wait until the command is finished

Force popen to not continue until all output is read by doing:


Center a button in a Linear layout

You can also set the width of the LinearLayout to wrap_content and use android:layout_centerInParent, android:layout_centerVertical="true":

<LinearLayout xmlns:android=""

<ImageButton android:id="@+id/btnFindMe" 

How to convert 1 to true or 0 to false upon model fetch

Here's another option that's longer but may be more readable:

Boolean(Number("0")); // false
Boolean(Number("1")); // true

shuffling/permutating a DataFrame in pandas

Sampling randomizes, so just sample the entire data frame.


How to get sp_executesql result into a variable?

This worked for me:


DECLARE @tbl Table (
    Id int,
    Account varchar(50),
    Amount int

-- Lots of code to Create my dynamic sql statement

insert into @tbl EXEC sp_executesql @SQL

select * from @tbl

How to make <input type="date"> supported on all browsers? Any alternatives?

      var datefield = document.createElement("input")
      datefield.setAttribute("type", "date")
      if (datefield.type != "date") { // if browser doesn't support input type="date", load files for jQuery UI Date Picker
         document.write('<link href="" rel="stylesheet" type="text/css" />\n')
         document.write('<script src=""><\/script>\n')
         document.write('<script src=""><\/script>\n')

    if (datefield.type != "date") { // if browser doesn't support input type="date", initialize date picker widget:
       jQuery(function($) { // on document.ready
       }); <- missing semicolon

   <b>Date of birth:</b>
   <input type="date" id="birthday" name="birthday" size="20">
   <input type="button" value="Submit" name="B1">


Convert a date format in PHP

function dateFormat($date)
    $m = preg_replace('/[^0-9]/', '', $date);
    if (preg_match_all('/\d{2}+/', $m, $r)) {
        $r = reset($r);
        if (count($r) == 4) {
            if ($r[2] <= 12 && $r[3] <= 31) return "$r[0]$r[1]-$r[2]-$r[3]"; // Y-m-d
            if ($r[0] <= 31 && $r[1] != 0 && $r[1] <= 12) return "$r[2]$r[3]-$r[1]-$r[0]"; // d-m-Y
            if ($r[0] <= 12 && $r[1] <= 31) return "$r[2]$r[3]-$r[0]-$r[1]"; // m-d-Y
            if ($r[2] <= 31 && $r[3] <= 12) return "$r[0]$r[1]-$r[3]-$r[2]"; //Y-m-d

        $y = $r[2] >= 0 && $r[2] <= date('y') ? date('y') . $r[2] : (date('y') - 1) . $r[2];
        if ($r[0] <= 31 && $r[1] != 0 && $r[1] <= 12) return "$y-$r[1]-$r[0]"; // d-m-y

var_dump(dateFormat('31/01/00')); // return 2000-01-31
var_dump(dateFormat('31/01/2000')); // return 2000-01-31
var_dump(dateFormat('01-31-2000')); // return 2000-01-31
var_dump(dateFormat('2000-31-01')); // return 2000-01-31
var_dump(dateFormat('20003101')); // return 2000-01-31

How to load a jar file at runtime

I googled a bit, and found this code here:

File file = getJarFileToLoadFrom();   
String lcStr = getNameOfClassToLoad();   
URL jarfile = new URL("jar", "","file:" + file.getAbsolutePath()+"!/");    
URLClassLoader cl = URLClassLoader.newInstance(new URL[] {jarfile });   
Class loadedClass = cl.loadClass(lcStr);   

Can anyone share opinions/comments/answers regarding this approach?

Easiest way to loop through a filtered list with VBA?

a = 2
x = 0

Do Until Cells(a, 1).Value = ""
If Rows(a).Hidden = False Then
x = Cells(a, 1).Value + x
End If
a = a + 1

End Sub

How to justify a single flexbox item (override justify-content)

AFAIK there is no property for that in the specs, but here is a trick I’ve been using: set the container element ( the one with display:flex ) to justify-content:space-around Then add an extra element between the first and second item and set it to flex-grow:10 (or some other value that works with your setup)

Edit: if the items are tightly aligned it's a good idea to add flex-shrink: 10; to the extra element as well, so the layout will be properly responsive on smaller devices.

Calculate percentage Javascript

For percent increase and decrease, using 2 different methods:

const a = 541
const b = 394

// Percent increase 
  `Increase (from ${b} to ${a}) => `,
  (((a/b)-1) * 100).toFixed(2) + "%",

// Percent decrease
  `Decrease (from ${a} to ${b}) => `,
  (((b/a)-1) * 100).toFixed(2) + "%",

// Alternatives, using .toLocaleString() 
  `Increase (from ${b} to ${a}) => `,
  ((a/b)-1).toLocaleString('fullwide', {maximumFractionDigits:2, style:'percent'}),

  `Decrease (from ${a} to ${b}) => `,
  ((b/a)-1).toLocaleString('fullwide', {maximumFractionDigits:2, style:'percent'}),

Practical uses of different data structures

Any ranking of various data structures will be at least partially tied to problem context. It would help to learn how to analyze time and space performance of algorithms. Typically, "big O notation" is used, e.g. binary search is in O(log n) time, which means that the time to search for an element is the log (in base 2, implicitly) of the number of elements. Intuitively, since every step discards half of the remaining data as irrelevant, doubling the number of elements will increases the time by 1 step. (Binary search scales rather well.) Space performance concerns how the amount of memory grows for larger data sets. Also, note that big-O notation ignores constant factors - for smaller data sets, an O(n^2) algorithm may still be faster than an O(n * log n) algorithm that has a higher constant factor. Complex algorithms often have more work to do on startup.

Besides time and space, other characteristics include whether a data structure is sorted (trees and skiplists are sorted, hash tables are not), persistence (binary trees can reuse pointers from older versions, while hash tables are modified in place), etc.

While you'll need to learn the behavior of several data structures to be able to compare them, one way to develop a sense for why they differ in performance is to closely study a few. I'd suggest comparing singly-linked lists, binary search trees, and skip lists, all of which are relatively simple, but have very different characteristics. Think about how much work it takes to find a value, add a new value, find all values in order, etc.

There are various texts on analyzing algorithms / data structure performance that people recommend, but what really made them make sense to me was learning OCaml. Dealing with complex data structures is ML's strong suit, and their behavior is much clearer when you can avoid pointers and memory management as in C. (Learning OCaml just to understand data structures is almost certainly the long way around, though. :) )

How do I get the path of a process in Unix / Linux

I use:

ps -ef | grep 786

Replace 786 with your PID or process name.

JQuery - how to select dropdown item based on value

May be too late to answer, but at least some one will get help.

You can try two options:

This is the result when you want to assign based on index value, where '0' is Index.

 $('#mySelect').prop('selectedIndex', 0);

don't use 'attr' since it is deprecated with latest jquery.

When you want to select based on option value then choose this :


where 'fg' is the option value

Formatting dates on X axis in ggplot2

To show months as Jan 2017 Feb 2017 etc:

scale_x_date(date_breaks = "1 month", date_labels =  "%b %Y") 

Angle the dates if they take up too much space:

theme(axis.text.x=element_text(angle=60, hjust=1))

Google Play on Android 4.0 emulator

Playstore + Google Play Services In Linux(Ubuntu 14.04)

Download Google apps (GoogleLoginService.apk , GoogleServicesFramework.apk )

from here

and Download ( Phonesky.apk) from here


cd -Android SDK's tools Location-


Android/Sdk/tools$ ./emulator64-x86 -avd Kitkat -partition-size 566 -no-audio -no-boot-anim


cd Android/Sdk/platform-tools platform-tools$ adb shell mount -o remount,rw -t yaffs2 /dev/block/mtdblock0 /system

platform-tools$ adb shell chmod 777 /system/app

platform-tools$ adb push /home/nazmul/Downloads/GoogleLoginService.apk /system/app/.


platform-tools$ adb push /home/nazmul/Downloads/GoogleServicesFramework.apk /system/app/. platform-tools$ adb push /home/nazmul/Downloads/Phonesky.apk /system/app/. platform-tools$ adb shell rm /system/app/SdkSetup*

Splitting on last delimiter in Python string?

You can use rsplit


To get the string from reverse.

How to convert string to long

import org.apache.commons.lang.math.NumberUtils;

This will handle null


How to make a DIV always float on the screen in top right corner?

Use position: fixed, and anchor it to the top and right sides of the page:

#fixed-div {
    position: fixed;
    top: 1em;
    right: 1em;

IE6 does not support position: fixed, however. If you need this functionality in IE6, this purely-CSS solution seems to do the trick. You'll need a wrapper <div> to contain some of the styles for it to work, as seen in the stylesheet.

What are NDF Files?

Secondary data files are optional, are user-defined, and store user data. Secondary files can be used to spread data across multiple disks by putting each file on a different disk drive. Additionally, if a database exceeds the maximum size for a single Windows file, you can use secondary data files so the database can continue to grow.

Source: MSDN: Understanding Files and Filegroups

The recommended file name extension for secondary data files is .ndf, but this is not enforced.

Mysql - delete from multiple tables with one query

You can define foreign key constraints on the tables with ON DELETE CASCADE option.

Then deleting the record from parent table removes the records from child tables.

Check this link :

sql - insert into multiple tables in one query

MySQL doesn't support multi-table insertion in a single INSERT statement. Oracle is the only one I'm aware of that does, oddly...


Escaping Strings in JavaScript

You can also use this

let str = "hello single ' double \" and slash \\ yippie";

let escapeStr = escape(str);
document.write("<b>str : </b>"+str);
document.write("<br/><b>escapeStr : </b>"+escapeStr);
document.write("<br/><b>unEscapeStr : </b> "+unescape(escapeStr));

Setting default checkbox value in Objective-C?

Documentation on UISwitch says:

[mySwitch setOn:NO]; 

In Interface Builder, select your switch and in the Attributes inspector you'll find State which can be set to on or off.

capture div into image using html2canvas didn't work for me... just a blank page rendered... but I was able to make the png appear on the page by replacing the src attribute of a pre-existing img element created as the target.

     element_to_png("container", "testhtmltocanvasimg");_x000D_
function element_to_png(srcElementID, targetIMGid){_x000D_
    console.log("element_to_png called for element id " + srcElementID);_x000D_
    html2canvas($("#"+srcElementID)[0]).then( function (canvas) {_x000D_
        var myImage = canvas.toDataURL("image/png");_x000D_
        $("#"+targetIMGid).attr("src", myImage);_x000D_
  console.log("html2canvas completed.  png rendered to " + targetIMGid);_x000D_
<div id="testhtmltocanvasdiv" class="mt-3">_x000D_
   <img src="" id="testhtmltocanvasimg">_x000D_

I can then right-click on the rendered png and "save as". May be just as easy to use the "snipping tool" to capture the element, but html2canvas is an certainly an interesting bit of code!

PHP, get file name without file extension

in my case, i use below. I don't care what is its extention. :D i think it will help you

$exploded_filepath = explode(".", $filepath_or_URL);
$extension = end($exploded_filepath);
echo basename($filepath_or_URL, ".".$extension ); //will print out the the name without extension.

Get SSID when WIFI is connected

I found interesting solution to get SSID of currently connected Wifi AP. You simply need to use iterate WifiManager.getConfiguredNetworks() and find configuration with specific WifiInfo.getNetworkId()

My example

in Broadcast receiver with action WifiManager.NETWORK_STATE_CHANGED_ACTION I'm getting current connection state from intent

NetworkInfo nwInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);

If NetworkInfo.getState is equal to NetworkInfo.State.CONNECTED then i can get current WifiInfo object

WifiManager wifiManager = (WifiManager) getSystemService (Context.WIFI_SERVICE);
WifiInfo info = wifiManager.getConnectionInfo ();

And after that

public String findSSIDForWifiInfo(WifiManager manager, WifiInfo wifiInfo) {

    List<WifiConfiguration> listOfConfigurations = manager.getConfiguredNetworks();

    for (int index = 0; index < listOfConfigurations.size(); index++) {
        WifiConfiguration configuration = listOfConfigurations.get(index);
        if (configuration.networkId == wifiInfo.getNetworkId()) {
            return configuration.SSID;

    return null;

And very important thing this method doesn't require Location nor Location Permisions

In API29 Google redesigned Wifi API so this solution is outdated for Android 10.

How to avoid 'undefined index' errors?

foreach($i=0; $i<10; $i++){
    $v = @(array)$v;   
    // this could help defining $v as an array. 
    //@ is to supress undefined variable $v

    array_push($v, $i);

How to plot all the columns of a data frame in R

You can jump through hoops and convert your solution to a lapply, sapply or apply call. (I see @jonw shows one way to do this.) Other than that what you have already is perfectly acceptable code.

If these are all a time series or similar then the following might be a suitable alternative, which plots each series in it's own panel on a single plotting region. We use the zoo package as it handles ordered data like this very well indeed.

## example data
dat <- data.frame(X = cumsum(rnorm(100)), Y = cumsum(rnorm(100)),
                  Z = cumsum(rnorm(100)))
## convert to multivariate zoo object
datz <- zoo(dat)
## plot it

Which gives: Example of zoo plotting capabilities

How do I pass a class as a parameter in Java?

Construct your method to accept it-

public <T> void printClassNameAndCreateList(Class<T> className){
    //example access 1

    //example access 2
    ArrayList<T> list = new ArrayList<T>();
    //note that if you create a list this way, you will have to cast input

Call the method-


You can also restrict the type of class, for example, this is one of the methods from a library I made-

protected Class postExceptionActivityIn;

protected <T extends PostExceptionActivity>  void  setPostExceptionActivityIn(Class <T> postExceptionActivityIn) {
    this.postExceptionActivityIn = postExceptionActivityIn;

For more information, search Reflection and Generics.

How do I install SciPy on 64 bit Windows?

Another alternative:

Free and includes lots of stuff meant to work together smoothly.

This person says

Did you try linux.pythonxy ? ( ).

It's 64 bit ready ...

Though I'm not quite sure what that means.


This appears to be dead. I use Anaconda now, which has 32-bit or 64-bit installers.

String to HtmlDocument

Using Html Agility Pack as suggested by SLaks, this becomes very easy:

string html = webClient.DownloadString(url);
var doc = new HtmlDocument();

HtmlNode specificNode = doc.GetElementById("nodeId");
HtmlNodeCollection nodesMatchingXPath = doc.DocumentNode.SelectNodes("x/path/nodes");

Convert Unix timestamp into human readable date using MySQL

Need a unix timestamp in a specific timezone?

Here's a one liner if you have quick access to the mysql cli:

mysql> select convert_tz(from_unixtime(1467095851), 'UTC', 'MST') as 'local time';

| local time          |
| 2016-06-27 23:37:31 |

Replace 'MST' with your desired timezone. I live in Arizona thus the conversion from UTC to MST.

Way to ng-repeat defined number of times instead of repeating over array?

Heres an answer for angular 1.2.x

Basically it is the same, with the slight modification of of the ng-repeat

<li ng-repeat="i in getNumber(myNumber) track by $index">

here is the fiddle:

this is because angular 1.2 doesn't allow duplicate values in the directive. This means if you are trying to do the following, you will get an error.

<li ng-repeat="x in [1,1,1]"></li>

Parse rfc3339 date strings in Python?

You can use dateutil.parser.parse (install with python -m pip install python-dateutil) to parse strings into datetime objects.

dateutil.parser.parse will attempt to guess the format of your string, if you know the exact format in advance then you can use datetime.strptime which you supply a format string to (see Brent Washburne's answer).

from dateutil.parser import parse

a = "2012-10-09T19:00:55Z"

b = parse(a)

# 1 (equal to a Tuesday)

A CSS selector to get last visible div

It is not possible with CSS, however you could do this with jQuery.





        <li>Item 1</li>
        <li>Item 2</li>
        <li>Item 3</li>
        <li class="hideme">Item 4</li>    


.hideme {

.red {
    color: red;

jQuery (previous solution):

var $items = $($("li").get().reverse());

$items.each(function() {

    if ($(this).css("display") != "none") {
        return false;


Very simple C# CSV reader

This is what I used in a project, parses a single line of data.

    private string[] csvParser(string csv, char separator = ',')
        List <string> = new <string>();
        string[] temp = csv.Split(separator);
        int counter = 0;
        string data = string.Empty;
        while (counter < temp.Length)
            data = temp[counter].Trim();
            if (data.Trim().StartsWith("\""))
                bool isLast = false;
                while (!isLast && counter < temp.Length)
                    data += separator.ToString() + temp[counter + 1];
                    isLast = (temp[counter].Trim().EndsWith("\""));

        return parsed.ToArray();


Creating a file name as a timestamp in a batch job

Maybe this can help:

echo off
@prompt set date=$d$_ set time=$t$h$h$h
echo some log >> %date% %time%.log


echo off
set v=%date%.log
echo some log >> %v%

How can I extract all values from a dictionary in Python?

Pythonic duck-typing should in principle determine what an object can do, i.e., its properties and methods. By looking at a dictionary object one may try to guess it has at least one of the following: dict.keys() or dict.values() methods. You should try to use this approach for future work with programming languages whose type checking occurs at runtime, especially those with the duck-typing nature.

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

I have improved @dacoinminster answer and this is the result with an example to share your app:

// Intents with SEND action
PackageManager packageManager = context.getPackageManager();
Intent sendIntent = new Intent(Intent.ACTION_SEND);
List<ResolveInfo> resolveInfoList = packageManager.queryIntentActivities(sendIntent, 0);

List<LabeledIntent> intentList = new ArrayList<LabeledIntent>();
Resources resources = context.getResources();

for (int j = 0; j < resolveInfoList.size(); j++) {
    ResolveInfo resolveInfo = resolveInfoList.get(j);
    String packageName = resolveInfo.activityInfo.packageName;
    Intent intent = new Intent();
    intent.setComponent(new ComponentName(packageName,;

    if (packageName.contains("twitter")) {
        intent.putExtra(Intent.EXTRA_TEXT, resources.getString(R.string.twitter) + "" + context.getPackageName());
    } else {
        // skip android mail and gmail to avoid adding to the list twice
        if (packageName.contains("") || packageName.contains("")) {
        intent.putExtra(Intent.EXTRA_TEXT, resources.getString(R.string.largeTextForFacebookWhatsapp) + "" + context.getPackageName());

    intentList.add(new LabeledIntent(intent, packageName, resolveInfo.loadLabel(packageManager), resolveInfo.icon));

Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:"));
emailIntent.putExtra(Intent.EXTRA_SUBJECT, resources.getString(R.string.subjectForMailApps));
emailIntent.putExtra(Intent.EXTRA_TEXT, resources.getString(R.string.largeTextForMailApps) + "" + context.getPackageName());

context.startActivity(Intent.createChooser(emailIntent, resources.getString(R.string.compartirEn)).putExtra(Intent.EXTRA_INITIAL_INTENTS, intentList.toArray(new LabeledIntent[intentList.size()])));

How to validate an Email in PHP?

User data is very important for a good developer, so don't ask again and again for same data, use some logic to correct some basic error in data.

Before validation of Email: First you have to remove all illegal characters from email.

//This will Remove all illegal characters from email
$email = filter_var($email, FILTER_SANITIZE_EMAIL);

after that validate your email address using this filter_var() function.

filter_var($email, FILTER_VALIDATE_EMAIL)) // To Validate the email

For e.g.

$email = "[email protected]";

// Remove all illegal characters from email
$email = filter_var($email, FILTER_SANITIZE_EMAIL);

// Validate email
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo $email." is a valid email address";
} else {
    echo $email." is not a valid email address";

Set background image on grid in WPF using C#

All of this can easily be acheived in the xaml by adding the following code in the grid

        <ImageBrush ImageSource="/MyProject;component/Images/bg.png"/>     

Left for you to do, is adding a folder to the solution called 'Images' and adding an existing file to your new 'Images' folder, in this case called 'bg.png'

How do you reset the stored credentials in 'git credential-osxkeychain'?

Try running /Applications/Utilities/Keychain Access.

Bulk insert with SQLAlchemy ORM

SQLAlchemy introduced that in version 1.0.0:

Bulk operations - SQLAlchemy docs

With these operations, you can now do bulk inserts or updates!

For instance (if you want the lowest overhead for simple table INSERTs), you can use Session.bulk_insert_mappings():

loadme = [(1, 'a'),
          (2, 'b'),
          (3, 'c')]
dicts = [dict(bar=t[0], fly=t[1]) for t in loadme]

s = Session()
s.bulk_insert_mappings(Foo, dicts)

Or, if you want, skip the loadme tuples and write the dictionaries directly into dicts (but I find it easier to leave all the wordiness out of the data and load up a list of dictionaries in a loop).

Installing Apple's Network Link Conditioner Tool

  1. Remove "Network Link Conditioner", open "System Preferences", press CTRL and click the "Network Link Conditioner" icon. Select "Remove".
  2. Restart your computer
  3. Download the dmg "Hardware IO tools" for your XCode version from, you need to be logged in to do this.
  4. Open it and install "Network Link Conditioner"
  5. Restart your computer one last time.

How to use cURL to send Cookies?

You are using a wrong format in your cookie file. As curl documentation states, it uses an old Netscape cookie file format, which is different from the format used by web browsers. If you need to create a curl cookie file manually, this post should help you. In your example the file should contain following line   FALSE   /   FALSE   0   USER_TOKEN  in

having 7 TAB-separated fields meaning domain, tailmatch, path, secure, expires, name, value.

Vertically centering a div inside another div

When your height is not set (auto); you can give inner div some padding (top and bottom) to make it vertically center:

    <div style="padding-top:20px;padding-bottom:20px">

VB6 IDE cannot load MSCOMCTL.OCX after update KB 2687323

The solution for me is to install this VB6 patch. I'm on Server2008 (32-bit).

It makes me sad that we're still talking about this in 2014... but here it is. :)

From puetzk's comment: These are outdated: you want to be using Microsoft Visual Basic 6.0 Service Pack 6 Cumulative Update (kb957924).

Send mail via CMD console

Scenario: Your domain: Domain you wish to send to:

1. Determine the mail server you're sending to. Open a CMD prompt Type

 set q=mx


Non-authoritative answer: MX preference = 50, mail exchanger = 

EDIT Be sure to type exit to terminate NSLOOKUP.

2. Connect to their mail server

SMTP communicates over port 25. We will now try to use TELNET to connect to their mail server ""

Open a CMD prompt


You should see something like this as a response:

220 ESMTP 6si6253627yxg.6

Be aware that different servers will come up with different greetings but you should get SOMETHING. If nothing comes up at this point there are 2 possible problems. Port 25 is being blocked at your firewall, or their server is not responding. Try a different domain, if that works then it's not you.

3. Send an Email

Now, use simple SMTP commands to send a test email. This is very important, you CANNOT use the backspace key, it will work onscreen but not be interpreted correctly. You have to type these commands perfectly.

mail from:<[email protected]> 
rcpt to:<[email protected]> 
This is a test, please do not respond

So, what does that all mean? EHLO - introduce yourself to the mail server HELO can also be used but EHLO tells the server to use the extended command set (not that we're using that).

MAIL FROM - who's sending the email. Make sure to place this is the greater than/less than brackets as many email servers will require this (Postini).

RCPT TO - who you're sending it to. Again you need to use the brackets. See Step #4 on how to test relaying mail!

DATA - tells the SMTP server that what follows is the body of your email. Make sure to hit "Enter" at the end.

. - the period alone on the line tells the SMTP server you're all done with the data portion and it's clear to send the email.

quit - exits the TELNET session.

4. Test SMTP relay Testing SMTP relay is very easy, and simply requires a small change to the above commands. See below:

mail from:<[email protected]> 
rcpt to:<[email protected]> 
This is a test, please do not respond 

See the difference? On the RCPT TO line, we're sending to a domain that is not controlled by the SMTP server we're sending to. You will get an immediate error is SMTP relay is turned off. If you're able to continue and send an email, then relay is allowed by that server.

How to clear a data grid view

refresh the datagridview and refresh the datatable


How to convert vector to array

std::vector<double> vec;
double* arr =;

Java SSL: how to disable hostname verification

I also had the same problem while accessing RESTful web services. And I their with the below code to overcome the issue:

public class Test {
    //Bypassing the SSL verification to execute our code successfully 
    static {

    public static void main(String[] args) {    
        //Access HTTPS URL and do something    
    //Method used for bypassing SSL verification
    public static void disableSSLVerification() {

        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            public[] getAcceptedIssuers() {
                return null;

            public void checkClientTrusted(X509Certificate[] certs, String authType) {

            public void checkServerTrusted(X509Certificate[] certs, String authType) {

        } };

        SSLContext sc = null;
        try {
            sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new;
        } catch (KeyManagementException e) {
        } catch (NoSuchAlgorithmException e) {

        HostnameVerifier allHostsValid = new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;

It worked for me. try it!!

Convert generic list to dataset in C#

I apologize for putting an answer up to this question, but I figured it would be the easiest way to view my final code. It includes fixes for nullable types and null values :-)

    public static DataSet ToDataSet<T>(this IList<T> list)
        Type elementType = typeof(T);
        DataSet ds = new DataSet();
        DataTable t = new DataTable();

        //add a column to table for each public property on T
        foreach (var propInfo in elementType.GetProperties())
            Type ColType = Nullable.GetUnderlyingType(propInfo.PropertyType) ?? propInfo.PropertyType;

            t.Columns.Add(propInfo.Name, ColType);

        //go through each property on T and add each value to the table
        foreach (T item in list)
            DataRow row = t.NewRow();

            foreach (var propInfo in elementType.GetProperties())
                row[propInfo.Name] = propInfo.GetValue(item, null) ?? DBNull.Value;


        return ds;

using scp in terminal

You can download in the current directory with a . :

cd # by default, goes to $HOME
scp me@host:/path/to/file .

or in you HOME directly with :

scp me@host:/path/to/file ~

NoClassDefFoundError for code in an Java library on Android

I tried all of the above said solutions but did not worked out for me, Here is what i did to get it done project-> config build path-> order and export-> move dependent project on top

Convert unix time to readable date in pandas dataframe

Alternatively, by changing a line of the above code:

# = d: datetime.strptime(d, "%Y-%m-%d")) = d: datetime.datetime.fromtimestamp(int(d)).strftime('%Y-%m-%d'))

It should also work.

Send email with PHP from html form on submit with the same script

PHP script to connect to a SMTP server and send email on Windows 7

Sending an email from PHP in Windows is a bit of a minefield with gotchas and head scratching. I'll try to walk you through one instance where I got it to work on Windows 7 and PHP 5.2.3 under (IIS) Internet Information Services webserver.

I'm assuming you don't want to use any pre-built framework like CodeIgniter or Symfony which contains email sending capability. We'll be sending an email from a standalone PHP file. I acquired this code from under the codeigniter hood (under system/libraries) and modified it so you can just drop in this Email.php file and it should just work.

This should work with newer versions of PHP. But you never know.

Step 1, You need a username/password with an SMTP server:

I'm using the smtp server from which is already created and setup for me. If you don't have this you can't proceed. You should be able to use an email client like thunderbird, evolution, Microsoft Outlook, to specify your smtp server and then be able to send emails through there.

Step 2, Create your Hello World Email file:

I'm assuming you are using IIS. So create a file called index.php under C:\inetpub\wwwroot and put this code in there:



  $c = new CI_Email();

  $c->from("[email protected]");
  $c->to("[email protected]");
  $c->subject("Celestial Temple");
  $c->message("Dominion reinforcements on the way.");
  echo "done";

You should be able to visit this index.php by navigating to localhost/index.php in a browser, it will spew errors because Email.php is missing. But make sure you can at least run it from the browser.

Step 3, Create a file called Email.php:

Create a new file called Email.php under C:\inetpub\wwwroot.

Copy/paste this PHP code into Email.php:

Since there are many kinds of smtp servers, you will have to manually fiddle with the settings at the top of Email.php. I've set it up so it automatically works with, but your smtp server might be different.

For example:

  1. Set the smtp_port setting to the port of your smtp server.
  2. Set the smtp_crypto setting to what your smtp server needs.
  3. Set the $newline and $crlf so it's compatible with what your smtp server uses. If you pick wrong, the smtp server may ignore your request without error. I use \r\n, for you maybe \n is required.

The linked code is too long to paste as a stackoverflow answer, If you want to edit it, leave a comment in here or through github and I'll change it.

Step 4, make sure your php.ini has ssl extension enabled:

Find your PHP.ini file and uncomment the


So it looks like:


Step 5, Run the index.php file you just made in a browser:

You should get the following output:

220 Microsoft ESMTP MAIL Service ready at 
Wed, 16 Apr 2014 15:43:58 -0400 250 2.6.0 
<[email protected]> Queued mail for delivery 


Step 6, check your email, and spam folder:

Visit the email account for [email protected] and you should have received an email. It should arrive within 5 or 10 seconds. If you does not, inspect the errors returned on the page. If that doesn't work, try mashing your face on the keyboard on google while chanting: "working at the grocery store isn't so bad."

How can I select an element in a component template?

Note: This doesn't apply to Angular 6 and above as ElementRef became ElementRef<T> with T denoting the type of nativeElement.

I would like to add that if you are using ElementRef, as recommended by all answers, then you will immediately encounter the problem that ElementRef has an awful type declaration that looks like

export declare class ElementRef {
  nativeElement: any;

this is stupid in a browser environment where nativeElement is an HTMLElement.

To workaround this you can use the following technique

import {Inject, ElementRef as ErrorProneElementRef} from '@angular/core';

interface ElementRef {
  nativeElement: HTMLElement;

@Component({...}) export class MyComponent {
  constructor(@Inject(ErrorProneElementRef) readonly elementRef: ElementRef) { }

What is an MDF file?

Just to make this absolutely clear for all:

A .MDF file is “typically” a SQL Server data file however it is important to note that it does NOT have to be.

This is because .MDF is nothing more than a recommended/preferred notation but the extension itself does not actually dictate the file type.

To illustrate this, if someone wanted to create their primary data file with an extension of .gbn they could go ahead and do so without issue.

To qualify the preferred naming conventions:

  • .mdf - Primary database data file.
  • .ndf - Other database data files i.e. non Primary.
  • .ldf - Log data file.

how to use List<WebElement> webdriver

Try with below logic


List<WebElement> allElements=driver.findElements(By.cssSelector(".list.list-categories li"));

for(WebElement ele :allElements) {
    System.out.println("Name + Number===>"+ele.getText());
    String s=ele.getText();
    s=s.substring(s.indexOf("(")+1, s.indexOf(")"));

Name + Number===>Vše (950)
Name + Number===>Byty (181)
Name + Number===>Domy (512)
Name + Number===>Pozemky (172)
Name + Number===>Chaty (28)
Name + Number===>Zemedelské objekty (5)
Name + Number===>Komercní objekty (30)
Name + Number===>Ostatní (22)

Custom Cell Row Height setting in storyboard is not responding

Open the storyboard in the XML view and try to edit the rowHeight attribute of the wanted element.

It worked for me when I tried to set custom rowHeight for my prototyped row. It's not working via inspector, but via XML it works.

How to use hex() without 0x in Python?

>>> format(3735928559, 'x')

Jackson enum Serializing and DeSerializer

I did it like this :

// Your JSON
{"event":"forgot password"}

// Your class to map 
public class LoggingDto {
    @JsonProperty(value = "event")
    private FooEnum logType;

//Your enum
public enum FooEnum {

    DATA_LOG ("Dummy 1"),
    DATA2_LOG ("Dummy 2"),
    DATA3_LOG ("forgot password"),
    DATA4_LOG ("Dummy 4"),
    DATA5_LOG ("Dummy 5"),
    UNKNOWN ("");

    private String fullName;

    FooEnum(String fullName) {
        this.fullName = fullName;

    public String getFullName() {
        return fullName;

    public static FooEnum getLogTypeFromFullName(String fullName) {
        for (FooEnum logType : FooEnum.values()) {
            if (logType.fullName.equals(fullName)) {
                return logType;
        return UNKNOWN;


So the value of the property "logType" for class LoggingDto will be DATA3_LOG