Programs & Examples On #Filereferencelist

How to make the background DIV only transparent using CSS

I don't know if this has changed. But from my experience. nested elements have a maximum opacity equal to the fathers.

Which mean:

<div id="a">
<div id="b">

Div#a has 0.6 opacity
div#b has 1 opacity

Has #b is within #a then it's maximum opacity is always 0.6

If #b would have 0.5 opacity. In reallity it would be 0.6*0.5 == 0.3 opacity

How to make the division of 2 ints produce a float instead of another int?

JLS Standard

JLS 7 15.17.2. Division Operator / says:

Integer division rounds toward 0. That is, the quotient produced for operands n and d that are integers after binary numeric promotion (§5.6.2) is an integer value q whose magnitude is as large as possible while satisfying |d · q| = |n|. Moreover, q is positive when |n| = |d| and n and d have the same sign, but q is negative when |n| = |d| and n and d have opposite signs.

This is why 1/2 does not give a float.

Converting just either one to float as in (float)1/2 suffices because 15.17. Multiplicative Operators says:

Binary numeric promotion is performed on the operands

and 5.6.2. Binary Numeric Promotion says:

  • If either operand is of type double, the other is converted to double.
  • Otherwise, if either operand is of type float, the other is converted to float

How to empty a Heroku database

If you are logged in from the console, this will do the job in the latest heroku toolbelt,

heroku pg:reset --confirm database-name

How to retrieve records for last 30 minutes in MS SQL?

SQL Server uses Julian dates so your 30 means "30 calendar days". getdate() - 0.02083 means "30 minutes ago".

How is "mvn clean install" different from "mvn install"?

Maven lets you specify either goals or lifecycle phases on the command line (or both).

clean and install are two different phases of two different lifecycles, to which different plugin goals are bound (either per default or explicitly in your pom.xml)

The clean phase, per convention, is meant to make a build reproducible, i.e. it cleans up anything that was created by previous builds. In most cases it does that by calling clean:clean, which deletes the directory bound to ${} (usually called "target")

Use of the MANIFEST.MF file in Java

Manifest.MF contains information about the files contained in the JAR file.

Whenever a JAR file is created a default file is created inside META-INF folder and it contains the default entries like this:

Manifest-Version: 1.0
Created-By: 1.7.0_06 (Oracle Corporation)

These are entries as “header:value” pairs. The first one specifies the manifest version and second one specifies the JDK version with which the JAR file is created.

Main-Class header: When a JAR file is used to bundle an application in a package, we need to specify the class serving an entry point of the application. We provide this information using ‘Main-Class’ header of the manifest file,

Main-Class: {fully qualified classname}

The ‘Main-Class’ value here is the class having main method. After specifying this entry we can execute the JAR file to run the application.

Class-Path header: Most of the times we need to access the other JAR files from the classes packaged inside application’s JAR file. This can be done by providing their fully qualified paths in the manifest file using ‘Class-Path’ header,

Class-Path: {jar1-name jar2-name directory-name/jar3-name}

This header can be used to specify the external JAR files on the same local network and not inside the current JAR.

Package version related headers: When the JAR file is used for package versioning the following headers are used as specified by the Java language specification:

Headers in a manifest
Header                  | Definition
Name                    | The name of the specification.
Specification-Title     | The title of the specification.
Specification-Version   | The version of the specification.
Specification-Vendor    | The vendor of the specification.
Implementation-Title    | The title of the implementation.
Implementation-Version  | The build number of the implementation.
Implementation-Vendor   | The vendor of the implementation.

Package sealing related headers:

We can also specify if any particular packages inside a JAR file should be sealed meaning all the classes defined in that package must be archived in the same JAR file. This can be specified with the help of ‘Sealed’ header,

Name: {package/some-package/} Sealed:true

Here, the package name must end with ‘/’.

Enhancing security with manifest files:

We can use manifest files entries to ensure the security of the web application or applet it packages with the different attributes as ‘Permissions’, ‘Codebae’, ‘Application-Name’, ‘Trusted-Only’ and many more.

META-INF folder:

This folder is where the manifest file resides. Also, it can contain more files containing meta data about the application. For example, in an EJB module JAR file, this folder contains the EJB deployment descriptor for the EJB module along with the manifest file for the JAR. Also, it contains the xml file containing mapping of an abstract EJB references to concrete container resources of the application server on which it will be run.


How can one run multiple versions of PHP 5.x on a development LAMP server?

Having multiple instances of apache + php never really tickled my fancy, but it probably the easiest way to do it. If you don't feel like KISS ... here's an idea.

Get your apache up and running, and try do configure it like debian and ubuntu do it, eg, have directories for loaded modules. Your apache conf can use lines like this:

Include /etc/apache2/mods-enabled/*.load
Include /etc/apache2/mods-enabled/*.conf

Then build your first version of php, and give it a prefix that has the version number explicitly contained, eg, /usr/local/php/5.2.8, /usr/local/php/5.2.6 ...

The conf/load would look something like this:


LoadModule php5_module /usr/local/php/5.2.6/


LoadModule php5_module /usr/local/php/5.2.8/

To switch versions, all you have to do is change the load and conf files from the directory apache does the include on for the ones for another version. You can automate that with a simple bash script (delete the actual file, copy the alternate versions file in place, and restart apache.

One advantage of this setup is the everything is consitent, so long you keep the php.ini's the same in terms of options and modules (which you would have to do with CGI anyway). They're all going through SAPI. Your applications won't need any changes whatsoever, nor need to use relative URLs.

I think this should work, but then again, i haven't tried it, nor am i likely to do so as i don't have the same requirements as you. Do comment if you ever do try though.

plot is not defined

Change that import to

from matplotlib.pyplot import *

Note that this style of imports (from X import *) is generally discouraged. I would recommend using the following instead:

import matplotlib.pyplot as plt

JavaScript URL Decode function

Here is a complete function (taken from PHPJS):

function urldecode(str) {
   return decodeURIComponent((str+'').replace(/\+/g, '%20'));

No 'Access-Control-Allow-Origin' header in Angular 2 app

I have spent lot of time for solution and got it worked finally by making changes in the server side.Check the website

It worked for me when I enabled corse in the server side.We were using Asp.Net core in API and the below code worked

1) Added Addcors in ConfigureServices of Startup.cs

public void ConfigureServices(IServiceCollection services)

2) Added UseCors in Configure method as below:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        app.UseCors(builder =>builder.AllowAnyOrigin());

Get epoch for a specific date using Javascript

Some answers does not explain the side effects of variations in the timezone for JavaScript Date object. So you should consider this answer if this is a concern for you.

Method 1: Machine's timezone dependent

By default, JavaScript returns a Date considering the machine's timezone, so getTime() result varies from computer to computer. You can check this behavior running:

new Date(1970, 0, 1, 0, 0, 0, 0).getTime()
    // Since 1970-01-01 is Epoch, you may expect ZERO
    // but in fact the result varies based on computer's timezone

This is not a problem if you really want the time since Epoch considering your timezone. So if you want to get time since Epoch for the current Date or even a specified Date based on the computer's timezone, you're free to continue using this method.

// Seconds since Epoch (Unix timestamp format)

new Date().getTime() / 1000             // local Date/Time since Epoch in seconds
new Date(2020, 11, 1).getTime() / 1000  // time since Epoch to 2020-12-01 00:00 (local timezone) in seconds

// Milliseconds since Epoch (used by some systems, eg. JavaScript itself)

new Date().getTime()                    // local Date/Time since Epoch in milliseconds
new Date(2020,  0, 2).getTime()         // time since Epoch to 2020-01-02 00:00 (local timezone) in milliseconds

// **Warning**: notice that MONTHS in JavaScript Dates starts in zero (0 = January, 11 = December)

Method 2: Machine's timezone independent

However, if you want to get ride of variations in timezone and get time since Epoch for a specified Date in UTC (that is, timezone independent), you need to use Date.UTC method or shift the date from your timezone to UTC:

Date.UTC(1970,  0, 1)
    // should be ZERO in any computer, since it is ZERO the difference from Epoch

    // Alternatively (if, for some reason, you do not want Date.UTC)
    const timezone_diff = new Date(1970, 0, 1).getTime()  // difference in milliseconds between your timezone and UTC
    (new Date(1970,  0, 1).getTime() - timezone_diff)
    // should be ZERO in any computer, since it is ZERO the difference from Epoch

So, using this method (or, alternatively, subtracting the difference), the result should be:

// Seconds since Epoch (Unix timestamp format)

Date.UTC(2020,  0, 1) / 1000  // time since Epoch to 2020-01-01 00:00 UTC in seconds

    // Alternatively (if, for some reason, you do not want Date.UTC)
    const timezone_diff = new Date(1970, 0, 1).getTime()
    (new Date(2020,  0, 1).getTime() - timezone_diff) / 1000  // time since Epoch to 2020-01-01 00:00 UTC in seconds
    (new Date(2020, 11, 1).getTime() - timezone_diff) / 1000  // time since Epoch to 2020-12-01 00:00 UTC in seconds

// Milliseconds since Epoch (used by some systems, eg. JavaScript itself)

Date.UTC(2020,  0, 2)   // time since Epoch to 2020-01-02 00:00 UTC in milliseconds

    // Alternatively (if, for some reason, you do not want Date.UTC)
    const timezone_diff = new Date(1970, 0, 1).getTime()
    (new Date(2020,  0, 2).getTime() - timezone_diff)         // time since Epoch to 2020-01-02 00:00 UTC in milliseconds

// **Warning**: notice that MONTHS in JavaScript Dates starts in zero (0 = January, 11 = December)

IMO, unless you know what you're doing (see note above), you should prefer Method 2, since it is machine independent.

End note

Although the recomendations in this answer, and since Date.UTC does not work without a specified date/time, you may be inclined in using the alternative approach and doing something like this:

const timezone_diff = new Date(1970, 0, 1).getTime()
(new Date().getTime() - timezone_diff)  // <-- !!! new Date() without arguments
    // means "local Date/Time subtracted by timezone since Epoch" (?)

This does not make any sense and it is probably WRONG (you are modifying the date). Be aware of not doing this. If you want to get time since Epoch from the current date AND TIME, you are most probably OK using Method 1.

What is the fastest way to create a checksum for large files in C#

As Anton Gogolev noted, FileStream reads 4096 bytes at a time by default, But you can specify any other value using the FileStream constructor:

new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 16 * 1024 * 1024)

Note that Brad Abrams from Microsoft wrote in 2004:

there is zero benefit from wrapping a BufferedStream around a FileStream. We copied BufferedStream’s buffering logic into FileStream about 4 years ago to encourage better default performance


Best way to Format a Double value to 2 Decimal places

An alternative is to use String.format:

double[] arr = { 23.59004,

for ( double dub : arr ) {
  System.out.println( String.format( "%.2f", dub ) );



You could also use System.out.format (same method signature), or create a java.util.Formatter which works in the same way.

Connect with SSH through a proxy

In my case since I had a jump host or Bastion host on the way, and because the signatures on these bastion nodes had changed since they were imported into known_hosts file, I just needed to delete those entries/lines from the following file:


From above file, delete those lines referring to the bastion hosts.

lodash: mapping array to object

Yep it is here, using _.reduce

var params = [
    { name: 'foo', input: 'bar' },
    { name: 'baz', input: 'zle' }

_.reduce(params , function(obj,param) {
 obj[] = param.input
 return obj;
}, {});

What does O(log n) mean exactly?

I cannot understand how to identify a function with a log time.

The most common attributes of logarithmic running-time function are that:

  • the choice of the next element on which to perform some action is one of several possibilities, and
  • only one will need to be chosen.


  • the elements on which the action is performed are digits of n

This is why, for example, looking up people in a phone book is O(log n). You don't need to check every person in the phone book to find the right one; instead, you can simply divide-and-conquer by looking based on where their name is alphabetically, and in every section you only need to explore a subset of each section before you eventually find someone's phone number.

Of course, a bigger phone book will still take you a longer time, but it won't grow as quickly as the proportional increase in the additional size.

We can expand the phone book example to compare other kinds of operations and their running time. We will assume our phone book has businesses (the "Yellow Pages") which have unique names and people (the "White Pages") which may not have unique names. A phone number is assigned to at most one person or business. We will also assume that it takes constant time to flip to a specific page.

Here are the running times of some operations we might perform on the phone book, from fastest to slowest:

  • O(1) (in the worst case): Given the page that a business's name is on and the business name, find the phone number.

  • O(1) (in the average case): Given the page that a person's name is on and their name, find the phone number.

  • O(log n): Given a person's name, find the phone number by picking a random point about halfway through the part of the book you haven't searched yet, then checking to see whether the person's name is at that point. Then repeat the process about halfway through the part of the book where the person's name lies. (This is a binary search for a person's name.)

  • O(n): Find all people whose phone numbers contain the digit "5".

  • O(n): Given a phone number, find the person or business with that number.

  • O(n log n): There was a mix-up at the printer's office, and our phone book had all its pages inserted in a random order. Fix the ordering so that it's correct by looking at the first name on each page and then putting that page in the appropriate spot in a new, empty phone book.

For the below examples, we're now at the printer's office. Phone books are waiting to be mailed to each resident or business, and there's a sticker on each phone book identifying where it should be mailed to. Every person or business gets one phone book.

  • O(n log n): We want to personalize the phone book, so we're going to find each person or business's name in their designated copy, then circle their name in the book and write a short thank-you note for their patronage.

  • O(n2): A mistake occurred at the office, and every entry in each of the phone books has an extra "0" at the end of the phone number. Take some white-out and remove each zero.

  • O(n · n!): We're ready to load the phonebooks onto the shipping dock. Unfortunately, the robot that was supposed to load the books has gone haywire: it's putting the books onto the truck in a random order! Even worse, it loads all the books onto the truck, then checks to see if they're in the right order, and if not, it unloads them and starts over. (This is the dreaded bogo sort.)

  • O(nn): You fix the robot so that it's loading things correctly. The next day, one of your co-workers plays a prank on you and wires the loading dock robot to the automated printing systems. Every time the robot goes to load an original book, the factory printer makes a duplicate run of all the phonebooks! Fortunately, the robot's bug-detection systems are sophisticated enough that the robot doesn't try printing even more copies when it encounters a duplicate book for loading, but it still has to load every original and duplicate book that's been printed.

MySQL: ERROR 1227 (42000): Access denied - Cannot CREATE USER

First thing to do is run this:


You will quickly see you were assigned the anonymous user to authenticate into mysql.

Instead of logging into mysql with


login like this:

mysql -uroot

By default, root@localhost has all rights and no password.

If you cannot login as root without a password, do the following:

Step 01) Add the two options in the mysqld section of my.ini:


Step 02) Restart mysql

net stop mysql
<wait 10 seconds>
net start mysql

Step 03) Connect to mysql


Step 04) Create a password from root@localhost

UPDATE mysql.user SET password=password('whateverpasswordyoulike')
WHERE user='root' AND host='localhost';

Step 05) Restart mysql

net stop mysql
<wait 10 seconds>
net start mysql

Step 06) Login as root with password

mysql -u root -p

You should be good from there.

CAVEAT: Please remove anonymous users !!!

Reverse a string without using reversed() or [::-1]?

You can do simply like this

def rev(str):
   rev = ""
   for i in range(0,len(str)):
   rev = rev + str[(len(str)-1)-i]
   return rev

C++ Returning reference to local variable

This code snippet:

int& func1()
    int i;
    i = 1;
    return i;

will not work because you're returning an alias (a reference) to an object with a lifetime limited to the scope of the function call. That means once func1() returns, int i dies, making the reference returned from the function worthless because it now refers to an object that doesn't exist.

int main()
    int& p = func1();
    /* p is garbage */

The second version does work because the variable is allocated on the free store, which is not bound to the lifetime of the function call. However, you are responsible for deleteing the allocated int.

int* func2()
    int* p;
    p = new int;
    *p = 1;
    return p;

int main()
    int* p = func2();
    /* pointee still exists */
    delete p; // get rid of it

Typically you would wrap the pointer in some RAII class and/or a factory function so you don't have to delete it yourself.

In either case, you can just return the value itself (although I realize the example you provided was probably contrived):

int func3()
    return 1;

int main()
    int v = func3();
    // do whatever you want with the returned value

Note that it's perfectly fine to return big objects the same way func3() returns primitive values because just about every compiler nowadays implements some form of return value optimization:

class big_object 
    big_object(/* constructor arguments */);
    big_object(const big_object& rhs);
    big_object& operator=(const big_object& rhs);
    /* public methods */
    /* data members */

big_object func4()
    return big_object(/* constructor arguments */);

int main()
     // no copy is actually made, if your compiler supports RVO
    big_object o = func4();    

Interestingly, binding a temporary to a const reference is perfectly legal C++.

int main()
    // This works! The returned temporary will last as long as the reference exists
    const big_object& o = func4();    
    // This does *not* work! It's not legal C++ because reference is not const.
    // big_object& o = func4();  

php form action php self

How about leaving it empty, what is wrong with that?

<form name="form1" id="mainForm" method="post" enctype="multipart/form-data" action="">


Also, you can omit the action attribute and it will work as expected.

Error: ANDROID_HOME is not set and "android" command not in your PATH. You must fulfill at least one of these conditions.

ANDROID_HOME is deprecated now instead of using ANDROID_HOME use ANDROID_SDK_ROOT

as per Google android documentation -

ANDROID_SDK_ROOT sets the path to the SDK installation directory. Once set, the value does not typically change, and can be shared by multiple users on the same machine. ANDROID_HOME, which also points to the SDK installation directory, is deprecated.

If you continue to use it, the following rules apply:

  • If ANDROID_HOME is defined and contains a valid SDK installation, its value is used instead of the value in ANDROID_SDK_ROOT.
  • If ANDROID_HOME is not defined, the value in ANDROID_SDK_ROOT is used.
  • If ANDROID_HOME is defined but does not exist or does not contain a valid SDK installation, the value in ANDROID_SDK_ROOT is used instead.

For details follow this Android Documentation link

Deleting a pointer in C++

int value, *ptr;

value = 8;
ptr = &value;
// ptr points to value, which lives on a stack frame.
// you are not responsible for managing its lifetime.

ptr = new int;
delete ptr;
// yes this is the normal way to manage the lifetime of
// dynamically allocated memory, you new'ed it, you delete it.

ptr = nullptr;
delete ptr;
// this is illogical, essentially you are saying delete nothing.

JavaScript click event listener on class

Also consider that if you click a button, the target of the event listener is not necessaily the button itself, but whatever content inside the button you clicked on. You can reference the element to which you assigned the listener using the currentTarget property. Here is a pretty solution in modern ES using a single statement:

    document.querySelectorAll(".myClassName").forEach(i => i.addEventListener(
        e => {

VBA to copy a file from one directory to another

One thing that caused me a massive headache when using this code (might affect others and I wish that somebody had left a comment like this one here for me to read):

  • My aim is to create a dynamic access dashboard, which requires that its linked tables be updated.
  • I use the copy methods described above to replace the existing linked CSVs with an updated version of them.
  • Running the above code manually from a module worked fine.
  • Running identical code from a form linked to the CSV data had runtime error 70 (Permission denied), even tho the first step of my code was to close that form (which should have unlocked the CSV file so that it could be overwritten).
  • I now believe that despite the form being closed, it keeps the outdated CSV file locked while it executes VBA associated with that form.

My solution will be to run the code (On timer event) from another hidden form that opens with the database.

What does "opt" mean (as in the "opt" directory)? Is it an abbreviation?

It is an abbreviation for 'optional' , used for optional software in some distros.

Reading Excel files from C#

I want to show a simple method to read xls/xlsx file with .NET. I hope that the following will be helpful for you.

 private DataTable ReadExcelToTable(string path)    

     //Connection String

     string connstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties='Excel 8.0;HDR=NO;IMEX=1';";  
     //the same name 
     //string connstring = Provider=Microsoft.JET.OLEDB.4.0;Data Source=" + path + //";Extended Properties='Excel 8.0;HDR=NO;IMEX=1';"; 

     using(OleDbConnection conn = new OleDbConnection(connstring))
        //Get All Sheets Name
        DataTable sheetsName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,new object[]{null,null,null,"Table"});  

        //Get the First Sheet Name
        string firstSheetName = sheetsName.Rows[0][2].ToString(); 

        //Query String 
        string sql = string.Format("SELECT * FROM [{0}]",firstSheetName); 
        OleDbDataAdapter ada =new OleDbDataAdapter(sql,connstring);
        DataSet set = new DataSet();
        return set.Tables[0];   

Code is from article: You can get more details from it.

Parameter in like clause JPQL

If you do

LIKE :code

and then do

namedQuery.setParameter("code", "%" + this.value + "%");

Then value remains free from the '%' sign. If you need to use it somewhere else in the same query simply use another parameter name other than 'code' .

Is there a command to refresh environment variables from the command prompt in Windows?

You can capture the system environment variables with a vbs script, but you need a bat script to actually change the current environment variables, so this is a combined solution.

Create a file named resetvars.vbs containing this code, and save it on the path:

Set oShell = WScript.CreateObject("WScript.Shell")
filename = oShell.ExpandEnvironmentStrings("%TEMP%\resetvars.bat")
Set objFileSystem = CreateObject("Scripting.fileSystemObject")
Set oFile = objFileSystem.CreateTextFile(filename, TRUE)

set oEnv=oShell.Environment("System")
for each sitem in oEnv 
    oFile.WriteLine("SET " & sitem)
path = oEnv("PATH")

set oEnv=oShell.Environment("User")
for each sitem in oEnv 
    oFile.WriteLine("SET " & sitem)

path = path & ";" & oEnv("PATH")
oFile.WriteLine("SET PATH=" & path)

create another file name resetvars.bat containing this code, same location:

@echo off
call "%TEMP%\resetvars.bat"

When you want to refresh the environment variables, just run resetvars.bat


The two main problems I had coming up with this solution were

a. I couldn't find a straightforward way to export environment variables from a vbs script back to the command prompt, and

b. the PATH environment variable is a concatenation of the user and the system PATH variables.

I'm not sure what the general rule is for conflicting variables between user and system, so I elected to make user override system, except in the PATH variable which is handled specifically.

I use the weird vbs+bat+temporary bat mechanism to work around the problem of exporting variables from vbs.

Note: this script does not delete variables.

This can probably be improved.


If you need to export the environment from one cmd window to another, use this script (let's call it exportvars.vbs):

Set oShell = WScript.CreateObject("WScript.Shell")
filename = oShell.ExpandEnvironmentStrings("%TEMP%\resetvars.bat")
Set objFileSystem = CreateObject("Scripting.fileSystemObject")
Set oFile = objFileSystem.CreateTextFile(filename, TRUE)

set oEnv=oShell.Environment("Process")
for each sitem in oEnv 
    oFile.WriteLine("SET " & sitem)

Run exportvars.vbs in the window you want to export from, then switch to the window you want to export to, and type:


jQuery Validation plugin: disable validation for specified submit buttons

$("form").validate().settings.ignore = "*";


$("form").validate().cancelSubmit = true;

But without success in a custom required validator. For call a submit dynamically, i have created a fake hidden submit button with this code:

var btn = form.children('input.cancel.fakeSubmitFormButton');
if (btn.length === 0) {
    btn = $('<input name="FakeCancelSubmitButton" class="cancel fakeSubmitFormButton hide" type="submit" formnovalidate value="FakeCancelSubmitButton" />');

Now skip the validation correctly :)

What precisely does 'Run as administrator' do?

The Run as *Anything command saves you from logging out and logging in as the user for which you use the runas command for.

The reason programs ask for this elevated privilege started with Black Comb and the Panther folder. There is 0 access to the Kernel in windows unless through the Admin prompt and then it is only a virtual relation with the O/S kernel.


error LNK2001: unresolved external symbol (C++)

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

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

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

R: Select values from data table in range

Lots of options here, but one of the easiest to follow is subset. Consider:

> set.seed(43)
> df <- data.frame(name = sample(letters, 100, TRUE), date = sample(1:500, 100, TRUE))
> subset(df, date > 5 & date < 15)
   name date
11    k   10
67    y   12
86    e    8

You can also insert logic directly into the index for your data.frame. The comma separates the rows from columns. We just have to remember that R indexes rows first, then columns. So here we are saying rows with date > 5 & < 15 and then all columns:

df[df$date > 5 & df$date < 15 ,]

I'd also recommend checking out the help pages for subset, ?subset and the logical operators ?"&"

Angular CLI SASS options

For Angular 9.0 and above, update the "schematics":{} object in angular.json file like this:

"schematics": {
  "@schematics/angular:component": {
    "style": "scss"

In Perl, what is the difference between a .pm (Perl module) and .pl (Perl script) file?

A .pl is a single script.

In .pm (Perl Module) you have functions that you can use from other Perl scripts:

A Perl module is a self-contained piece of Perl code that can be used by a Perl program or by other Perl modules. It is conceptually similar to a C link library, or a C++ class.

Set the maximum character length of a UITextField in Swift

Simply just check with the number of characters in the string

  1. Add a delegate to view controller ans asign delegate
    class YorsClassName : UITextFieldDelegate {

  1. check the number of chars allowed for textfield
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    if textField.text?.count == 1 {
        return false
    return true

Note: Here I checked for only char allowed in textField

Changing CSS Values with Javascript

I don't know why the other solutions go through the whole list of stylesheets for the document. Doing so creates a new entry in each stylesheet, which is inefficient. Instead, we can simply append a new stylesheet and simply add our desired CSS rules there.

function css(selector,property,value)
    try{ stylesheet.insertRule(selector+' {'+property+':'+value+'}',stylesheet.cssRules.length); }

Note that we can override even inline styles set directly on elements by adding " !important" to the value of the property, unless there already exist more specific "!important" style declarations for that property.

How to disable JavaScript in Chrome Developer Tools?

The fast way:

1) just click on CTRL + SHIFT + P

2) fill the field by the 3 letters dis and will appear this box and select the item Disable Javascript

disable javascript .

that's all folks!

Gradle, Android and the ANDROID_HOME SDK location

In my case settings.gradle was missing.

Save the file and put it at the top level folder in your project, even you can copy from another project too.

Screenshot reference:

enter image description here

Hope this would save your time.

What is let-* in Angular 2 templates?

update Angular 5

ngOutletContext was renamed to ngTemplateOutletContext

See also


Templates (<template>, or <ng-template> since 4.x) are added as embedded views and get passed a context.

With let-col the context property $implicit is made available as col within the template for bindings. With let-foo="bar" the context property bar is made available as foo.

For example if you add a template

<ng-template #myTemplate let-col let-foo="bar">

<!-- render above template with a custom context -->
<ng-template [ngTemplateOutlet]="myTemplate"
                                           $implicit: 'some col value',
                                           bar: 'some bar value'

See also this answer and ViewContainerRef#createEmbeddedView.

*ngFor also works this way. The canonical syntax makes this more obvious

<ng-template ngFor let-item [ngForOf]="items" let-i="index" let-odd="odd">

where NgFor adds the template as embedded view to the DOM for each item of items and adds a few values (item, index, odd) to the context.

See also Using $implict to pass multiple parameters

C# Linq Group By on multiple columns

var consolidatedChildren =
    from c in children
    group c by new
    } into gcs
    select new ConsolidatedChild()
        School = gcs.Key.School,
        Friend = gcs.Key.Friend,
        FavoriteColor = gcs.Key.FavoriteColor,
        Children = gcs.ToList(),

var consolidatedChildren =
        .GroupBy(c => new
        .Select(gcs => new ConsolidatedChild()
            School = gcs.Key.School,
            Friend = gcs.Key.Friend,
            FavoriteColor = gcs.Key.FavoriteColor,
            Children = gcs.ToList(),

JavaScript hashmap equivalent

Try my JavaScript hash table implementation:

It looks for a hashCode() method of key objects, or you can supply a hashing function when creating a Hashtable object.

How to draw in JPanel? (Swing/graphics Java)

Variation of the code by Bijaya Bidari that is accepted by Java 8 without warnings in regard with overridable method calls in constructor:

public class Graph extends JFrame {
    JPanel jp;

    public Graph() {
        super("Simple Drawing");
        super.setSize(300, 300);

        jp = new GPanel();

    public static void main(String[] args) {
        Graph g1 = new Graph();

    class GPanel extends JPanel {
        public GPanel() {
            super.setPreferredSize(new Dimension(300, 300));

        public void paintComponent(Graphics g) {
            //rectangle originated at 10,10 and end at 240,240
            g.drawRect(10, 10, 240, 240);
                    //filled Rectangle with rounded corners.    
            g.fillRoundRect(50, 50, 100, 100, 80, 80);

How do I make a C++ macro behave like a function?

I know you said "ignore what the macro does", but people will find this question by searching based on the title, so I think discussion of further techniques to emulate functions with macros are warranted.

Closest I know of is:

#define MACRO(X,Y) \
do { \
    auto MACRO_tmp_1 = (X); \
    auto MACRO_tmp_2 = (Y); \
    using std::cout; \
    using std::endl; \
    cout << "1st arg is:" << (MACRO_tmp_1) << endl;    \
    cout << "2nd arg is:" << (MACRO_tmp_2) << endl;    \
    cout << "Sum is:" << (MACRO_tmp_1 + MACRO_tmp_2) << endl; \
} while(0)

This does the following:

  • Works correctly in each of the stated contexts.
  • Evaluates each of its arguments exactly once, which is a guaranteed feature of a function call (assuming in both cases no exceptions in any of those expressions).
  • Acts on any types, by use of "auto" from C++0x. This is not yet standard C++, but there's no other way to get the tmp variables necessitated by the single-evaluation rule.
  • Doesn't require the caller to have imported names from namespace std, which the original macro does, but a function would not.

However, it still differs from a function in that:

  • In some invalid uses it may give different compiler errors or warnings.
  • It goes wrong if X or Y contain uses of 'MACRO_tmp_1' or 'MACRO_tmp_2' from the surrounding scope.
  • Related to the namespace std thing: a function uses its own lexical context to look up names, whereas a macro uses the context of its call site. There's no way to write a macro that behaves like a function in this respect.
  • It can't be used as the return expression of a void function, which a void expression (such as the comma solution) can. This is even more of an issue when the desired return type is not void, especially when used as an lvalue. But the comma solution can't include using declarations, because they're statements, so pick one or use the ({ ... }) GNU extension.

How can I quantify difference between two images?

A trivial thing to try:

Resample both images to small thumbnails (e.g. 64 x 64) and compare the thumbnails pixel-by-pixel with a certain threshold. If the original images are almost the same, the resampled thumbnails will be very similar or even exactly the same. This method takes care of noise that can occur especially in low-light scenes. It may even be better if you go grayscale.

Determine if 2 lists have the same elements, regardless of order?

Determine if 2 lists have the same elements, regardless of order?

Inferring from your example:

x = ['a', 'b']
y = ['b', 'a']

that the elements of the lists won't be repeated (they are unique) as well as hashable (which strings and other certain immutable python objects are), the most direct and computationally efficient answer uses Python's builtin sets, (which are semantically like mathematical sets you may have learned about in school).

set(x) == set(y) # prefer this if elements are hashable

In the case that the elements are hashable, but non-unique, the collections.Counter also works semantically as a multiset, but it is far slower:

from collections import Counter
Counter(x) == Counter(y)

Prefer to use sorted:

sorted(x) == sorted(y) 

if the elements are orderable. This would account for non-unique or non-hashable circumstances, but this could be much slower than using sets.

Empirical Experiment

An empirical experiment concludes that one should prefer set, then sorted. Only opt for Counter if you need other things like counts or further usage as a multiset.

First setup:

import timeit
import random
from collections import Counter

data = [str(random.randint(0, 100000)) for i in xrange(100)]
data2 = data[:]     # copy the list into a new one

def sets_equal(): 
    return set(data) == set(data2)

def counters_equal(): 
    return Counter(data) == Counter(data2)

def sorted_lists_equal(): 
    return sorted(data) == sorted(data2)

And testing:

>>> min(timeit.repeat(sets_equal))
>>> min(timeit.repeat(counters_equal))
>>> min(timeit.repeat(sorted_lists_equal))

So we see that comparing sets is the fastest solution, and comparing sorted lists is second fastest.

How to study design patterns?

The notion that read design patterns, practice coding them is not really going to help IMO. When you read these books 1. Look for the basic problem that a particular design pattern solves,starting with Creational Patterns is your best bet. 2. I am sure you have written code in past, analyze if you faced the same problems that design patterns aim at providing a solution. 3. Try to redesign/re factor code or perhaps start off fresh.

About resources you can check these

  2. Design Patterns: Elements of Reusable Object-Oriented Software (Addison-Wesley Professional Computing Series) by Erich Gamma, Richard Helm, Ralph Johnson, and John M. Vlissides
  3. Patterns of Enterprise Application Architecture by Martin Fowler

1 is quick start, 2 will be in depth study..3 will explain or should make you think what you learnt in 2 fits in enterprise software.

My 2 cents...

jQuery.animate() with css class only, without explicit styles

Check out James Padolsey's animateToSelector

Intro: This jQuery plugin will allow you to animate any element to styles specified in your stylesheet. All you have to do is pass a selector and the plugin will look for that selector in your StyleSheet and will then apply it as an animation.

ResourceDictionary in a separate assembly

Using XAML:

If you know the other assembly structure and want the resources in c# code, then use below code:

 ResourceDictionary dictionary = new ResourceDictionary();
 dictionary.Source = new Uri("pack://application:,,,/WpfControlLibrary1;Component/RD1.xaml", UriKind.Absolute);
 foreach (var item in dictionary.Values)

Output: If we want to use ResourceDictionary RD1.xaml of Project WpfControlLibrary1 into StackOverflowApp project.

Structure of Projects:

Structure of Projects

Resource Dictionary: Resource Dictionary

Code Output:


PS: All ResourceDictionary Files should have Build Action as 'Resource' or 'Page'.

Using C#:

If anyone wants the solution in purely c# code then see my this solution.

Sniffing/logging your own Android Bluetooth traffic

On Xiaomi Redmi Note 9s This configuration file can also be found /storage/emulated/0/MIUI/debug_log/common named as

With enabled 'Settings->Developer Options, then checking the box next to "Bluetooth HCI Snoop Log." '

I was used Total Commander for taking file from Internal storage

How to return a value from __init__ in Python?

init() return none value solved perfectly

class Solve:
def __init__(self,w,d):
def __str__(self):
    return str("my speed is "+str(self.value)+" "+str(self.unit))
print (ob)

output: my speed is 21 kmh

Use a normal link to submit a form

Two ways. Either create a button and style it so it looks like a link with css, or create a link and use onclick="this.closest('form').submit();return false;".

Circle-Rectangle collision detection (intersection)

Assuming you have the four edges of the rectangle check the distance from the edges to the center of the circle, if its less then the radius, then the shapes are intersecting.

if sqrt((rectangleRight.x - circleCenter.x)^2 +
        (rectangleBottom.y - circleCenter.y)^2) < radius
// then they intersect

if sqrt((rectangleRight.x - circleCenter.x)^2 +
        (rectangleTop.y - circleCenter.y)^2) < radius
// then they intersect

if sqrt((rectangleLeft.x - circleCenter.x)^2 +
        (rectangleTop.y - circleCenter.y)^2) < radius
// then they intersect

if sqrt((rectangleLeft.x - circleCenter.x)^2 +
        (rectangleBottom.y - circleCenter.y)^2) < radius
// then they intersect

Tomcat request timeout

This article talks about setting the timeouts on the server level.

What is causing the application to go into infinite loop? If you are opening connections to other resources, you might want to put timeouts on those connections and sending appropriate response when those time out occurs.

C# get and set properties for a List Collection

It would be inappropriate for it to be part of the setter - it's not like you're really setting the whole list of strings - you're just trying to add one.

There are a few options:

  • Put AddSubheading and AddContent methods in your class, and only expose read-only versions of the lists
  • Expose the mutable lists just with getters, and let callers add to them
  • Give up all hope of encapsulation, and just make them read/write properties

In the second case, your code can be just:

public class Section
    public String Head { get; set; }
    private readonly List<string> _subHead = new List<string>();
    private readonly List<string> _content = new List<string>();

    // Note: fix to case to conform with .NET naming conventions
    public IList<string> SubHead { get { return _subHead; } }
    public IList<string> Content { get { return _content; } }

This is reasonably pragmatic code, although it does mean that callers can mutate your collections any way they want, which might not be ideal. The first approach keeps the most control (only your code ever sees the mutable list) but may not be as convenient for callers.

Making the setter of a collection type actually just add a single element to an existing collection is neither feasible nor would it be pleasant, so I'd advise you to just give up on that idea.

How to remove item from a python list in a loop?

This stems from the fact that on deletion, the iteration skips one element as it semms only to work on the index.

Workaround could be:

x = ["ok", "jj", "uy", "poooo", "fren"]
for item in x[:]: # make a copy of x
    if len(item) != 2:
        print "length of %s is: %s" %(item, len(item))

How can I search for a commit message on GitHub?

Using Advanced Search on Github seemed the easiest with a combination of other answers. It's basically a search string builder.

For example I wanted to find all commits in Autodesk/maya-usd containing "USD" enter image description here

Then in the search results can choose Commits from the list on the left: enter image description here

Extracting Path from OpenFileDialog path/filename

if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
    strfilename = openFileDialog1.InitialDirectory + openFileDialog1.FileName;

"Could not find a valid gem in any repository" (rubygame and others)

I tried to install a gem which is for JRuby only, running into the same error. Using jruby's command worked then:

jruby -S gem install some_jruby_gem

How to access shared folder without giving username and password

I found one way to access the shared folder without giving the username and password.

We need to change the share folder protect settings in the machine where the folder has been shared.

Go to Control Panel > Network and sharing center > Change advanced sharing settings > Enable Turn Off password protect sharing option.

By doing the above settings we can access the shared folder without any username/password.

Sublime Text 2: How to delete blank/empty lines

In my case some empty lines contained the unicode character zero width space (U+200b). To rid empty lines, including the ones with this unicode character:


Non-resolvable parent POM for Could not find artifact and 'parent.relativePath' points at wrong local POM

Make sure you have settings.xml. I had the same problem when I've deleted it by mistake.

Changing image sizes proportionally using CSS?

Put it as a background on your holder e.g.

<div style="background:url(path/to/image/myimage.jpg) center center; width:120px; height:120px;">

This will center your image inside a 120x120 div chopping off any excess of the image

Bootstrap 4: responsive sidebar menu to top navbar

Big screen:

navigation side bar in big screen size

Small screen (Mobile)

sidebar in small mobile size screen

if this is what you wanted this is code


    @import ",400,500,600,700";_x000D_
    body {_x000D_
      font-family: 'Poppins', sans-serif;_x000D_
      background: #fafafa;_x000D_
    p {_x000D_
      font-family: 'Poppins', sans-serif;_x000D_
      font-size: 1.1em;_x000D_
      font-weight: 300;_x000D_
      line-height: 1.7em;_x000D_
      color: #999;_x000D_
    a:focus {_x000D_
      color: inherit;_x000D_
      text-decoration: none;_x000D_
      transition: all 0.3s;_x000D_
    .navbar {_x000D_
      padding: 15px 10px;_x000D_
      background: #fff;_x000D_
      border: none;_x000D_
      border-radius: 0;_x000D_
      margin-bottom: 40px;_x000D_
      box-shadow: 1px 1px 3px rgba(0, 0, 0, 0.1);_x000D_
    .navbar-btn {_x000D_
      box-shadow: none;_x000D_
      outline: none !important;_x000D_
      border: none;_x000D_
    .line {_x000D_
      width: 100%;_x000D_
      height: 1px;_x000D_
      border-bottom: 1px dashed #ddd;_x000D_
      margin: 40px 0;_x000D_
    /* ---------------------------------------------------_x000D_
----------------------------------------------------- */_x000D_
    #sidebar {_x000D_
      width: 250px;_x000D_
      position: fixed;_x000D_
      top: 0;_x000D_
      left: 0;_x000D_
      height: 100vh;_x000D_
      z-index: 999;_x000D_
      background: #7386D5;_x000D_
      color: #fff !important;_x000D_
      transition: all 0.3s;_x000D_
    _x000D_ {_x000D_
      margin-left: -250px;_x000D_
    #sidebar .sidebar-header {_x000D_
      padding: 20px;_x000D_
      background: #6d7fcc;_x000D_
    #sidebar ul.components {_x000D_
      padding: 20px 0;_x000D_
      border-bottom: 1px solid #47748b;_x000D_
    #sidebar ul p {_x000D_
      color: #fff;_x000D_
      padding: 10px;_x000D_
    #sidebar ul li a {_x000D_
      padding: 10px;_x000D_
      font-size: 1.1em;_x000D_
      display: block;_x000D_
    #sidebar ul li a:hover {_x000D_
      color: #7386D5;_x000D_
      background: #fff;_x000D_
    #sidebar ul>a,_x000D_
    a[aria-expanded="true"] {_x000D_
      color: #fff;_x000D_
      background: #6d7fcc;_x000D_
    a[data-toggle="collapse"] {_x000D_
      position: relative;_x000D_
    a[aria-expanded="true"]::before {_x000D_
      content: '\e259';_x000D_
      display: block;_x000D_
      position: absolute;_x000D_
      right: 20px;_x000D_
      font-family: 'Glyphicons Halflings';_x000D_
      font-size: 0.6em;_x000D_
    a[aria-expanded="true"]::before {_x000D_
      content: '\e260';_x000D_
    ul ul a {_x000D_
      font-size: 0.9em !important;_x000D_
      padding-left: 30px !important;_x000D_
      background: #6d7fcc;_x000D_
    ul.CTAs {_x000D_
      padding: 20px;_x000D_
    ul.CTAs a {_x000D_
      text-align: center;_x000D_
      font-size: 0.9em !important;_x000D_
      display: block;_x000D_
      border-radius: 5px;_x000D_
      margin-bottom: 5px;_x000D_
    _x000D_ {_x000D_
      background: #fff;_x000D_
      color: #7386D5;_x000D_
    a.article:hover {_x000D_
      background: #6d7fcc !important;_x000D_
      color: #fff !important;_x000D_
    /* ---------------------------------------------------_x000D_
----------------------------------------------------- */_x000D_
    #content {_x000D_
      width: calc(100% - 250px);_x000D_
      padding: 40px;_x000D_
      min-height: 100vh;_x000D_
      transition: all 0.3s;_x000D_
      position: absolute;_x000D_
      top: 0;_x000D_
      right: 0;_x000D_
    _x000D_ {_x000D_
      width: 100%;_x000D_
    /* ---------------------------------------------------_x000D_
----------------------------------------------------- */_x000D_
    @media (max-width: 768px) {_x000D_
      #sidebar {_x000D_
        margin-left: -250px;_x000D_
      }_x000D_ {_x000D_
        margin-left: 0;_x000D_
      #content {_x000D_
        width: 100%;_x000D_
      }_x000D_ {_x000D_
        width: calc(100% - 250px);_x000D_
      #sidebarCollapse span {_x000D_
        display: none;_x000D_
<!DOCTYPE html>_x000D_
  <meta charset="utf-8">_x000D_
  <meta name="viewport" content="width=device-width, initial-scale=1.0">_x000D_
  <meta http-equiv="X-UA-Compatible" content="IE=edge">_x000D_
  <title>Collapsible sidebar using Bootstrap 3</title>_x000D_
  <!-- Bootstrap CSS CDN -->_x000D_
  <link rel="stylesheet" href="">_x000D_
  <!-- Our Custom CSS -->_x000D_
  <link rel="stylesheet" href="style2.css">_x000D_
  <!-- Scrollbar Custom CSS -->_x000D_
  <link rel="stylesheet" href="">_x000D_
  <div class="wrapper">_x000D_
    <!-- Sidebar Holder -->_x000D_
    <nav id="sidebar">_x000D_
      <div class="sidebar-header">_x000D_
        <h3>Header as you want </h3>_x000D_
      <ul class="list-unstyled components">_x000D_
        <p>Dummy Heading</p>_x000D_
        <li class="active">_x000D_
          <a href="#menu">Animación</a>_x000D_
          <a href="#menu">Ilustración</a>_x000D_
          <a href="#menu">Interacción</a>_x000D_
          <a href="#">Blog</a>_x000D_
          <a href="#">Acerca</a>_x000D_
          <a href="#">contacto</a>_x000D_
    <!-- Page Content Holder -->_x000D_
    <div id="content">_x000D_
      <nav class="navbar navbar-default">_x000D_
        <div class="container-fluid">_x000D_
          <div class="navbar-header">_x000D_
            <button type="button" id="sidebarCollapse" class="btn btn-info navbar-btn">_x000D_
                                <i class="glyphicon glyphicon-align-left"></i>_x000D_
                                <span>Toggle Sidebar</span>_x000D_
          <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">_x000D_
            <ul class="nav navbar-nav navbar-right">_x000D_
              <li><a href="#">Page</a></li>_x000D_
  <!-- jQuery CDN -->_x000D_
  <script src=""></script>_x000D_
  <!-- Bootstrap Js CDN -->_x000D_
  <script src=""></script>_x000D_
  <!-- jQuery Custom Scroller CDN -->_x000D_
  <script src=""></script>_x000D_
  <script type="text/javascript">_x000D_
    $(document).ready(function() {_x000D_
      $('#sidebarCollapse').on('click', function() {_x000D_
        $('#sidebar, #content').toggleClass('active');_x000D_
        $('a[aria-expanded=true]').attr('aria-expanded', 'false');_x000D_

if this is what you want .

How can I make SMTP authenticated in C#

How do you send the message?

The classes in the System.Net.Mail namespace (which is probably what you should use) has full support for authentication, either specified in Web.config, or using the SmtpClient.Credentials property.

How to print in C

try this:

printf("%d", addNumber(a,b))

Here's the documentation for printf.

Swift GET request with parameters

I use:

let dictionary = ["method":"login_user",
                  "password":password.text!] as  Dictionary<String,String>

for (key, value) in dictionary {

request.HTTPBody = data.dataUsingEncoding(NSUTF8StringEncoding);

Global variables in Javascript across multiple files

I think you should be using "local storage" rather than global variables.

If you are concerned that "local storage" may not be supported in very old browsers, consider using an existing plug-in which checks the availability of "local storage" and uses other methods if it isn't available.

I used and I'm happy with it so far.

How to break lines in PowerShell?

Just in case someone else comes across this, to clarify the answer `n is grave accent n, not single tick n

Convert char to int in C and C++

int charToint(char a){
char *p = &a;
int k = atoi(p);
return k;

You can use this atoi method for converting char to int. For more information, you can refer to this ,

Android check internet connection

Check to make sure it is "connected" to a network:

public boolean isNetworkAvailable(Context context) {
    ConnectivityManager connectivityManager = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE));
    return connectivityManager.getActiveNetworkInfo() != null && connectivityManager.getActiveNetworkInfo().isConnected();

Check to make sure it is "connected" to a internet:

public boolean isInternetAvailable() {
    try {
        InetAddress address = InetAddress.getByName("");
        return !address.equals("");
    } catch (UnknownHostException e) {
        // Log error
    return false;

Permission needed:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

How can I hide an HTML table row <tr> so that it takes up no space?

I was having the same issue, I even added style="display: none" to each cell.

In the end I used HTML comments <!-- [HTML] -->

How to test if parameters exist in rails

Here's what I do,

before_action :validate_presence

and then following methods:

    def check_presence
  params[:param1].present? && params[:param2].present?

 def validate_presence
  if !check_presence
    render json:  {
                      error:  {
                                message: "Bad Request, parameters missing.",
                                status: 500

Find the line number where a specific word appears with "grep"

Or You can use

   grep -n . file1 |tail -LineNumberToStartWith|grep regEx

This will take care of numbering the lines in the file

   grep -n . file1 

This will print the last-LineNumberToStartWith

   tail -LineNumberToStartWith

And finally it will grep your desired lines(which will include line number as in orignal file)

grep regEX

Rename Oracle Table or View

In order to rename a table in a different schema, try:

ALTER TABLE owner.mytable RENAME TO othertable;

The rename command (as in "rename mytable to othertable") only supports renaming a table in the same schema.

How to hide navigation bar permanently in android activity?

The other answers mostly use the flags for setSystemUiVisibility() method in View. However, this API is deprecated since Android 11. Check my article about modifying the system UI visibility for more information. The article also explains how to handle the cutouts properly or how to listen to the visibility changes.

Here are code snippets for showing / hiding system bars with the new API as well as the deprecated one for backward compatibility:

 * Hides the system bars and makes the Activity "fullscreen". If this should be the default
 * state it should be called from [Activity.onWindowFocusChanged] if hasFocus is true.
 * It is also recommended to take care of cutout areas. The default behavior is that the app shows
 * in the cutout area in portrait mode if not in fullscreen mode. This can cause "jumping" if the
 * user swipes a system bar to show it. It is recommended to set [WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_NEVER],
 * call [showBelowCutout] from [Activity.onCreate]
 * (see [Android Developers article about cutouts](
 * @see showSystemUI
 * @see addSystemUIVisibilityListener
fun Activity.hideSystemUI() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
        window.insetsController?.let {
            // Default behavior is that if navigation bar is hidden, the system will "steal" touches
            // and show it again upon user's touch. We just want the user to be able to show the
            // navigation bar by swipe, touches are handled by custom code -> change system bar behavior.
            // Alternative to deprecated SYSTEM_UI_FLAG_IMMERSIVE.
            it.systemBarsBehavior = WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
            // make navigation bar translucent (alternative to deprecated
            // WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION)
            // - do this already in hideSystemUI() so that the bar
            // is translucent if user swipes it up
            window.navigationBarColor = getColor(R.color.internal_black_semitransparent_light)
            // Finally, hide the system bars, alternative to View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
            // and SYSTEM_UI_FLAG_FULLSCREEN.
    } else {
        // Enables regular immersive mode.
        // For "lean back" mode, remove SYSTEM_UI_FLAG_IMMERSIVE.
        // Or for "sticky immersive," replace it with SYSTEM_UI_FLAG_IMMERSIVE_STICKY
        window.decorView.systemUiVisibility = (
                // Do not let system steal touches for showing the navigation bar
                        // Hide the nav bar and status bar
                        or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                        or View.SYSTEM_UI_FLAG_FULLSCREEN
                        // Keep the app content behind the bars even if user swipes them up
                        or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN)
        // make navbar translucent - do this already in hideSystemUI() so that the bar
        // is translucent if user swipes it up

 * Shows the system bars and returns back from fullscreen.
 * @see hideSystemUI
 * @see addSystemUIVisibilityListener
fun Activity.showSystemUI() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
        // show app content in fullscreen, i. e. behind the bars when they are shown (alternative to
        // finally, show the system bars
    } else {
        // Shows the system bars by removing all the flags
        // except for the ones that make the content appear under the system bars.
        window.decorView.systemUiVisibility = (
                        or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN)

How to Deserialize XML document

My solution:

  1. Use Edit > Past Special > Paste XML As Classes to get the class in your code
  2. Try something like this: create a list of that class (List<class1>), then use the XmlSerializer to serialize that list to a xml file.
  3. Now you just replace the body of that file with your data and try to deserialize it.


StreamReader sr = new StreamReader(@"C:\Users\duongngh\Desktop\Newfolder\abc.txt");
XmlSerializer xml = new XmlSerializer(typeof(Class1[]));
var a = xml.Deserialize(sr);

NOTE: you must pay attention to the root name, don't change it. Mine is "ArrayOfClass1"

Android Room - simple select query - Cannot access database on the main thread

You can allow database access on the main thread but only for debugging purpose, you shouldn't do this on production.

Here is the reason.

Note: Room doesn't support database access on the main thread unless you've called allowMainThreadQueries() on the builder because it might lock the UI for a long period of time. Asynchronous queries—queries that return instances of LiveData or Flowable—are exempt from this rule because they asynchronously run the query on a background thread when needed.

What are the default access modifiers in C#?

Class is Internal by default.

  • Class members are private by default.

Interface is Internal by default.

  • Interface members are public by default. (Interfaces won't allow us to specify any kind of accessibility to it's members.)

    Note: If you try to specify any access specifier to interface's members then, it shows compile error.

Struct is Internal by default.

  • Struct members are private by default.

How can I replace non-printable Unicode characters in Java?

I propose it remove the non printable characters like below instead of replacing it

private String removeNonBMPCharacters(final String input) {
    StringBuilder strBuilder = new StringBuilder();
    input.codePoints().forEach((i) -> {
        if (Character.isSupplementaryCodePoint(i)) {
        } else {
    return strBuilder.toString();

Printing to the console in Google Apps Script?

Make sure you select the function that needs to be executed. See screenshot:
Apps script logging

How to set the java.library.path from Eclipse

I'm using Mac OS X Yosemite and Netbeans 8.02, I got the same error and the simple solution I have found is like above, this is useful when you need to include native library in the project. So do the next for Netbeans:

1.- Right click on the Project
2.- Properties
3.- Click on RUN
4.- VM Options: java -Djava.library.path="your_path"
5.- for example in my case: java -Djava.library.path=</Users/Lexynux/NetBeansProjects/NAO/libs>
6.- Ok

I hope it could be useful for someone. The link where I found the solution is here: java.library.path – What is it and how to use

Can you change a path without reloading the controller in AngularJS?

Since about version 1.2, you can use $location.replace():


What are the differences between Mustache.js and Handlebars.js?

You've pretty much nailed it, however Mustache templates can also be compiled.

Mustache is missing helpers and the more advanced blocks because it strives to be logicless. Handlebars' custom helpers can be very useful, but often end up introducing logic into your templates.

Mustache has many different compilers (JavaScript, Ruby, Python, C, etc.). Handlebars began in JavaScript, now there are projects like django-handlebars,, handlebars-ruby, lightncandy (PHP), and handlebars-objc.

how to print json data in console.log

I used '%j' option in console.log to print JSON objects

console.log("%j", jsonObj);

How to put text in the upper right, or lower right corner of a "box" using css

Float right the text you want to appear on the right, and in the markup make sure that this text and its surrounding span occurs before the text that should be on the left. If it doesn't occur first, you may have problems with the floated text appearing on a different line.

      <span style="float:right">here</span>Lorem Ipsum etc<br/>
      blah blah<br/>
      <span style="float:right">and here</span>lorem ipsums<br/>

Note that this works for any line, not just the top and bottom corners.

jQuery .css("margin-top", value) not updating in IE 8 (Standards mode)

I'm having a problem with your script in Firefox. When I scroll down, the script continues to add a margin to the page and I never reach the bottom of the page. This occurs because the ActionBox is still part of the page elements. I posted a demo here.

  • One solution would be to add a position: fixed to the CSS definition, but I see this won't work for you
  • Another solution would be to position the ActionBox absolutely (to the document body) and adjust the top.
  • Updated the code to fit with the solution found for others to benefit.



#ActionBox {
 position: relative;
 float: right;


var alert_top = 0;
var alert_margin_top = 0;

$(function() {
  alert_top = $("#ActionBox").offset().top;
  alert_margin_top = parseInt($("#ActionBox").css("margin-top"),10);

  $(window).scroll(function () {
    var scroll_top = $(window).scrollTop();
    if (scroll_top > alert_top) {
      $("#ActionBox").css("margin-top", ((scroll_top-alert_top)+(alert_margin_top*2)) + "px");
      console.log("Setting margin-top to " + $("#ActionBox").css("margin-top"));
    } else {
      $("#ActionBox").css("margin-top", alert_margin_top+"px");

Also it is important to add a base (10 in this case) to your parseInt(), e.g.


Node.JS: Getting error : [nodemon] Internal watch failed: watch ENOSPC

As per discussion over here, ENOSPC means Error No more hard-disk space available. Reason why this much memory required by nodemon or gulp-nodemon (in my case) is that it was watching contents of a folder which it shouldn't. To fix that nodemon has ignore setting that can be used to tell nodemon what not to watch. Have a look at nodemon sample config here.

Is it possible to execute multiple _addItem calls asynchronously using Google Analytics?

From the docs:

_trackTrans() Sends both the transaction and item data to the Google Analytics server. This method should be called after _trackPageview(), and used in conjunction with the _addItem() and addTrans() methods. It should be called after items and transaction elements have been set up.

So, according to the docs, the items get sent when you call trackTrans(). Until you do, you can add items, but the transaction will not be sent.

Edit: Further reading led me here:

Where it clearly says you can start another transaction with an existing ID. When you commit it, the new items you listed will be added to that transaction.

What is the difference between persist() and merge() in JPA and Hibernate?

Persist should be called only on new entities, while merge is meant to reattach detached entities.

If you're using the assigned generator, using merge instead of persist can cause a redundant SQL statement.

Also, calling merge for managed entities is also a mistake since managed entities are automatically managed by Hibernate, and their state is synchronized with the database record by the dirty checking mechanism upon flushing the Persistence Context.

Block Comments in a Shell Script

The following should work for sh,bash, ksh and zsh.

The blocks of code to be commented can be put inside BEGINCOMMENT and ENDCOMMENT:

[ -z $BASH ] || shopt -s expand_aliases
alias BEGINCOMMENT="if [ ]; then"
alias ENDCOMMENT="fi"

  echo "This line appears in a commented block"
  echo "And this one too!"

echo "This is outside the commented block"

Executing the above code would result in:

This is outside the commented block

In order to uncomment the code blocks thus commented, say

alias BEGINCOMMENT="if : ; then"

instead of

alias BEGINCOMMENT="if [ ]; then"

in the example above.

jQuery: Load Modal Dialog Contents via Ajax

may be this code may give you some idea.

$(document).ready(function() {
    $('#page-help').each(function() {
        var $link = $(this);
        var $dialog = $('<div></div>')
                autoOpen: false,
                title: $link.attr('title'),
                width: 500,
                height: 300

        $ {

            return false;

Create Pandas DataFrame from a string

In one line, but first import IO

import pandas as pd
import io   


df = pd.read_csv(  io.StringIO(TESTDATA)  , sep=";")
print ( df )

JSLint says "missing radix parameter"

I'm not properly answering the question but, I think it makes sense to clear why we should specify the radix.

On MDN documentation we can read that:

If radix is undefined or 0 (or absent), JavaScript assumes the following:

  • [...]
  • If the input string begins with "0", radix is eight (octal) or 10 (decimal). Exactly which radix is chosen is implementation-dependent. ECMAScript 5 specifies that 10 (decimal) is used, but not all browsers support this yet. For this reason always specify a radix when using parseInt.
  • [...]

Source: MDN parseInt()

Getting absolute URLs using ASP.NET Core

In a new ASP.Net 5 MVC project in a controller action you can still do this.Context and this.Context.Request It looks like on the Request there is no longer a Url property but the child properties (schema, host, etc) are all on the request object directly.

 public IActionResult About()
        ViewBag.Message = "Your application description page.";
        var schema = this.Context.Request.Scheme;

        return View();

Rather or not you want to use this.Context or inject the property is another conversation. Dependency Injection in ASP.NET vNext

how to show calendar on text box click in html

Starting with HTML5, <input type="date" /> will do just fine.


HTML5 Audio Looping

This works and it is a lot easier to toggle that the methods above:

use inline: onended="if($(this).attr('data-loop')){ this.currentTime = 0;; }"

Turn the looping on by $(audio_element).attr('data-loop','1'); Turn the looping off by $(audio_element).removeAttr('data-loop');

What are my options for storing data when using React Native? (iOS and Android)

Quick and dirty: just use Redux + react-redux + redux-persist + AsyncStorage for react-native.

It fits almost perfectly the react native world and works like a charm for both android and ios. Also, there is a solid community around it, and plenty of information.

For a working example, see the F8App from Facebook.

What are the different options for data persistence?

With react native, you probably want to use redux and redux-persist. It can use multiple storage engines. AsyncStorage and redux-persist-filesystem-storage are the options for RN.

There are other options like Firebase or Realm, but I never used those on a RN project.

For each, what are the limits of that persistence (i.e., when is the data no longer available)? For example: when closing the application, restarting the phone, etc.

Using redux + redux-persist you can define what is persisted and what is not. When not persisted, data exists while the app is running. When persisted, the data persists between app executions (close, open, restart phone, etc).

AsyncStorage has a default limit of 6MB on Android. It is possible to configure a larger limit (on Java code) or use redux-persist-filesystem-storage as storage engine for Android.

For each, are there differences (other than general setup) between implementing in iOS vs Android?

Using redux + redux-persist + AsyncStorage the setup is exactly the same on android and iOS.

How do the options compare for accessing data offline? (or how is offline access typically handled?)

Using redux, offiline access is almost automatic thanks to its design parts (action creators and reducers).

All data you fetched and stored are available, you can easily store extra data to indicate the state (fetching, success, error) and the time it was fetched. Normally, requesting a fetch does not invalidate older data and your components just update when new data is received.

The same apply in the other direction. You can store data you are sending to server and that are still pending and handle it accordingly.

Are there any other considerations I should keep in mind?

React promotes a reactive way of creating apps and Redux fits very well on it. You should try it before just using an option you would use in your regular Android or iOS app. Also, you will find much more docs and help for those.

How do I apply a CSS class to Html.ActionLink in ASP.NET MVC?

It is:

<%=Html.ActionLink("Home", "Index", MyRouteValObj, new with {.class = "tab" })%>

In you set an anonymous type using

new with {.class = "tab" }

and, as other point out, your third parameter should be an object (could be an anonymous type, also).

How do I convert struct System.Byte byte[] to a System.IO.Stream object in C#?

The easiest way to convert a byte array to a stream is using the MemoryStream class:

Stream stream = new MemoryStream(byteArray);

How to measure elapsed time

There are many ways to achieve this, but the most important consideration to measure elapsed time is to use System.nanoTime() and TimeUnit.NANOSECONDS as the time unit. Why should I do this? Well, it is because System.nanoTime() method returns a high-resolution time source, in nanoseconds since some reference point (i.e. Java Virtual Machine's start up).

This method can only be used to measure elapsed time and is not related to any other notion of system or wall-clock time.

For the same reason, it is recommended to avoid the use of the System.currentTimeMillis() method for measuring elapsed time. This method returns the wall-clock time, which may change based on many factors. This will be negative for your measurements.

Note that while the unit of time of the return value is a millisecond, the granularity of the value depends on the underlying operating system and may be larger. For example, many operating systems measure time in units of tens of milliseconds.

So here you have one solution based on the System.nanoTime() method, another one using Guava, and the final one Apache Commons Lang

public class TimeBenchUtil
    public static void main(String[] args) throws InterruptedException

    public static void stopWatch() throws InterruptedException
        long endTime, timeElapsed, startTime = System.nanoTime();

        /* ... the code being measured starts ... */

        // sleep for 5 seconds

        /* ... the code being measured ends ... */

        endTime = System.nanoTime();

        // get difference of two nanoTime values
        timeElapsed = endTime - startTime;

        System.out.println("Execution time in nanoseconds   : " + timeElapsed);

    public static void stopWatchGuava() throws InterruptedException
        // Creates and starts a new stopwatch
        Stopwatch stopwatch = Stopwatch.createStarted();

        /* ... the code being measured starts ... */

        // sleep for 5 seconds
        /* ... the code being measured ends ... */

        stopwatch.stop(); // optional

        // get elapsed time, expressed in milliseconds
        long timeElapsed = stopwatch.elapsed(TimeUnit.NANOSECONDS);

        System.out.println("Execution time in nanoseconds   : " + timeElapsed);

    public static void stopWatchApacheCommons() throws InterruptedException
        StopWatch stopwatch = new StopWatch();

        /* ... the code being measured starts ... */

        // sleep for 5 seconds

        /* ... the code being measured ends ... */

        stopwatch.stop();    // Optional

        long timeElapsed = stopwatch.getNanoTime();

        System.out.println("Execution time in nanoseconds   : " + timeElapsed);

How to position absolute inside a div?

The problem is described (among other) in this article.

#box is relatively positioned, which makes it part of the "flow" of the page. Your other divs are absolutely positioned, so they are removed from the page's "flow".

Page flow means that the positioning of an element effects other elements in the flow.

In other words, as #box now sees the dom, .a and .b are no longer "inside" #box.

To fix this, you would want to make everything relative, or everything absolute.

One way would be:

.a {
   padding: 5px;

How to restore the permissions of files and directories within git if they have been modified?

Git doesn't store file permissions other than executable scripts. Consider using something like git-cache-meta to save file ownership and permissions.

Git can only store two types of modes: 755 (executable) and 644 (not executable). If your file was 444 git would store it has 644.

Git: Installing Git in PATH with GitHub client for Windows

Having searched around several posts. On Windows 10 having downloaded and installed Github for Windows 2.10.2 I found the git.exe in


and the git-cmd.exe in


Please note the change to Programs folder within Local from the above posts.

How to extract the hostname portion of a URL in JavaScript

I know this is a bit late, but I made a clean little function with a little ES6 syntax

function getHost(href){
  return Object.assign(document.createElement('a'), { href }).host;

It could also be writen in ES5 like

function getHost(href){
  return Object.assign(document.createElement('a'), { href: href }).host;

Of course IE doesn't support Object.assign, but in my line of work, that doesn't matter.

Download pdf file using jquery ajax

jQuery has some issues loading binary data using AJAX requests, as it does not yet implement some HTML5 XHR v2 capabilities, see this enhancement request and this discussion

Given that, you have one of two solutions:

First solution, abandon JQuery and use XMLHTTPRequest

Go with the native HTMLHTTPRequest, here is the code to do what you need

  var req = new XMLHttpRequest();"GET", "/file.pdf", true);
  req.responseType = "blob";

  req.onload = function (event) {
    var blob = req.response;
    var link=document.createElement('a');
    link.href=window.URL.createObjectURL(blob);"Dossier_" + new Date() + ".pdf";;


Second solution, use the jquery-ajax-native plugin

The plugin can be found here and can be used to the XHR V2 capabilities missing in JQuery, here is a sample code how to use it

  dataType: 'native',
  url: "/file.pdf",
  xhrFields: {
    responseType: 'blob'
  success: function(blob){
      var link=document.createElement('a');
      link.href=window.URL.createObjectURL(blob);"Dossier_" + new Date() + ".pdf";;

String.Format alternative in C++

In addition to options suggested by others I can recommend the fmt library which implements string formatting similar to str.format in Python and String.Format in C#. Here's an example:

std::string a = "test";
std::string b = "text.txt";
std::string c = "text1.txt";
std::string result = fmt::format("{0} {1} > {2}", a, b, c);

Disclaimer: I'm the author of this library.

Properties private set;

This is one possible solution although not very clean:

  1. Make the property you need to expose to BAL & DAL internal
  2. Mark BAL.dll & DAL.dll Internal Visible in assemblyinfo.cs

public class Person
    public Person(int id)

    public string Name { get;  set; }
    public int Id { get; internal set; }
    public int Age { get; set; }

AssemblyInfo.cs for Entities.dll

[assembly: InternalsVisibleTo("DAL"), InternalsVisibleTo("BAL")]

That way all your internals will be visible to DAL & BAL. This may not be desirable but I'm just suggesting one possible solution.

How do I get the current time zone of MySQL?

It may be

select timediff(current_time(),utc_time())

You won't get the timezone value directly this way.

@@global.time_zone cannot be used as it is a variable, and it returns the value 'SYSTEM'.

If you need to use your query in a session with a changed timezone by using session SET TIME_ZONE =, then you will get that with @@session.time_zone. If you query @@global.time_zone, then you get 'SYSTEM'.

If you try datediff, date_sub, or timediff with now() and utc_time(), then you'll probably run into conversion issues.

But the things suggested above will probably work at least with some server versions. My version is 5.5.43-37 and is a hosted solution.

C# Interfaces. Implicit implementation versus Explicit implementation

Reason #1

I tend to use explicit interface implementation when I want to discourage "programming to an implementation" (Design Principles from Design Patterns).

For example, in an MVP-based web application:

public interface INavigator {
    void Redirect(string url);

public sealed class StandardNavigator : INavigator {
    void INavigator.Redirect(string url) {

Now another class (such as a presenter) is less likely to depend on the StandardNavigator implementation and more likely to depend on the INavigator interface (since the implementation would need to be cast to an interface to make use of the Redirect method).

Reason #2

Another reason I might go with an explicit interface implementation would be to keep a class's "default" interface cleaner. For example, if I were developing an ASP.NET server control, I might want two interfaces:

  1. The class's primary interface, which is used by web page developers; and
  2. A "hidden" interface used by the presenter that I develop to handle the control's logic

A simple example follows. It's a combo box control that lists customers. In this example, the web page developer isn't interested in populating the list; instead, they just want to be able to select a customer by GUID or to obtain the selected customer's GUID. A presenter would populate the box on the first page load, and this presenter is encapsulated by the control.

public sealed class CustomerComboBox : ComboBox, ICustomerComboBox {
    private readonly CustomerComboBoxPresenter presenter;

    public CustomerComboBox() {
        presenter = new CustomerComboBoxPresenter(this);

    protected override void OnLoad() {
        if (!Page.IsPostBack) presenter.HandleFirstLoad();

    // Primary interface used by web page developers
    public Guid ClientId {
        get { return new Guid(SelectedItem.Value); }
        set { SelectedItem.Value = value.ToString(); }

    // "Hidden" interface used by presenter
    IEnumerable<CustomerDto> ICustomerComboBox.DataSource { set; }

The presenter populates the data source, and the web page developer never needs to be aware of its existence.

But's It's Not a Silver Cannonball

I wouldn't recommend always employing explicit interface implementations. Those are just two examples where they might be helpful.

How do I find the date a video (.AVI .MP4) was actually recorded?

Actually you can find very easy the day a video was created, right-click, property but remember it will only give the details of any copy date of the video but if you do click where it says DETAILS JUST there is the information you need, the original date that the archive was created on. Note that most modern devices will produce this information when you take pictures and videos but others will not.

Get the value of input text when enter key pressed

Something like this (not tested, but should work)

Pass this as parameter in Html:

<input type="text" placeholder="some text" class="search" onkeydown="search(this)"/>

And alert the value of the parameter passed into the search function:

function search(e){

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

The typical way to check for existence in many STL containers such as std::map, std::set, ... is:

const bool is_in = container.find(element) != container.end();

How to extract custom header value in Web API message handler?

To further expand on @neontapir's solution, here's a more generic solution that can apply to HttpRequestMessage or HttpResponseMessage equally and doesn't require hand coded expressions or functions.

using System.Net.Http;
using System.Collections.Generic;
using System.Linq;

public static class HttpResponseMessageExtensions
    public static T GetFirstHeaderValueOrDefault<T>(
        this HttpResponseMessage response,
        string headerKey)
        var toReturn = default(T);

        IEnumerable<string> headerValues;

        if (response.Content.Headers.TryGetValues(headerKey, out headerValues))
            var valueString = headerValues.FirstOrDefault();
            if (valueString != null)
                return (T)Convert.ChangeType(valueString, typeof(T));

        return toReturn;

Sample usage:

var myValue = response.GetFirstHeaderValueOrDefault<int>("MyValue");

The type or namespace name 'Entity' does not exist in the namespace 'System.Data'

I noticed that in the csproj the framework entity had hintpath like


I had this in the nuget.config file:

 <add key="repositoryPath" value="../lib" />

a) I removed the above lines, b) uninstalled the framework entity package, c) THEN CLOSED THE solution and reopened it, d) reinstalled the framework.

It fixed my issue.

MVC4 Passing model from view to controller

I hope this complete example will help you.

This is the TaxiInfo class which holds information about a taxi ride:

namespace Taxi.Models
    public class TaxiInfo
        public String Driver { get; set; }
        public Double Fare { get; set; }
        public Double Distance { get; set; }
        public String StartLocation { get; set; }
        public String EndLocation { get; set; }

We also have a convenience model which holds a List of TaxiInfo(s):

namespace Taxi.Models
    public class TaxiInfoSet
        public List<TaxiInfo> TaxiInfoList { get; set; }

        public TaxiInfoSet(params TaxiInfo[] TaxiInfos)
            TaxiInfoList = new List<TaxiInfo>();

            foreach(var TaxiInfo in TaxiInfos)

Now in the home controller we have the default Index action which for this example makes two taxi drivers and adds them to the list contained in a TaxiInfo:

public ActionResult Index()
    var taxi1 = new TaxiInfo() { Fare = 20.2, Distance = 15, Driver = "Billy", StartLocation = "Perth", EndLocation = "Brisbane" };
    var taxi2 = new TaxiInfo() { Fare = 2339.2, Distance = 1500, Driver = "Smith", StartLocation = "Perth", EndLocation = "America" };

    return View(new TaxiInfoSet(taxi1,taxi2));

The code for the view is as follows:

@model Taxi.Models.TaxiInfoSet
    ViewBag.Title = "Index";


@foreach(var TaxiInfo in Model.TaxiInfoList){
        <h1>Cost: [email protected]</h1>
        <h2>Distance: @(TaxiInfo.Distance) km</h2>
            Our diver, @TaxiInfo.Driver will take you from @TaxiInfo.StartLocation to @TaxiInfo.EndLocation

The ActionLink is responsible for the re-directing to the booking action of the Home controller (and passing in the appropriate TaxiInfo object) which is defiend as follows:

    public ActionResult Booking(TaxiInfo Taxi)
        return View(Taxi);

This returns a the following view:

@model Taxi.Models.TaxiInfo

    ViewBag.Title = "Booking";

<h2>Booking For</h2>
<h1>@Model.Driver, going from @Model.StartLocation to @Model.EndLocation (a total of @Model.Distance km) for [email protected]</h1>

A visual tour:

The Index view

The Booking view

How to get a substring of text?

If you have your text in your_text variable, you can use:


Hibernate Criteria Restrictions AND / OR combination

For the new Criteria since version Hibernate 5.2:

CriteriaBuilder criteriaBuilder = getSession().getCriteriaBuilder();
CriteriaQuery<SomeClass> criteriaQuery = criteriaBuilder.createQuery(SomeClass.class);

Root<SomeClass> root = criteriaQuery.from(SomeClass.class);

Path<Object> expressionA = root.get("A");
Path<Object> expressionB = root.get("B");

Predicate predicateAEqualX = criteriaBuilder.equal(expressionA, "X");
Predicate predicateBInXY ="X",Y);
Predicate predicateLeft = criteriaBuilder.and(predicateAEqualX, predicateBInXY);

Predicate predicateAEqualY = criteriaBuilder.equal(expressionA, Y);
Predicate predicateBEqualZ = criteriaBuilder.equal(expressionB, "Z");
Predicate predicateRight = criteriaBuilder.and(predicateAEqualY, predicateBEqualZ);

Predicate predicateResult = criteriaBuilder.or(predicateLeft, predicateRight);


List<SomeClass> list = getSession()

Easiest way to open a download window without navigating away from the page

After hours of trying, the function is born :) I had a scenario where I had to display loader in time while the file is preparing for download:

Working in Chrome, Safari and Firefox

function ajaxDownload(url, filename = 'file', method = 'get', data = {}, callbackSuccess = () => {}, callbackFail = () => {}) {
        url: url,
        method: 'GET',
        xhrFields: {
            responseType: 'blob'
        success: function (data) {
            // create link element
            let a = document.createElement('a'), 
                url = window.URL.createObjectURL(data);

            // initialize 
            a.href = url;
   = filename;

            // append element to the body, 
            // a must, due to Firefox

            // trigger download

            // delay a bit deletion of the element
            }, 100);

            // invoke callback if any 
        error: function (err) {
            // invoke fail callback if any

Unzip files (7-zip) via cmd command

make sure that your path is pointing to .exe file in C:\Program Files\7-Zip (may in bin directory)

Data access object (DAO) in Java

Don't get confused with too many explanations. DAO: From the name itself it means Accessing Data using Object. DAO is separated from other Business Logic.

How can I avoid getting this MySQL error Incorrect column specifier for column COLUMN NAME?

Quoting the doc:

Some attributes do not apply to all data types. AUTO_INCREMENT applies only to integer and floating-point types. DEFAULT does not apply to the BLOB or TEXT types.

In your case, you're trying to apply AUTO_INCREMENT modifier to char column. To solve this, either drop AUTO_INCREMENT altogether (that means you'll have to generate a unique id on the application level) or just change topic_id type to the relevant integer one.

As a sidenote, it makes little sense using char(36) to store the posts count, so that column's type probably has to be changed as well. It looks like you're going this way to prevent integer overflow - but if you're dealing with more than 18446744073709551615 posts (the biggest number that can be stored in BIGINT UNSIGNED column) in a single topic, you have far bigger problem on your side probably. )

isolating a sub-string in a string before a symbol in SQL Server 2008

DECLARE @test nvarchar(100)

SET @test = 'Foreign Tax Credit - 1997'

SELECT @test, left(@test, charindex('-', @test) - 2) AS LeftString,
    right(@test, len(@test) - charindex('-', @test) - 1)  AS RightString

How do I apply a perspective transform to a UIView?

You can only use Core Graphics (Quartz, 2D only) transforms directly applied to a UIView's transform property. To get the effects in coverflow, you'll have to use CATransform3D, which are applied in 3-D space, and so can give you the perspective view you want. You can only apply CATransform3Ds to layers, not views, so you're going to have to switch to layers for this.

Check out the "CovertFlow" sample that comes with Xcode. It's mac-only (ie not for iPhone), but a lot of the concepts transfer well.

Creating a search form in PHP to search a database?

You're getting errors 'table liam does not exist' because the table's name is Liam which is not the same as liam. MySQL table names are case sensitive.

How can I extract audio from video with ffmpeg?

Extract all audio tracks / streams

This puts all audio into one file:

ffmpeg -i -map 0:a -c copy
  • -map 0:a selects all audio streams only. Video and subtitles will be excluded.
  • -c copy enables stream copy mode. This copies the audio and does not re-encode it. Remove -c copy if you want the audio to be re-encoded.
  • Choose an output format that supports your audio format. See comparison of container formats.

Extract a specific audio track / stream

Example to extract audio stream #4:

ffmpeg -i input.mkv -map 0:a:3 -c copy output.m4a
  • -map 0:a:3 selects audio stream #4 only (ffmpeg starts counting from 0).
  • -c copy enables stream copy mode. This copies the audio and does not re-encode it. Remove -c copy if you want the audio to be re-encoded.
  • Choose an output format that supports your audio format. See comparison of container formats.

Extract and re-encode audio / change format

Similar to the examples above, but without -c copy. Various examples:

ffmpeg -i input.mp4 -map 0:a output.mp3
ffmpeg -i input.mkv -map 0:a output.m4a
ffmpeg -i input.avi -map 0:a -c:a aac output.mka
ffmpeg -i input.mp4 output.wav

Extract all audio streams individually

This input in this example has 4 audio streams. Each audio stream will be output as single, individual files.

ffmpeg -i -map 0:a:0 output0.wav -map 0:a:1 output1.wav -map 0:a:2 output2.wav -map 0:a:3 output3.wav

Optionally add -c copy before each output file name to enable stream copy mode.

Extract a certain channel

Use the channelsplit filter. Example to get the Front Right (FR) channel from a stereo input:

ffmpeg -i stereo.wav -filter_complex "[0:a]channelsplit=channel_layout=stereo:channels=FR[right]" -map "[right]" front_right.wav
  • channel_layout is the channel layout of the input. It is not automatically detected so you must provide the layout name.
  • channels lists the channel(s) you want to extract.
  • See ffmpeg -layouts for audio channel layout names (for channel_layout) and channel names (for channels).
  • Using stream copy mode (-c copy) is not possible to use when filtering, so the audio must be re-encoded.
  • See FFmpeg Wiki: Audio Channels for more examples.

What's the difference between -map and -vn?

ffmpeg has a default stream selection behavior that will select 1 stream per stream type (1 video, 1 audio, 1 subtitle, 1 data).

-vn is an old, legacy option. It excludes video from the default stream selection behavior. So audio, subtitles, and data are still automatically selected unless told not to with -an, -sn, or -dn.

-map is more complicated but more flexible and useful. -map disables the default stream selection behavior and ffmpeg will only include what you tell it to with -map option(s). -map can also be used to exclude certain streams or stream types. For example, -map 0 -map -0:v would include all streams except all video.

See FFmpeg Wiki: Map for more examples.


Invalid audio stream. Exactly one MP3 audio stream is required.

MP3 only supports 1 audio stream. The error means you are trying to put more than 1 audio stream into MP3. It can also mean you are trying to put non-MP3 audio into MP3.

WAVE files have exactly one stream

Similar to above.

Could not find tag for codec in stream #0, codec not currently supported in container

You are trying to put an audio format into an output that does not support it, such as PCM (WAV) into MP4.

Remove -c copy, choose a different output format (change the file name extension), or manually choose the encoder (such as -c:a aac).

See comparison of container formats.

Could not write header for output file #0 (incorrect codec parameters ?): Invalid argument

This is a useless, generic error. The actual, informative error should immediately precede this generic error message.

Facebook Javascript SDK Problem: "FB is not defined"

Try Asynchronous Loading:

<div id="fb-root"></div>
  window.fbAsyncInit = function() {
      appId  : 'YOUR APP ID',
      status : true, // check login status
      cookie : true, // enable cookies to allow the server to access the session
      xfbml  : true  // parse XFBML

  (function() {
    var e = document.createElement('script');
    e.src = document.location.protocol + '//';
    e.async = true;

Drop Down Menu/Text Field in one

You can use the <datalist> tag instead of the <select> tag.

<input list="browsers" name="browser" id="browser">
<datalist id="browsers">
  <option value="Edge">
  <option value="Firefox">
  <option value="Chrome">
  <option value="Opera">
  <option value="Safari">

Center Align on a Absolutely Positioned Div

    position: absolute;
    right: 0;
    left: 0;
    margin: auto;

Iterating over all the keys of a map

A Type agnostic solution:

for _, key := range reflect.ValueOf(yourMap).MapKeys() {
    value := s.MapIndex(key).Interface()
    fmt.Println("Key:", key, "Value:", value)

Remove commas from the string using JavaScript

This is the simplest way to do it.

let total = parseInt(('100,000.00'.replace(',',''))) + parseInt(('500,000.00'.replace(',','')))

How can I compare time in SQL Server?


Separate the time value from the date value if you want to use indexes in your search (you probably should, for performance). You can: (1) use function-based indexes or (2) create a new column for time only, index this column and use it in you SELECT clause.

Keep in mind you will lose any index performance boost if you use functions in a SQL's WHERE clause, the engine has to do a scan search. Just run your query with EXPLAIN SELECT... to confirm this. This happens because the engine has to process EVERY value in the field for EACH comparison, and the converted value is not indexed.

Most answers say to use float(), convert(), cast(), addtime(), etc.. Again, your database won't use indexes if you do this. For small tables that may be OK.

It is OK to use functions in WHERE params though (where field = func(value)), because you won't be changing EACH field's value in the table.

In case you want to keep use of indexes, you can create a function-based index for the time value. The proper way to do this (and support for it) may depend on your database engine. Another option is adding a column to store only the time value and index this column, but try the former approach first.

Edit 06-02

Do some performance tests before updating your database to have a new time column or whatever to make use of indexes. In my tests, I found out the performance boost was minimal (when I could see some improvement) and wouldn't be worth the trouble and overhead of adding a new index.

How can I convert JSON to a HashMap using Gson?

JSONObject typically uses HashMap internally to store the data. So, you can use it as Map in your code.


JSONObject obj = JSONObject.fromObject(strRepresentation);
Iterator i = obj.entrySet().iterator();
while (i.hasNext()) {
   Map.Entry e = (Map.Entry);
   System.out.println("Key: " + e.getKey());
   System.out.println("Value: " + e.getValue());

How to use multiple conditions (With AND) in IIF expressions in ssrs

Could you try this out?

=IIF((Fields!OpeningStock.Value=0) AND (Fields!GrossDispatched.Value=0) AND 
(Fields!TransferOutToMW.Value=0) AND (Fields!TransferOutToDW.Value=0) AND 
(Fields!TransferOutToOW.Value=0) AND (Fields!NetDispatched.Value=0) AND (Fields!QtySold.Value=0) 
AND (Fields!StockAdjustment.Value=0) AND (Fields!ClosingStock.Value=0),True,False)

Note: Setting Hidden to False will make the row visible

How to make a JFrame Modal in Swing java

There's a bit of code that might help:

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;

public class ModalJFrame extends JFrame {

    Object currentWindow = this;

    public ModalJFrame() 
        super.setTitle("Main JFrame");
        super.setSize(500, 500);

        JMenuBar menuBar = new JMenuBar();

        JMenu fileMenu = new JMenu("File");
        JMenu editMenu = new JMenu("Edit");


        JMenuItem newAction = new JMenuItem("New");
        JMenuItem openAction = new JMenuItem("Open");
        JMenuItem exitAction = new JMenuItem("Exit");
        JMenuItem cutAction = new JMenuItem("Cut");
        JMenuItem copyAction = new JMenuItem("Copy");
        JMenuItem pasteAction= new JMenuItem("Paste");



        newAction.addActionListener(new ActionListener()
            public void actionPerformed(ActionEvent arg0)

                JFrame popupJFrame = new JFrame();

                popupJFrame.addWindowListener(new WindowAdapter()
                      public void windowClosing(WindowEvent e) 
                          ((Component) currentWindow).setEnabled(true);                     }

                ((Component) currentWindow).setEnabled(false);
                popupJFrame.setTitle("Pop up JFrame");
                popupJFrame.setSize(400, 500);

        exitAction.addActionListener(new ActionListener()
            public void actionPerformed(ActionEvent arg0)
    public static void main(String[] args) {

        ModalJFrame myWindow = new ModalJFrame();

Relative paths based on file location instead of current working directory

Just one line will be OK.

cat "`dirname $0`"/../some.txt

Difference between subprocess.Popen and os.system

os.system is equivalent to Unix system command, while subprocess was a helper module created to provide many of the facilities provided by the Popen commands with an easier and controllable interface. Those were designed similar to the Unix Popen command.

system() executes a command specified in command by calling /bin/sh -c command, and returns after the command has been completed


The popen() function opens a process by creating a pipe, forking, and invoking the shell.

If you are thinking which one to use, then use subprocess definitely because you have all the facilities for execution, plus additional control over the process.

Is a view faster than a simple query?

There is no practical different and if you read BOL you will find that ever your plain old SQL SELECT * FROM X does take advantage of plan caching etc.

Sharing url link does not show thumbnail image on facebook

I ran into this and while I had the og:image (and others), I was missing og:url and og:type, so I added those and then it worked.

<meta property="og:url" content="<? 
 $url = 'https://' . $_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']."?".$_SERVER['QUERY_STRING'];; 
echo htmlentities($url,ENT_QUOTES); ?>"/> 

Putting HTML inside Html.ActionLink(), plus No Link Text?

This has always worked well for me. It's not messy and very clean.

<a href="@Url.Action("Index", "Home")"><span>Text</span></a>

Using C++ base class constructors?

Yes, Since C++11:

struct B2 {
    B2(int = 13, int = 42);
struct D2 : B2 {
    using B2::B2;
// The set of inherited constructors is
// 1. B2(const B2&)
// 2. B2(B2&&)
// 3. B2(int = 13, int = 42)
// 4. B2(int = 13)
// 5. B2()

// D2 has the following constructors:
// 1. D2()
// 2. D2(const D2&)
// 3. D2(D2&&)
// 4. D2(int, int) <- inherited
// 5. D2(int) <- inherited

For additional information see

Action Bar's onClick listener for the Home button

answers in half part of what is happening. if onOptionsItemSelected not control homeAsUp button when parent activity sets in manifest.xml system goes to parent activity. use like this in activity tag:

<activity ... >
android:value="com.activities.MainActivity" /> 

How to remove and clear all localStorage data


should work.

Parsing JSON using

(This question came up high on a search engine result, but I ended up using a different approach. Adding an answer to this old question in case other people with similar questions read this)

You can solve this with Json.Net and make an extension method to handle the items you want to loop:

public static Tuple<string, int, int> ToTuple(this JToken token)
    var type = token["attributes"]["OBJECT_TYPE"].ToString();
    var x = token["position"]["x"].Value<int>();
    var y = token["position"]["y"].Value<int>();
    return new Tuple<string, int, int>(type, x, y);

And then access the data like this: (scenario: writing to console):

var tuples = JObject.Parse(myJsonString)["objects"].Select(item => item.ToTuple()).ToList();
tuples.ForEach(t => Console.WriteLine("{0}: ({1},{2})", t.Item1, t.Item2, t.Item3));

Passing an array/list into a Python function

When you define your function using this syntax:

def someFunc(*args):
    for x in args
        print x

You're telling it that you expect a variable number of arguments. If you want to pass in a List (Array from other languages) you'd do something like this:

def someFunc(myList = [], *args):
    for x in myList:
        print x

Then you can call it with this:

items = [1,2,3,4,5]


You need to define named arguments before variable arguments, and variable arguments before keyword arguments. You can also have this:

def someFunc(arg1, arg2, arg3, *args, **kwargs):
    for x in args
        print x

Which requires at least three arguments, and supports variable numbers of other arguments and keyword arguments.

Sample database for exercise

Check out CodePlex for Microsoft SQL Server Community Projects & Samples

3rd party edit

On top of the link above you might look at

jQuery UI dialog box not positioned center screen

To fix this issue I made sure my body height was set to 100%.

body { height:100% }

This also maintains the center position while the user scrolls.

When to use the JavaScript MIME type application/javascript instead of text/javascript?

application because .js-Files aren't something a user wants to read but something that should get executed.

Read file from resources folder in Spring Boot

stuck in the same issue, this helps me

URL resource = getClass().getClassLoader().getResource("jsonschema.json");
JsonNode jsonNode = JsonLoader.fromURL(resource);

Have bash script answer interactive prompts

In my situation I needed to answer some questions without Y or N but with text or blank. I found the best way to do this in my situation was to create a shellscript file. In my case I called it

I was needing to answer some questions for a doctrine schema exporter so my file looked like this.

-- This is an example only --

php vendor/bin/mysql-workbench-schema-export mysqlworkbenchfile.mwb ./doctrine << EOF
`#Export to Doctrine Annotation Format`                                     1
`#Would you like to change the setup configuration before exporting`        y
`#Log to console`                                                           y
`#Log file`                                                                 testing.log
`#Filename [%entity%.%extension%]`
`#Indentation [4]`
`#Use tabs [no]`
`#Eol delimeter (win, unix) [win]`
`#Backup existing file [yes]`
`#Add generator info as comment [yes]`
`#Skip plural name checking [no]`
`#Use logged storage [no]`
`#Sort tables and views [yes]`
`#Export only table categorized []`
`#Enhance many to many detection [yes]`
`#Skip many to many tables [yes]`
`#Bundle namespace []`
`#Entity namespace []`
`#Repository namespace []`
`#Use automatic repository [yes]`
`#Skip column with relation [no]`
`#Related var name format [%name%%related%]`
`#Nullable attribute (auto, always) [auto]`
`#Generated value strategy (auto, identity, sequence, table, none) [auto]`
`#Default cascade (persist, remove, detach, merge, all, refresh, ) [no]`
`#Use annotation prefix [ORM\]`
`#Skip getter and setter [no]`
`#Generate entity serialization [yes]`
`#Generate extendable entity [no]`                                          y
`#Quote identifier strategy (auto, always, none) [auto]`
`#Extends class []`
`#Property typehint [no]`

The thing I like about this strategy is you can comment what your answers are and using EOF a blank line is just that (the default answer). Turns out by the way this exporter tool has its own JSON counterpart for answering these questions, but I figured that out after I did this =).

to run the script simply be in the directory you want and run 'sh' in terminal.

In short by using << EOL & EOF in combination with Return Lines you can answer each question of the prompt as necessary. Each new line is a new answer.

My example just shows how this can be done with comments also using the ` character so you remember what each step is.

Note the other advantage of this method is you can answer with more then just Y or N ... in fact you can answer with blanks!

Hope this helps someone out.

JavaScript moving element in the DOM

.before and .after

Use modern vanilla JS! Way better/cleaner than previously. No need to reference a parent.

const div1 = document.getElementById("div1");
const div2 = document.getElementById("div2");
const div3 = document.getElementById("div3");


Browser Support - 95% Global as of Oct '20

Undefined reference to pthread_create in Linux

You need to use the option -lpthread with gcc.

Python [Errno 98] Address already in use

A simple solution that worked for me is to close the Terminal and restart it.

Preventing form resubmission

You need to use PRG - Post/Redirect/Get pattern and you have just implemented the P of PRG. You need to Redirect. (Now days you do not need redirection at all. See this)

PRG is a web development design pattern that prevents some duplicate form submissions which means, Submit form (Post Request 1) -> Redirect -> Get (Request 2)

Under the hood

Redirect status code - HTTP 1.0 with HTTP 302 or HTTP 1.1 with HTTP 303

An HTTP response with redirect status code will additionally provide a URL in the location header field. The user agent (e.g. a web browser) is invited by a response with this code to make a second, otherwise identical, request to the new URL specified in the location field.

The redirect status code is to ensure that in this situation, the web user's browser can safely refresh the server response without causing the initial HTTP POST request to be resubmitted.

Double Submit Problem

Double Submit Problem

Post/Redirect/Get Solution

Post/Redirect/Get Solution


Enum ToString with user friendly strings

The simplest way is just to include this extension class into your project, it will work with any enum in the project:

public static class EnumExtensions
    public static string ToFriendlyString(this Enum code)
        return Enum.GetName(code.GetType(), code);


enum ExampleEnum
    Demo = 0,
    Test = 1, 
    Live = 2


ExampleEnum ee = ExampleEnum.Live;

TypeScript - Append HTML to container element in Angular 2

When working with Angular the recent update to Angular 8 introduced that a static property inside @ViewChild() is required as stated here and here. Then your code would require this small change:

@ViewChild('one') d1:ElementRef;


// query results available in ngOnInit
@ViewChild('one', {static: true}) foo: ElementRef;


// query results available in ngAfterViewInit
@ViewChild('one', {static: false}) foo: ElementRef;

How to use SQL LIKE condition with multiple values in PostgreSQL?

Use LIKE ANY(ARRAY['AAA%', 'BBB%', 'CCC%']) as per this cool trick @maniek showed earlier today.

How to get the groups of a user in Active Directory? (c#,

In case Translate works locally but not remotly e.i group.Translate(typeof(NTAccount)

If you want to have the application code executes using the LOGGED IN USER identity, then enable impersonation. Impersonation can be enabled thru IIS or by adding the following element in the web.config.

<identity impersonate="true"/>

If impersonation is enabled, the application executes using the permissions found in your user account. So if the logged in user has access, to a specific network resource, only then will he be able to access that resource thru the application.

Thank PRAGIM tech for this information from his diligent video

Windows authentication in Part 87:

But impersonation creates a lot of overhead on the server

The best solution to allow users of certain network groups is to deny anonymous in the web config <authorization><deny users="?"/><authentication mode="Windows"/>

and in your code behind, preferably in the global.asax, use the HttpContext.Current.User.IsInRole :

Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
If HttpContext.Current.User.IsInRole("TheDomain\TheGroup") Then
//code to do when user is in group
End If

NOTE: The Group must be written with a backslash \ i.e. "TheDomain\TheGroup"

How to create a trie in Python

Using defaultdict and reduce function.

Create Trie

from functools import reduce
from collections import defaultdict
T = lambda : defaultdict(T)
trie = T()
reduce(dict.__getitem__,'how',trie)['isEnd'] = True

Trie :

defaultdict(<function __main__.<lambda>()>,
            {'h': defaultdict(<function __main__.<lambda>()>,
                         {'o': defaultdict(<function __main__.<lambda>()>,
                                      {'w': defaultdict(<function __main__.<lambda>()>,
                                                   {'isEnd': True})})})})

Search In Trie :

curr = trie
for w in 'how':
    if w in curr:
        curr = curr[w]
        print("Not Found")
if curr['isEnd']:

PDO mysql: How to know if insert was successful

You can test the rowcount

    $sqlStatement->execute( ...);
    if ($sqlStatement->rowCount() > 0)
        return true;

How can I disable editing cells in a WPF Datagrid?

I see users in comments wondering how to disable cell editing while allowing row deletion : I managed to do this by setting all columns individually to read only, instead of the DataGrid itself.

<DataGrid IsReadOnly="False">
        <DataGridTextColumn IsReadOnly="True"/>
        <DataGridTextColumn IsReadOnly="True"/>

How to choose the id generation strategy when using JPA and Hibernate

Basically, you have two major choices:

  • You can generate the identifier yourself, in which case you can use an assigned identifier.
  • You can use the @GeneratedValue annotation and Hibernate will assign the identifier for you.

For the generated identifiers you have two options:

  • UUID identifiers.
  • Numerical identifiers.

For numerical identifiers you have three options:


IDENTITY is only a good choice when you cannot use SEQUENCE (e.g. MySQL) because it disables JDBC batch updates.

SEQUENCE is the preferred option, especially when used with an identifier optimizer like pooled or pooled-lo.

TABLE is to be avoided since it uses a separate transaction to fetch the identifier and row-level locks which scales poorly.

String to byte array in php

PHP has no explicit byte type, but its string is already the equivalent of Java's byte array. You can safely write fputs($connection, "The quick brown fox …"). The only thing you must be aware of is character encoding, they must be the same on both sides. Use mb_convert_encoding() when in doubt.

UICollectionView current visible cell index

For Swift 3.0

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    let visibleRect = CGRect(origin: colView.contentOffset, size: colView.bounds.size)
    let visiblePoint = CGPoint(x: visibleRect.midX, y: visibleRect.midY)
    let indexPath = colView.indexPathForItem(at: visiblePoint)

Setting a log file name to include current date in Log4j

Even if u use DailyRollingFileAppender like @gedevan suggested, u will still get logname.log.2008-10-10 (After a day, because the previous day log will get archived and the date will be concatenated to it's filename). So if u want .log at the end, u'll have to do it like this on the DatePattern:


JavaScript Array Push key value

You have to use bracket notation:

var obj = {};
obj[a[i]] = 0;

The result will be:

x = [{left: 0}, {top: 0}];

Maybe instead of an array of objects, you just want one object with two properties:

var x = {};


x[a[i]] = 0;

This will result in x = {left: 0, top: 0}.

Compilation error: stray ‘\302’ in program etc

I got the same with a character that visibly appeared as an asterisk, but was a UTF-8 sequence instead.

Encoder * st;

When compiled returned:

g.c:2:1: error: stray ‘\342’ in program
g.c:2:1: error: stray ‘\210’ in program
g.c:2:1: error: stray ‘\227’ in program

342 210 227 turns out to be UTF-8 for ASTERISK OPERATOR.

Deleting the '*' and typing it again fixed the problem.

Python list of dictionaries search

@Frédéric Hamidi's answer is great. In Python 3.x the syntax for .next() changed slightly. Thus a slight modification:

>>> dicts = [
     { "name": "Tom", "age": 10 },
     { "name": "Mark", "age": 5 },
     { "name": "Pam", "age": 7 },
     { "name": "Dick", "age": 12 }
>>> next(item for item in dicts if item["name"] == "Pam")
{'age': 7, 'name': 'Pam'}

As mentioned in the comments by @Matt, you can add a default value as such:

>>> next((item for item in dicts if item["name"] == "Pam"), False)
{'name': 'Pam', 'age': 7}
>>> next((item for item in dicts if item["name"] == "Sam"), False)

Pinging servers in Python

If you don't need to support Windows, here's a really concise way to do it:

import os
hostname = "" #example
response = os.system("ping -c 1 " + hostname)

#and then check the response...
if response == 0:
  print hostname, 'is up!'
  print hostname, 'is down!'

This works because ping returns a non-zero value if the connection fails. (The return value actually differs depending on the network error.) You could also change the ping timeout (in seconds) using the '-t' option. Note, this will output text to the console.

Custom Date Format for Bootstrap-DatePicker

I solve it editing the file bootstrap-datapicker.js.

Look for the text bellow in the file and edit the variable "Format:"

var defaults = $.fn.datepicker.defaults = {
    assumeNearbyYear: false,
    autoclose: false,
    beforeShowDay: $.noop,
    beforeShowMonth: $.noop,
    beforeShowYear: $.noop,
    beforeShowDecade: $.noop,
    beforeShowCentury: $.noop,
    calendarWeeks: false,
    clearBtn: false,
    toggleActive: false,
    daysOfWeekDisabled: [],
    daysOfWeekHighlighted: [],
    datesDisabled: [],
    endDate: Infinity,
    forceParse: true,
    format: 'dd/mm/yyyy',
    keyboardNavigation: true,
    language: 'en',
    minViewMode: 0,
    maxViewMode: 4,
    multidate: false,
    multidateSeparator: ',',
    orientation: "auto",
    rtl: false,
    startDate: -Infinity,
    startView: 0,
    todayBtn: false,
    todayHighlight: false,
    weekStart: 0,
    disableTouchKeyboard: false,
    enableOnReadonly: true,
    showOnFocus: true,
    zIndexOffset: 10,
    container: 'body',
    immediateUpdates: false,
    title: '',
    templates: {
        leftArrow: '&laquo;',
        rightArrow: '&raquo;'

how to redirect to home page

strRetMsg ="<script>window.location.href = '../Other/Home.htm';</script>";

Page.ClientScript.RegisterStartupScript(this.GetType(), "Script", strRetMsg,false);

Put this code in Page Load.

Jquery submit form

Since a jQuery object inherits from an array, and this array contains the selected DOM elements. Saying you're using an id and so the element should be unique within the DOM, you could perform a direct call to submit by doing :

$(".nextbutton").click(function() { 

Parse Error: Adjacent JSX elements must be wrapped in an enclosing tag

It is late to answer this question but I thought It will add to the explanation.

It is happening because any where in your code you are returning two elements simultaneously.


    <div id="div1"></div>
    <div id="div1"></div>

It should be wrapped in a parent element. e.g

      <div id="parent">
        <div id="div1"></div>
        <div id="div1"></div>

**More Detailed Explanation**

Your below jsx code get transformed

class App extends React.Component {
    return (
        <h1>Welcome to React</h1>

into this

_createClass(App, [{
    key: 'render',
    value: function render() {
      return React.createElement(
          'Welcome to React'

But if you do this

class App extends React.Component {
    return (
        <h1>Welcome to React</h1>

this gets converted into this(Just for illustration purpose, actually you will get error : Adjacent JSX elements must be wrapped in an enclosing tag)

_createClass(App, [{
    key: 'render',
    value: function render() {
      return React.createElement(
    return React.createElement(
          'Welcome to React'

In the above code you can see that you are trying to return twice from a method call, which is obviously wrong.

Edit- Latest changes in React 16 and own-wards:

If you do not want to add extra div to wrap around and want to return more than one child components you can go with React.Fragments.

React.Fragments (<React.Fragments>)are little bit faster and has less memory usage (no need to create an extra DOM node, less cluttered DOM tree).

e.g (In React 16.2.0)

render() {
  return (
       React fragments.
      <h2>A heading</h2>
      More React fragments.
      <h2>Another heading</h2>
      Even more React fragments.


render() {
  return (
       React fragments.
      <h2>A heading</h2>
      More React fragments.
      <h2>Another heading</h2>
      Even more React fragments.


render() {
 return [
  "Some text.",
  <h2 key="heading-1">A heading</h2>,
  "More text.",
  <h2 key="heading-2">Another heading</h2>,
  "Even more text."

Removing object from array in Swift 3

This is what I've used (Swift 5)...

    extension Array where Element:Equatable
        mutating func removeFirst(_ item:Any ) -> Any? {
            for index in 0..<self.count {
                if(item as? Element == self[index]) {
                    return self.remove(at: index)
            return nil
        mutating func removeLast(_ item:Any ) -> Any? {
            var index = self.count-1
            while index >= 0 {
                if(item as? Element == self[index]) {
                    return self.remove(at: index)
                index -= 1
            return nil

    var arrContacts:[String] = ["A","B","D","C","B","D"]
    var contacts: [Any] = ["B","D"]
    var index = 1
    index = 0


   ["A", "B", "D", "C", "B", "D"]
   ["A", "B", "C", "B", "D"]
   ["A", "B", "C", "D"]

Important: The array from which you remove items must contain Equatable elements (such as objects, strings, number, etc.)

Android Calling JavaScript functions in WebView


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



import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.bluapp.androidview.R;

public class WebViewActivity3 extends AppCompatActivity {
    private WebView webView;

    protected void onCreate(Bundle savedInstanceState) {
        webView = (WebView) findViewById(;
        webView.setWebViewClient(new WebViewClient());

        webView.setWebViewClient(new WebViewClient(){
            public void onPageFinished(WebView view, String weburl){
                webView.loadUrl("javascript:testEcho('Javascript function in webview')");

assets file

<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.0//EN" "">
<html xmlns="">
<meta forua="true" http-equiv="Cache-Control" content="max-age=0"/>

<body style="background-color:#212121">
<script type="text/javascript">
function testEcho(p1){


CSS/HTML: What is the correct way to make text italic?

OK, the first thing to note is that <i> has been deprecated, and shouldn't be used <i> has not been deprecated, but I still do not recommend using it—see the comments for details. This is because it goes entirely against keeping presentation in the presentation layer, which you've pointed out. Similarly, <span class="italic"> seems to break the mold too.

So now we have two real ways of doing things: <em> and <span class="footnote">. Remember that em stands for emphasis. When you wish to apply emphasis to a word, phrase or sentence, stick it in <em> tags regardless of whether you want italics or not. If you want to change the styling in some other way, use CSS: em { font-weight: bold; font-style: normal; }. Of course, you can also apply a class to the <em> tag: if you decide you want certain emphasised phrases to show up in red, give them a class and add it to the CSS:

Fancy some <em class="special">shiny</em> text?

em { font-weight: bold; font-style: normal; }
em.special { color: red; }

If you're applying italics for some other reason, go with the other method and give the section a class. That way, you can change its styling whenever you want without adjusting the HTML. In your example, footnotes should not be emphasised—in fact, they should be de-emphasised, as the point of a footnote is to show unimportant but interesting or useful information. In this case, you're much better off applying a class to the footnote and making it look like one in the presentation layer—the CSS.

Can't open and lock privilege tables: Table 'mysql.user' doesn't exist

As suggested above, i had similar issue with mysql-5.7.18,
i did this in this way

1. Executed this command from "MYSQL_HOME\bin\mysqld.exe --initialize-insecure"
2. then started "MYSQL_HOME\bin\mysqld.exe"
3. Connect workbench to this localhost:3306 with username 'root'
4. then executed this query "SET PASSWORD FOR 'root'@'localhost' = 'root';"

password was also updated successfully.

Safe width in pixels for printing web pages?

A solution to ensure that images don't get cut when printed in a Web page is to have the following CSS rule:

@media print { 
  img { 
    max-width:100% !important;

How can I retrieve the remote git address of a repo?

If you have the name of the remote, you will be able with git 2.7 (Q4 2015), to use the new git remote get-url command:

git remote get-url origin

(nice pendant of git remote set-url origin <newurl>)

See commit 96f78d3 (16 Sep 2015) by Ben Boeckel (mathstuf).
(Merged by Junio C Hamano -- gitster -- in commit e437cbd, 05 Oct 2015)

remote: add get-url subcommand

Expanding insteadOf is a part of ls-remote --url and there is no way to expand pushInsteadOf as well.
Add a get-url subcommand to be able to query both as well as a way to get all configured urls.

What is the difference between "long", "long long", "long int", and "long long int" in C++?

Historically, in early C times, when processors had 8 or 16 bit wordlength,intwas identical to todays short(16 bit). In a certain sense, int is a more abstract data type thanchar,short,longorlong long, as you cannot be sure about the bitwidth.

When definingint n;you could translate this with "give me the best compromise of bitwidth and speed on this machine for n". Maybe in the future you should expect compilers to translateintto be 64 bit. So when you want your variable to have 32 bits and not more, better use an explicitlongas data type.

[Edit: #include <stdint.h> seems to be the proper way to ensure bitwidths using the int##_t types, though it's not yet part of the standard.]

Trigger validation of all fields in Angular Form submit

One approach is to force all attributes to be dirty. You can do that in each controller, but it gets very messy. It would be better to have a general solution.

The easiest way I could think of was to use a directive

  • it will handle the form submit attribute
  • it iterates through all form fields and marks pristine fields dirty
  • it checks if the form is valid before calling the submit function

Here is the directive

myModule.directive('submit', function() {
  return {
    restrict: 'A',
    link: function(scope, formElement, attrs) {
      var form;
      form = scope[];
      return formElement.bind('submit', function() {
        angular.forEach(form, function(field, name) {
          if (typeof name === 'string' && !name.match('^[\$]')) {
            if (field.$pristine) {
              return field.$setViewValue(field.$value);
        if (form.$valid) {
          return scope.$apply(attrs.submit);

And update your form html, for example:

 <form ng-submit='justDoIt()'>


 <form name='myForm' novalidate submit='justDoIt()'>

See a full example here:

How can I set up an editor to work with Git on Windows?

Thanks to the Stack Overflow community ... and a little research I was able to get my favorite editor, EditPad Pro, to work as the core editor with msysgit 1.7.5.GIT and TortoiseGit v1.7.3.0 over Windows XP SP3...

Following the advice above, I added the path to a Bash script for the code editor...

git config --global core.editor c:/msysgit/cmd/

However, after several failed attempts at the above mentioned solutions ... I was finally able to get this working. Per EditPad Pro's documentation, adding the '/newinstance' flag would allow the shell to wait for the editor input...

The '/newinstance' flag was the key in my case...

"C:/Program Files/JGsoft/EditPadPro6/EditPadPro.exe" //newinstance "$*"

How to efficiently build a tree from a flat structure?

Vague as the question seems to me, I would probably create a map from the ID to the actual object. In pseudo-java (I didn't check whether it works/compiles), it might be something like:

Map<ID, FlatObject> flatObjectMap = new HashMap<ID, FlatObject>();

for (FlatObject object: flatStructure) {
    flatObjectMap.put(object.ID, object);

And to look up each parent:

private FlatObject getParent(FlatObject object) {

private FlatObject getRealObject(ID objectID) {

By reusing getRealObject(ID) and doing a map from object to a collection of objects (or their IDs), you get a parent->children map too.

How to add a touch event to a UIView?

You can achieve this by adding Gesture Recogniser in your code.

Step 1: ViewController.m:

// Declare the Gesture.
UITapGestureRecognizer *gesRecognizer = [[UITapGestureRecognizer alloc] 
gesRecognizer.delegate = self;

// Add Gesture to your view.
[yourView addGestureRecognizer:gesRecognizer]; 

Step 2: ViewController.m:

// Declare the Gesture Recogniser handler method.
- (void)handleTap:(UITapGestureRecognizer *)gestureRecognizer{

NOTE: here yourView in my case was @property (strong, nonatomic) IBOutlet UIView *localView;

EDIT: *localView is the white box in Main.storyboard from below

enter image description here

enter image description here

How do I increase the capacity of the Eclipse output console?

For C++ users, to increase the Build console output size see here

ie Windows > Preference > C/C++ > Build > Console

Show hide divs on click in HTML and CSS without jQuery

Using display:none is not SEO-friendly. The following way allows the hidden content to be searchable. Adding the transition-delay ensures any links included in the hidden content is clickable.

.collapse > p{
cursor: pointer;
display: block;

outline: none;

.collapse > div {
height: 0;
width: 0;
overflow: hidden;
transition-delay: 0.3s;

.collapse:focus div{
display: block; 
height: 100%;
width: 100%;
overflow: auto;

<div class="collapse" tabindex="1">
<p>Question 1</p>
  <p>Visit <a href="">Stack Overflow</a></p>
<div class="collapse" tabindex="2">
<p>Question 2</p>
  <p>Visit <a href="">Stack Overflow</a></p>

Import CSV file with mixed data types

% Assuming that the dataset is ";"-delimited and each line ends with ";"
fid = fopen('sampledata.csv');
tline = fgetl(fid);
u=sprintf('%c',tline); c=length(u);
id=findstr(u,';'); n=length(id);
for I=1:n
    if I==1
while ischar(tline)
    tline = fgetl(fid);
        for I=1:n
            if I==1

How to add border radius on table row

All the answers are way too long. The easiest way to add border radius to a table element that accepts border as a property, is doing border radius with overflow: hidden.

border: xStyle xColor xSize;
border-collapse: collapse;
border-radius: 1em;
overflow: hidden;

How to remove lines in a Matplotlib plot

Hopefully this can help others: The above examples use ax.lines. With more recent mpl (3.3.1), there is ax.get_lines(). This bypasses the need for calling ax.lines=[]

for line in ax.get_lines(): # ax.lines:
# ax.lines=[] # needed to complete removal when using ax.lines

The program can't start because MSVCR110.dll is missing from your computer

Weird, just had simmilar issue, went here downloaded and installed vcredist_x86 (i'm using 32bit apache) and it works like a charm.

Java Regex Capturing Groups

From the doc :

Capturing groups</a> are indexed from left
 * to right, starting at one.  Group zero denotes the entire pattern, so
 * the expression is equivalent to

So capture group 0 send the whole line.

How to copy directories in OS X 10.7.3?


cp -R "/src/project 1/App" "/src/project 2"


Using quotes will cater for spaces in the directory names

cp -R "/src/project 1/App" "/src/project 2"

If the App directory is specified in the destination directory:

cp -R "/src/project 1/App" "/src/project 2/App"

and "/src/project 2/App" already exists the result will be "/src/project 2/App/App"

Best not to specify the directory copied in the destination so that the command can be repeated over and over with the expected result.

Inside a bash script:

cp -R "${1}/App" "${2}"

Command-line svn for Windows?

VisualSVN for Windows has a command-line-only executable (as well Visual Studio plugins). See

It is completely portable, so no installation is necessary.

How to detect a textbox's content has changed

I would recommend taking a look at jQuery UI autocomplete widget. They handled most of the cases there since their code base is more mature than most ones out there.

Below is a link to a demo page so you can verify it works.

You will get the most benefit from reading the source and seeing how they solved it. You can find it here:

Basically they do it all, they bind to input, keydown, keyup, keypress, focus and blur. Then they have special handling for all sorts of keys like page up, page down, up arrow key and down arrow key. A timer is used before getting the contents of the textbox. When a user types a key that does not correspond to a command (up key, down key and so on) there is a timer that explorers the content after about 300 milliseconds. It looks like this in the code:

// switch statement in the 
switch( event.keyCode ) {
            case keyCode.ENTER:
            case keyCode.NUMPAD_ENTER:
                // when menu is open and has focus
                if ( ) {
                    // #6055 - Opera still allows the keypress to occur
                    // which causes forms to submit
                    suppressKeyPress = true;
           event );
                suppressKeyPressRepeat = true;
                // search timeout should be triggered before the input value is changed
                this._searchTimeout( event );
// ...
// ...
_searchTimeout: function( event ) {
    clearTimeout( this.searching );
    this.searching = this._delay(function() { // * essentially a warpper for a setTimeout call *
        // only search if the value has changed
        if ( this.term !== this._value() ) { // * _value is a wrapper to get the value *
            this.selectedItem = null;
   null, event );
    }, this.options.delay );

The reason to use a timer is so that the UI gets a chance to be updated. When Javascript is running the UI cannot be updated, therefore the call to the delay function. This works well for other situations such as keeping focus on the textbox (used by that code).

So you can either use the widget or copy the code into your own widget if you are not using jQuery UI (or in my case developing a custom widget).

Condition within JOIN or WHERE

The relational algebra allows interchangeability of the predicates in the WHERE clause and the INNER JOIN, so even INNER JOIN queries with WHERE clauses can have the predicates rearrranged by the optimizer so that they may already be excluded during the JOIN process.

I recommend you write the queries in the most readable way possible.

Sometimes this includes making the INNER JOIN relatively "incomplete" and putting some of the criteria in the WHERE simply to make the lists of filtering criteria more easily maintainable.

For example, instead of:

FROM Customers c
INNER JOIN CustomerAccounts ca
    ON ca.CustomerID = c.CustomerID
    AND c.State = 'NY'
INNER JOIN Accounts a
    ON ca.AccountID = a.AccountID
    AND a.Status = 1


FROM Customers c
INNER JOIN CustomerAccounts ca
    ON ca.CustomerID = c.CustomerID
INNER JOIN Accounts a
    ON ca.AccountID = a.AccountID
WHERE c.State = 'NY'
    AND a.Status = 1

But it depends, of course.

Bootstrap control with multiple "data-toggle"

<a data-toggle="tooltip" data-placement="top" title="My Tooltip text!">+</a>