Programs & Examples On #System.printing

Why won't my PHP app send a 404 error?

Try this:

if (strstr($_SERVER['REQUEST_URI'],'index.php')) {
    header('HTTP/1.0 404 Not Found');
    echo "<head><title>404 Not Found</title></head>";
    echo "<h1>Not Found</h1>";
    $uri   = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
    echo "<p>The requested URL ".$uri." was not found on this server.</p>";

Open local folder from link

Local Explorer - File Manager on web browser extention can solve for chrome

but still some encoding problems

How to convert empty spaces into null values, using SQL Server?

This code generates some SQL which can achieve this on every table and column in the database:

   WHERE [' + COLUMN_NAME + '] = '''''
    DATA_TYPE IN ('char','nchar','varchar','nvarchar')

Android How to adjust layout in Full Screen Mode when softkeyboard is visible

I tried many solutions include Joseph Johnson's and Johan Stuyts's. But as a result I got a white space between content and keyboard on some devices (like Lenovo s820) in all cases. So I made some changes to their codes and finally got working solution.

My idea based on adding margin to top of content when keyboard is showing.

    int usableHeightNow = contentAreaOfWindowBounds.height();

    if (usableHeightNow != usableHeightPrevious) {

        int difference = usableHeightNow - usableHeightPrevious;

        if (difference < 0 && difference < -150) {
            keyboardShowed = true;
            rootViewLayout.topMargin -= difference + 30;
            rootViewLayout.bottomMargin += 30;
        else if (difference < 0 && difference > -150){
            rootViewLayout.topMargin -= difference + 30;
        else if (difference > 0 && difference > 150) {
            keyboardShowed = false;
            rootViewLayout.topMargin = 0;
            rootViewLayout.bottomMargin = 0;


        Log.e("Bug Workaround", "Difference: " + difference);

        usableHeightPrevious = usableHeightNow;

As you can see, I add 30 px to difference because there is a small white space between top of the screen and content zone with margin. And I dont know whence it appears so I decided just make margins smaller and now it works exactly how I needed.

How to limit the maximum value of a numeric field in a Django model?

There are two ways to do this. One is to use form validation to never let any number over 50 be entered by a user. Form validation docs.

If there is no user involved in the process, or you're not using a form to enter data, then you'll have to override the model's save method to throw an exception or limit the data going into the field.

What's a "static method" in C#?

When you add a "static" keyword to a method, it means that underlying implementation gives the same result for any instance of the class. Needless to say, result varies with change in the value of parameters

Unable to set data attribute using jQuery Data() API

Happened the same to me. It turns out that

var data = $("#myObject").data();

gives you a non-writable object. I solved it using:

var data = $.extend({}, $("#myObject").data());

And from then on, data was a standard, writable JS object.

Should jQuery's $(form).submit(); not trigger onSubmit within the form tag?

Try to trigger() event in your function:

$("form").trigger('submit'); // and then... do submit()

Using Environment Variables with Vue.js

If you are using Vue cli 3, only variables that start with VUE_APP_ will be loaded.

In the root create a .env file with:


And, if it's running, you need to restart serve so that the new env vars can be loaded.

With this, you will be able to use process.env.VUE_APP_ENV_VARIABLE in your project (.js and .vue files).


According to @ali6p, with Vue Cli 3, isn't necessary to install dotenv dependency.

What is apache's maximum url length?

Allowed default size of URI is 8177 characters in GET request. Simple code in python for such testing.

#!/usr/bin/env python2

import sys
import socket

if __name__ == "__main__":
    string = sys.argv[1]
    buf_get = "x" * int(string)
    buf_size = 1024
    request = "HEAD %s HTTP/1.1\nHost:localhost\n\n" % buf_get
    print "===>", request

    sock_http = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock_http.connect(("localhost", 80))
    while True:
       print "==>", sock_http.recv(buf_size)
       if not sock_http.recv(buf_size):

On 8178 characters you will get such message: HTTP/1.1 414 Request-URI Too Large

How to view data saved in android database(SQLite)?

If you are able to copy the actual SQLite database file to your desktop, you can use this tools to browse the data.

How can I retrieve Id of inserted entity using Entity framework?

I had been using Ladislav Mrnka's answer to successfully retrieve Ids when using the Entity Framework however I am posting here because I had been miss-using it (i.e. using it where it wasn't required) and thought I would post my findings here in-case people are looking to "solve" the problem I had.

Consider an Order object that has foreign key relationship with Customer. When I added a new customer and a new order at the same time I was doing something like this;

var customer = new Customer(); //no Id yet;
var order = new Order(); //requires Customer.Id to link it to customer;
context.SaveChanges();//this generates the Id for customer
order.CustomerId = customer.Id;//finally I can set the Id

However in my case this was not required because I had a foreign key relationship between customer.Id and order.CustomerId

All I had to do was this;

var customer = new Customer(); //no Id yet;
var order = new Order{Customer = customer}; 
context.SaveChanges();//adds customer.Id to customer and the correct CustomerId to order

Now when I save the changes the id that is generated for customer is also added to order. I've no need for the additional steps

I'm aware this doesn't answer the original question but thought it might help developers who are new to EF from over-using the top-voted answer for something that may not be required.

This also means that updates complete in a single transaction, potentially avoiding orphin data (either all updates complete, or none do).

How to get the Display Name Attribute of an Enum member via MVC Razor code?

In .NET5, I used DisplayTextFor without needing helper or extension methods:

@Html.DisplayTextFor(m => m.SomeEnumProperty)

Where SomeEnumProperty has a value of:

public enum MyEnum
    [Display(Name = "Not started")]
    NotStarted = 0,
    [Display(Name = "Weird display name instead of just 'Started'")]
    Started = 1,

How to center and crop an image to always appear in square shape with CSS?

    <img class="crop" src=""/>

<img src=""/>

div {
    width: 200px;
    height: 200px;
    overflow: hidden;
    margin: 10px;
    position: relative;
.crop {
    position: absolute;
    left: -100%;
    right: -100%;
    top: -100%;
    bottom: -100%;
    margin: auto; 
    height: auto;
    width: auto;

How to upgrade rubygems

I found other answers to be inaccurate/outdated. Best is to refer to the actual documentation.

Short version: in most cases gem update --system will suffice.

You should not blindly use sudo. In fact if you're not required to do so you most likely should not use it.

How and when to use SLEEP() correctly in MySQL?


But what are you using this for? Are you trying to circumvent/reinvent mutexes or transactions?

How to list all Git tags?

If you want to check you tag name locally, you have to go to the path where you have created tag(local path). Means where you have put your objects. Then type command:

git show --name-only <tagname>

It will show all the objects under that tag name. I am working in Teradata and object means view, table etc

jQuery: Get the cursor position of text in input without browser specific code?

A warning about the Jquery Caret plugin.

It will conflict with the Masked Input plugin (or vice versa). Fortunately the Masked Input plugin includes a caret() function of its own, which you can use very similarly to the Caret plugin for your basic needs - $(element).caret().begin or .end

Equal height rows in CSS Grid Layout

The short answer is that setting grid-auto-rows: 1fr; on the grid container solves what was asked.

How can I control Chromedriver open window size?

C# version of @yonatan-kiron's answer, and Selenium's using statement from their example code.

ChromeOptions chromeOptions = new ChromeOptions();

using (IWebDriver driver = new ChromeDriver(chromeOptions))

Could not get constructor for org.hibernate.persister.entity.SingleTableEntityPersister

I encountered this error when upgrading from jdk10 to jdk11. Adding the following dependency fixed the problem:


.append(), prepend(), .after() and .before()

append() & prepend() are for inserting content inside an element (making the content its child) while after() & before() insert content outside an element (making the content its sibling).

How To Use DateTimePicker In WPF?

There is DatePicker in WPF Tool Kit, but I have not seen DateTime Picker in WPF ToolKit. So I don't know what kind of DateTimePicker control John is talking about.

How can I import data into mysql database via mysql workbench?

  1. Open Connetion
  2. Select "Administration" tab
  3. Click on Data import

Upload sql file

enter image description here

Make sure to select your database in this award winning GUI:

enter image description here

Bootstrap 3 .col-xs-offset-* doesn't work?

You could get the offset set only for xs devises by negating the higher pixels with 0 offset. Like so,

class="col-xs-offset-1 col-md-offset-0"

How to properly override clone method?

Use serialization to make deep copies. This is not the quickest solution but it does not depend on the type.

Adding multiple class using ng-class

Other way we can create a function to control "using multiple class"


    .Red {
        color: Red;
    .Yellow {
        color: Yellow;
      .Blue {
        color: Blue;
      .Green {
        color: Green;
    .Gray {
        color: Gray;
    .b {
         font-weight: bold;


    angular.module('myapp', [])
            .controller('ExampleController', ['$scope', function ($scope) {
                $scope.MyColors = ['It is Red', 'It is Yellow', 'It is Blue', 'It is Green', 'It is Gray'];
                $scope.getClass = function (strValue) {
                    if (strValue == ("It is Red"))
                        return "Red";
                    else if (strValue == ("It is Yellow"))
                        return "Yellow";
                    else if (strValue == ("It is Blue"))
                        return "Blue";
                    else if (strValue == ("It is Green"))
                        return "Green";
                    else if (strValue == ("It is Gray"))
                        return "Gray";

Using it

<body ng-app="myapp" ng-controller="ExampleController">

<h2>AngularJS ng-class if example</h2>
<ul >
    <li ng-repeat="icolor in MyColors" >
        <p ng-class="[getClass(icolor), 'b']">{{icolor}}</p>

You can refer to full code page at ng-class if example

Permission denied: /var/www/abc/.htaccess pcfg_openfile: unable to check htaccess file, ensure it is readable?

I have also got stuck into this and believe me disabling SELinux is not a good idea.

Please just use below and you are good,

sudo restorecon -R /var/www/mysite


Restricting JTextField input to Integers

When you type integer numbers to JtextField1 after key release it will go to inside try , for any other character it will throw NumberFormatException. If you set empty string to jTextField1 inside the catch so the user cannot type any other keys except positive numbers because JTextField1 will be cleared for each bad attempt.

int x;
JTextField jTextField1;

 //Gui Code Here

private void jTextField1KeyReleased(java.awt.event.KeyEvent evt) {                                        
    try {
        x = Integer.parseInt(jTextField1.getText());
    } catch (NumberFormatException nfe) {

Delete commit on gitlab

  1. git reset --hard CommitId
  2. git push -f origin master

1st command will rest your head to commitid and 2nd command will delete all commit after that commit id on master branch.

Note: Don't forget to add -f in push otherwise it will be rejected.

count (non-blank) lines-of-code in bash

rgrep . | wc -l

gives the count of non blank lines in the current working directory.

how to check and set max_allowed_packet mysql variable

goto cpanel and login as Main Admin or Super Administrator

  1. find SSH/Shell Access ( you will find under the security tab of cpanel )

  2. now give the username and password of Super Administrator as root or whatyougave

    note: do not give any username, cos, it needs permissions
  3. once your into console type

    type ' mysql ' and press enter now you find youself in

    mysql> /* and type here like */

    mysql> set global net_buffer_length=1000000;

    Query OK, 0 rows affected (0.00 sec)

    mysql> set global max_allowed_packet=1000000000;

    Query OK, 0 rows affected (0.00 sec)

Now upload and enjoy!!!

Validate phone number with JavaScript

First off, your format validator is obviously only appropriate for NANP (country code +1) numbers. Will your application be used by someone with a phone number from outside North America? If so, you don't want to prevent those people from entering a perfectly valid [international] number.

Secondly, your validation is incorrect. NANP numbers take the form NXX NXX XXXX where N is a digit 2-9 and X is a digit 0-9. Additionally, area codes and exchanges may not take the form N11 (end with two ones) to avoid confusion with special services except numbers in a non-geographic area code (800, 888, 877, 866, 855, 900) may have a N11 exchange.

So, your regex will pass the number (123) 123 4566 even though that is not a valid phone number. You can fix that by replacing \d{3} with [2-9]{1}\d{2}.

Finally, I get the feeling you're validating user input in a web browser. Remember that client-side validation is only a convenience you provide to the user; you still need to validate all input (again) on the server.

TL;DR don't use a regular expression to validate complex real-world data like phone numbers or URLs. Use a specialized library.

How can I check whether Google Maps is fully loaded?

If you're using the Maps API v3, this has changed.

In version 3, you essentially want to set up a listener for the bounds_changed event, which will trigger upon map load. Once that has triggered, remove the listener as you don't want to be informed every time the viewport bounds change.

This may change in the future as the V3 API is evolving :-)

gulp command not found - error after installing gulp

  1. When you've installed gulp global, you need to go to


  2. There you do

    SHIFT + Right Click

  3. Choose "Open command prompt here"

  4. Run gulp from that cmd window

Proper usage of Java -D command-line parameters

You're giving parameters to your program instead to Java. Use

java -Dtest="true" -jar myApplication.jar 


Consider using


to avoid the NPE. But do not use "Yoda conditions" always without thinking, sometimes throwing the NPE is the right behavior and sometimes something like

System.getProperty("test") == null || System.getProperty("test").equalsIgnoreCase("true")

is right (providing default true). A shorter possibility is


but not using double negation doesn't make it less hard to misunderstand.

How to keep two folders automatically synchronized?

You can take advantage of fschange. It’s a Linux filesystem change notification. The source code is downloadable from the above link, you can compile it yourself. fschange can be used to keep track of file changes by reading data from a proc file (/proc/fschange). When data is written to a file, fschange reports the exact interval that has been modified instead of just saying that the file has been changed. If you are looking for the more advanced solution, I would suggest checking Resilio Connect. It is cross-platform, provides extended options for use and monitoring. Since it’s BitTorrent-based, it is faster than any other existing sync tool. It was written on their behalf.

How to install a node.js module without using npm?

You can clone the module directly in to your local project.

Start terminal. cd in to your project and then:

npm install --save

Disabling browser caching for all browsers from ASP.NET

See also How to prevent google chrome from caching my inputs, esp hidden ones when user click back? without which Chrome might reload but preserve the previous content of <input> elements -- in other words, use autocomplete="off".

How to view the current heap size that an application is using?

Attach with jvisualvm from Sun Java 6 JDK. Startup flags are listed.

How to comment out a block of code in Python

The only cure I know for this is a good editor. Sorry.

find all subsets that sum to a particular value

You may use Dynamic Programmining. Algo complexity is O(Sum * N) and use O(Sum) memory.

Here's my implementation in C#:

private static int GetmNumberOfSubsets(int[] numbers, int sum)
    int[] dp = new int[sum + 1];
    dp[0] = 1;
    int currentSum =0;
    for (int i = 0; i < numbers.Length; i++)
        currentSum += numbers[i];
        for (int j = Math.Min(sum, currentSum); j >= numbers[i]; j--)
            dp[j] += dp[j - numbers[i]];

    return dp[sum];

Notes: As number of subsets may have value 2^N it easy may overflows int type.

Algo works only for positive numbers.

How to get commit history for just one branch?

I think an option for your purposes is git log --online --decorate. This lets you know the checked commit, and the top commits for each branch that you have in your story line. By doing this, you have a nice view on the structure of your repo and the commits associated to a specific branch. I think reading this might help.

Foreach loop in java for a custom object list

for(Room room : rooms) {
  //room contains an element of rooms

Why do this() and super() have to be the first statement in a constructor?

I know I am a little late to the party, but I've used this trick a couple of times (and I know it's a bit unusual):

I create an generic interface InfoRunnable<T> with one method:

public T run(Object... args);

And if I need to do something before passing it to the constructor I just do this:

super(new InfoRunnable<ThingToPass>() {
    public ThingToPass run(Object... args) {
        /* do your things here */
}.run(/* args here */));

Eclipse and Windows newlines

There is a handy bash utility - dos2unix - which is a DOS/MAC to UNIX text file format converter, that if not already installed on your distro, should be able to be easily installed via a package manager. dos2unix man page

Maven Error: Could not find or load main class

I got it too, the key was to change the output folder from bin to target\classes. It seems that in Eclipse, when converting a project to Maven project, this step is not done automatically, but Maven project will not look for main class based on bin, but will on target\classes.

How do I read the source code of shell commands?

    cd ~ && apt-get source coreutils && ls -d coreutils*     

You should be able to use a command like this on ubuntu to gather the source for a package, you can omit sudo assuming your downloading to a location you own.

Cannot resolve symbol 'AppCompatActivity'

Try this. In Android Studio, after putting the dependency in build.gradle. Go to Build --> Clean Project.

It worked for me.

How to check for Is not Null And Is not Empty string in SQL server?

in basic way

FROM [TableName]
WHERE column_name!='' AND column_name IS NOT NULL

What is a good Hash Function?

A good hash function should

  1. be bijective to not loose information, where possible, and have the least collisions
  2. cascade as much and as evenly as possible, i.e. each input bit should flip every output bit with probability 0.5 and without obvious patterns.
  3. if used in a cryptographic context there should not exist an efficient way to invert it.

A prime number modulus does not satisfy any of these points. It is simply insufficient. It is often better than nothing, but it's not even fast. Multiplying with an unsigned integer and taking a power-of-two modulus distributes the values just as well, that is not well at all, but with only about 2 cpu cycles it is much faster than the 15 to 40 a prime modulus will take (yes integer division really is that slow).

To create a hash function that is fast and distributes the values well the best option is to compose it from fast permutations with lesser qualities like they did with PCG for random number generation.

Useful permutations, among others, are:

  • multiplication with an uneven integer
  • binary rotations
  • xorshift

Following this recipe we can create our own hash function or we take splitmix which is tested and well accepted.

If cryptographic qualities are needed I would highly recommend to use a function of the sha family, which is well tested and standardised, but for educational purposes this is how you would make one:

First you take a good non-cryptographic hash function, then you apply a one-way function like exponentiation on a prime field or k many applications of (n*(n+1)/2) mod 2^k interspersed with an xorshift when k is the number of bits in the resulting hash.

Is there a way to change the spacing between legend items in ggplot2?

Now that opts is deprecated in ggplot2 package, function theme should be used instead:

library(grid) # for unit()
... + theme(legend.key.height=unit(3,"line"))
... + theme(legend.key.width=unit(3,"line"))

git rm - fatal: pathspec did not match any files

Step 1

Add the file name(s) to your .gitignore file.

Step 2

git filter-branch --force --index-filter \
    'git rm -r --cached --ignore-unmatch YOURFILE' \
    --prune-empty --tag-name-filter cat -- --all

Step 3

git push -f origin branch

A big thank you to @mu.

Python error: AttributeError: 'module' object has no attribute

More accurately, your mod1 and lib directories are not modules, they are packages. The file is a module.

Python does not automatically import subpackages or modules. You have to explicitly do it, or "cheat" by adding import statements in the initializers.

>>> import lib
>>> dir(lib)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__']
>>> import lib.pkg1
>>> import lib.pkg1.mod11
>>> lib.pkg1.mod11.mod12()

An alternative is to use the from syntax to "pull" a module from a package into you scripts namespace.

>>> from lib.pkg1 import mod11

Then reference the function as simply mod11.mod12().

Oracle: what is the situation to use RAISE_APPLICATION_ERROR?

if your application accepts errors raise from Oracle, then you can use it. we have an application, each time when an error happens, we call raise_application_error, the application will popup a red box to show the error message we provide through this method.

When using dotnet code, I just use "raise", dotnet exception mechanisim will automatically capture the error passed by Oracle ODP and shown inside my catch exception code.

How to create helper file full of functions in react native?

I am sure this can help. Create fileA anywhere in the directory and export all the functions.

export const func1=()=>{
    // do stuff
export const func2=()=>{
    // do stuff 
export const func3=()=>{
    // do stuff 
export const func4=()=>{
    // do stuff 
export const func5=()=>{
    // do stuff 

Here, in your React component class, you can simply write one import statement.

import React from 'react';
import {func1,func2,func3} from 'path_to_fileA';

class HtmlComponents extends React.Component {
        //do stuff. 
        // foo==bar
   render() {
      return (
             <h1>React Components</h1>
             <RippleButton onClick={this.rippleClickFunction}/>

export default HtmlComponents;

Speed tradeoff of Java's -Xms and -Xmx options

It is difficult to say how the memory allocation will affect your speed. It depends on the garbage collection algorithm the JVM is using. For example if your garbage collector needs to pause to do a full collection, then if you have 10 more memory than you really need then the collector will have 10 more garbage to clean up.

If you are using java 6 you can use the jconsole (in the bin directory of the jdk) to attach to your process and watch how the collector is behaving. In general the collectors are very smart and you won't need to do any tuning, but if you have a need there are numerous options you have use to further tune the collection process.

PowerShell try/catch/finally

That is very odd.

I went through ItemNotFoundException's base classes and tested the following multiple catches to see what would catch it:

try {
  remove-item C:\nonexistent\file.txt -erroraction stop
catch [System.Management.Automation.ItemNotFoundException] {
  write-host 'ItemNotFound'
catch [System.Management.Automation.SessionStateException] {
  write-host 'SessionState'
catch [System.Management.Automation.RuntimeException] {
  write-host 'RuntimeException'
catch [System.SystemException] {
  write-host 'SystemException'
catch [System.Exception] {
  write-host 'Exception'
catch {
  write-host 'well, darn'

As it turns out, the output was 'RuntimeException'. I also tried it with a different exception CommandNotFoundException:

try {
catch [System.Management.Automation.CommandNotFoundException] {
  write-host 'CommandNotFoundException'
catch {
  write-host 'well, darn'

That output 'CommandNotFoundException' correctly.

I vaguely remember reading elsewhere (though I couldn't find it again) of problems with this. In such cases where exception filtering didn't work correctly, they would catch the closest Type they could and then use a switch. The following just catches Exception instead of RuntimeException, but is the switch equivalent of my first example that checks all base types of ItemNotFoundException:

try {
  Remove-Item C:\nonexistent\file.txt -ErrorAction Stop
catch [System.Exception] {
  switch($_.Exception.GetType().FullName) {
    'System.Management.Automation.ItemNotFoundException' {
      write-host 'ItemNotFound'
    'System.Management.Automation.SessionStateException' {
      write-host 'SessionState'
    'System.Management.Automation.RuntimeException' {
      write-host 'RuntimeException'
    'System.SystemException' {
      write-host 'SystemException'
    'System.Exception' {
      write-host 'Exception'
    default {'well, darn'}

This writes 'ItemNotFound', as it should.

Split string in JavaScript and detect line break

Split string in JavaScript

var array = str.match(/[^\r\n]+/g);


var array = str.split(/\r?\n/);


Convert integer to hexadecimal and back again


Very well explained and few programming lines GOOD JOB

// Store integer 182
int intValue = 182;
// Convert integer 182 as a hex in a string variable
string hexValue = intValue.ToString("X");
// Convert the hex string back to the number
int intAgain = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);


Something from the old school very old procedure of pascal converted to C #

    /// <summary>
    /// Conver number from Decadic to Hexadecimal
    /// </summary>
    /// <param name="w"></param>
    /// <returns></returns>
    public string MakeHex(int w)
           char[] b =  {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
           char[] S = new char[7];

              S[0] = b[(w >> 24) & 15];
              S[1] = b[(w >> 20) & 15];
              S[2] = b[(w >> 16) & 15];
              S[3] = b[(w >> 12) & 15];
              S[4] = b[(w >> 8) & 15];
              S[5] = b[(w >> 4) & 15];
              S[6] = b[w & 15];

              string _MakeHex = new string(S, 0, S.Count());

              return _MakeHex;
        catch (Exception ex)


"CAUTION: provisional headers are shown" in Chrome debugger

I came across this and it went away when I switched from https to http. The SSL certs we use in dev aren't verified by a 3rd party. They're just locally generated dev certs.

The same calls work just fine in Chrome Canary and Firefox. These browsers don't appear to be as strict about the SSL cert as Chrome is. The calls would fail in Chrome with the "CAUTION: Provisional headers..." message.

I think/hope that when we use a legit SSL cert in stage and prod, we won't see this behavior in Chrome anymore.

Bubble Sort Homework

arr = [5,4,3,1,6,8,10,9] # array not sorted

for i in range(len(arr)):
    for j in range(i, len(arr)):
        if(arr[i] > arr[j]):
            arr[i], arr[j] = arr[j], arr[i]

            print (arr)

Finish an activity from another activity

I've just applied Nepster's solution and works like a charm. There is a minor modification to run it from a Fragment.

To your Fragment

// sending intent to onNewIntent() of MainActivity
Intent intent = new Intent(getActivity(), MainActivity.class);
intent.putExtra("transparent_nav_changed", true);

And to your OnNewIntent() of the Activity you would like to restart.

// recreate activity when transparent_nav was just changed
if (getIntent().getBooleanExtra("transparent_nav_changed", false)) {
    finish(); // finish and create a new Instance
    Intent restarter = new Intent(MainActivity.this, MainActivity.class);

What is the difference between `sorted(list)` vs `list.sort()`?

Here are a few simple examples to see the difference in action:

See the list of numbers here:

nums = [1, 9, -3, 4, 8, 5, 7, 14]

When calling sorted on this list, sorted will make a copy of the list. (Meaning your original list will remain unchanged.)

Let's see.



[-3, 1, 4, 5, 7, 8, 9, 14]

Looking at the nums again


We see the original list (unaltered and NOT sorted.). sorted did not change the original list

[1, 2, -3, 4, 8, 5, 7, 14]

Taking the same nums list and applying the sort function on it, will change the actual list.

Let's see.

Starting with our nums list to make sure, the content is still the same.


[-3, 1, 4, 5, 7, 8, 9, 14]


Now the original nums list is changed and looking at nums we see our original list has changed and is now sorted.

[-3, 1, 2, 4, 5, 7, 8, 14]

What are pipe and tap methods in Angular tutorial?

You are right, the documentation lacks of those methods. However when I dug into rxjs repository, I found nice comments about tap (too long to paste here) and pipe operators:

   * Used to stitch together functional operators into a chain.
   * @method pipe
   * @return {Observable} the Observable result of all of the operators having
   * been called in the order they were passed in.
   * @example
   * import { map, filter, scan } from 'rxjs/operators';
   * Rx.Observable.interval(1000)
   *   .pipe(
   *     filter(x => x % 2 === 0),
   *     map(x => x + x),
   *     scan((acc, x) => acc + x)
   *   )
   *   .subscribe(x => console.log(x))

In brief:

Pipe: Used to stitch together functional operators into a chain. Before we could just do observable.filter().map().scan(), but since every RxJS operator is a standalone function rather than an Observable's method, we need pipe() to make a chain of those operators (see example above).

Tap: Can perform side effects with observed data but does not modify the stream in any way. Formerly called do(). You can think of it as if observable was an array over time, then tap() would be an equivalent to Array.forEach().

How to get package name from anywhere?

You can get your package name like so:

$ /path/to/adb shell 'pm list packages -f myapp'

Here are the options:

$ adb
Android Debug Bridge version 1.0.32
Revision 09a0d98bebce-android

 -a                            - directs adb to listen on all interfaces for a connection
 -d                            - directs command to the only connected USB device
                                 returns an error if more than one USB device is present.
 -e                            - directs command to the only running emulator.
                                 returns an error if more than one emulator is running.
 -s <specific device>          - directs command to the device or emulator with the given
                                 serial number or qualifier. Overrides ANDROID_SERIAL
                                 environment variable.
 -p <product name or path>     - simple product name like 'sooner', or
                                 a relative/absolute path to a product
                                 out directory like 'out/target/product/sooner'.
                                 If -p is not specified, the ANDROID_PRODUCT_OUT
                                 environment variable is used, which must
                                 be an absolute path.
 -H                            - Name of adb server host (default: localhost)
 -P                            - Port of adb server (default: 5037)
 devices [-l]                  - list all connected devices
                                 ('-l' will also list device qualifiers)
 connect <host>[:<port>]       - connect to a device via TCP/IP
                                 Port 5555 is used by default if no port number is specified.
 disconnect [<host>[:<port>]]  - disconnect from a TCP/IP device.
                                 Port 5555 is used by default if no port number is specified.
                                 Using this command with no additional arguments
                                 will disconnect from all connected TCP/IP devices.

device commands:
  adb push [-p] <local> <remote>
                               - copy file/dir to device
                                 ('-p' to display the transfer progress)
  adb pull [-p] [-a] <remote> [<local>]
                               - copy file/dir from device
                                 ('-p' to display the transfer progress)
                                 ('-a' means copy timestamp and mode)
  adb sync [ <directory> ]     - copy host->device only if changed
                                 (-l means list but don't copy)
  adb shell                    - run remote shell interactively
  adb shell <command>          - run remote shell command
  adb emu <command>            - run emulator console command
  adb logcat [ <filter-spec> ] - View device log
  adb forward --list           - list all forward socket connections.
                                 the format is a list of lines with the following format:
                                    <serial> " " <local> " " <remote> "\n"
  adb forward <local> <remote> - forward socket connections
                                 forward specs are one of:
                                   localabstract:<unix domain socket name>
                                   localreserved:<unix domain socket name>
                                   localfilesystem:<unix domain socket name>
                                   dev:<character device name>
                                   jdwp:<process pid> (remote only)
  adb forward --no-rebind <local> <remote>
                               - same as 'adb forward <local> <remote>' but fails
                                 if <local> is already forwarded
  adb forward --remove <local> - remove a specific forward socket connection
  adb forward --remove-all     - remove all forward socket connections
  adb reverse --list           - list all reverse socket connections from device
  adb reverse <remote> <local> - reverse socket connections
                                 reverse specs are one of:
                                   localabstract:<unix domain socket name>
                                   localreserved:<unix domain socket name>
                                   localfilesystem:<unix domain socket name>
  adb reverse --norebind <remote> <local>
                               - same as 'adb reverse <remote> <local>' but fails
                                 if <remote> is already reversed.
  adb reverse --remove <remote>
                               - remove a specific reversed socket connection
  adb reverse --remove-all     - remove all reversed socket connections from device
  adb jdwp                     - list PIDs of processes hosting a JDWP transport
  adb install [-lrtsdg] <file>
                               - push this package file to the device and install it
                                 (-l: forward lock application)
                                 (-r: replace existing application)
                                 (-t: allow test packages)
                                 (-s: install application on sdcard)
                                 (-d: allow version code downgrade)
                                 (-g: grant all runtime permissions)
  adb install-multiple [-lrtsdpg] <file...>
                               - push this package file to the device and install it
                                 (-l: forward lock application)
                                 (-r: replace existing application)
                                 (-t: allow test packages)
                                 (-s: install application on sdcard)
                                 (-d: allow version code downgrade)
                                 (-p: partial application install)
                                 (-g: grant all runtime permissions)
  adb uninstall [-k] <package> - remove this app package from the device
                                 ('-k' means keep the data and cache directories)
  adb bugreport                - return all information from the device
                                 that should be included in a bug report.

  adb backup [-f <file>] [-apk|-noapk] [-obb|-noobb] [-shared|-noshared] [-all] [-system|-nosystem] [<packages...>]
                               - write an archive of the device's data to <file>.
                                 If no -f option is supplied then the data is written
                                 to "backup.ab" in the current directory.
                                 (-apk|-noapk enable/disable backup of the .apks themselves
                                    in the archive; the default is noapk.)
                                 (-obb|-noobb enable/disable backup of any installed apk expansion
                                    (aka .obb) files associated with each application; the default
                                    is noobb.)
                                 (-shared|-noshared enable/disable backup of the device's
                                    shared storage / SD card contents; the default is noshared.)
                                 (-all means to back up all installed applications)
                                 (-system|-nosystem toggles whether -all automatically includes
                                    system applications; the default is to include system apps)
                                 (<packages...> is the list of applications to be backed up.  If
                                    the -all or -shared flags are passed, then the package
                                    list is optional.  Applications explicitly given on the
                                    command line will be included even if -nosystem would
                                    ordinarily cause them to be omitted.)

  adb restore <file>           - restore device contents from the <file> backup archive

  adb disable-verity           - disable dm-verity checking on USERDEBUG builds
  adb enable-verity            - re-enable dm-verity checking on USERDEBUG builds
  adb keygen <file>            - generate adb public/private key. The private key is stored in <file>,
                                 and the public key is stored in <file>.pub. Any existing files
                                 are overwritten.
  adb help                     - show this help message
  adb version                  - show version num

  adb wait-for-device          - block until device is online
  adb start-server             - ensure that there is a server running
  adb kill-server              - kill the server if it is running
  adb get-state                - prints: offline | bootloader | device
  adb get-serialno             - prints: <serial-number>
  adb get-devpath              - prints: <device-path>
  adb remount                  - remounts the /system, /vendor (if present) and /oem (if present) partitions on the device read-write
  adb reboot [bootloader|recovery]
                               - reboots the device, optionally into the bootloader or recovery program.
  adb reboot sideload          - reboots the device into the sideload mode in recovery program (adb root required).
  adb reboot sideload-auto-reboot
                               - reboots into the sideload mode, then reboots automatically after the sideload regardless of the result.
  adb sideload <file>          - sideloads the given package
  adb root                     - restarts the adbd daemon with root permissions
  adb unroot                   - restarts the adbd daemon without root permissions
  adb usb                      - restarts the adbd daemon listening on USB
  adb tcpip <port>             - restarts the adbd daemon listening on TCP on the specified port

  adb ppp <tty> [parameters]   - Run PPP over USB.
 Note: you should not automatically start a PPP connection.
 <tty> refers to the tty for PPP stream. Eg. dev:/dev/omap_csmi_tty1
 [parameters] - Eg. defaultroute debug dump local notty usepeerdns

adb sync notes: adb sync [ <directory> ]
  <localdir> can be interpreted in several ways:

  - If <directory> is not specified, /system, /vendor (if present), /oem (if present) and /data partitions will be updated.

  - If it is "system", "vendor", "oem" or "data", only the corresponding partition
    is updated.

environment variables:
  ADB_TRACE                    - Print debug information. A comma separated list of the following values
                                 1 or all, adb, sockets, packets, rwx, usb, sync, sysdeps, transport, jdwp
  ANDROID_SERIAL               - The serial number to connect to. -s takes priority over this if given.
  ANDROID_LOG_TAGS             - When used with the logcat option, only these debug tags are printed.

Angular2 @Input to a property with get/set

@Paul Cavacas, I had the same issue and I solved by setting the Input() decorator above the getter.

  get in(): any {
    return this._allowDays;

  // not working
  set in(val) {
    console.log('allowDays = '+val);
    this._allowDays = val;

See this plunker:

How to get CSS to select ID that begins with a string (not in Javascript)?

I'd do it like this:

[id^="product"] {

Ideally, use a class. This is what classes are for:

<div id="product176" class="product"></div>
<div id="product177" class="product"></div>
<div id="product178" class="product"></div>

And now the selector becomes:

.product {

Gaussian fit for Python

sigma = sum(y*(x - mean)**2)

should be

sigma = np.sqrt(sum(y*(x - mean)**2))

Import numpy on pycharm

I added Anaconda3/Library/Bin to the environment path and PyCharm no longer complained with the error.

Stated by

How to prevent Screen Capture in Android

To disable Screen Capture:

Add following line of code in onCreate() method:


To enable Screen Capture:

Find for LayoutParams.FLAG_SECURE and remove the line of code.

How do I concatenate two text files in PowerShell?

Simply use the Get-Content and Set-Content cmdlets:

Get-Content inputFile1.txt, inputFile2.txt | Set-Content joinedFile.txt

You can concatenate more than two files with this style, too.

If the source files are named similarly, you can use wildcards:

Get-Content inputFile*.txt | Set-Content joinedFile.txt

Note 1: PowerShell 5 and older versions allowed this to be done more concisely using the aliases cat and sc for Get-Content and Set-Content respectively. However, these aliases are problematic because cat is a system command in *nix systems, and sc is a system command in Windows systems - therefore using them is not recommended, and in fact sc is no longer even defined as of PowerShell Core (v7). The PowerShell team recommends against using aliases in general.

Note 2: Be careful with wildcards - if you try to output to examples.txt (or similar that matches the pattern), PowerShell will get into an infinite loop! (I just tested this.)

Note 3: Outputting to a file with > does not preserve character encoding! This is why using Set-Content is recommended.

jQuery Set Selected Option Using Next


Android Fastboot devices not returning device

I had the same issue, but I was running Ubuntu 12.04 through a VM. I am using a Nexus 10. I had added the usb device as a filter for the VM (using virtual box in the virtual machine's settings).

The device I had added was "samsung Nexus 10".

The problem is that once the device is in fastboot mode, it shows up as a different device: "Google, Inc Android 1.0." So doing "lsusb" in the VM showed no device connected, and obviously "fastboot devices" returned nothing until I added the "second" device as a filter for the VM as well.

Hope this helps someone.

How can I stop "property does not exist on type JQuery" syntax errors when using Typescript?

I think this is the most readable solution:

($("div.printArea") as any).printArea();

React Native Change Default iOS Simulator Device

You can also use npm for this by adding an entry to the scripts element of your package.json file. E.g.

"launch-ios": "react-native run-ios --simulator \"iPad Air 2\""

Then to use this: npm run launch-ios

java.lang.NoClassDefFoundError: Could not initialize class XXX

I had the same exception - but only while running in debug mode, this is how I solved the problem (after 3 whole days): in the build.gradle i had : "multiDexEnabled true" set in the defaultConfig section.

        defaultConfig {
    applicationId ""
    minSdkVersion 15
    targetSdkVersion 28
    versionCode 5123
    versionName "5123"
    // Enabling multidex support.
    multiDexEnabled true

but apparently this wasn't enough. but when i changed:

public class MyAppClass  extends Application 


public class MyAppClass  extends MultiDexApplication 

this solved it. hope this will help someone

Spring MVC How take the parameter value of a GET HTTP Request in my controller method?

As explained in the documentation, by using an @RequestParam annotation:

public @ResponseBody String byParameter(@RequestParam("foo") String foo) {
    return "Mapped by path + method + presence of query parameter! (MappingController) - foo = "
           + foo;

How to troubleshoot an "AttributeError: __exit__" in multiproccesing in Python?

The problem is in this line:

with pattern.findall(row) as f:

You are using the with statement. It requires an object with __enter__ and __exit__ methods. But pattern.findall returns a list, with tries to store the __exit__ method, but it can't find it, and raises an error. Just use

f = pattern.findall(row)


How to delete mysql database through shell command

In general, you can pass any query to mysql from shell with -e option.

mysql -u username -p -D dbname -e "DROP DATABASE dbname"

http to https through .htaccess

Try the following:

 RewriteEngine On
 RewriteCond %{HTTPS} !=on
 RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R,L]

Also, you can also redirect based on port number, for example:

 RewriteCond %{SERVER_PORT} ^80$
 RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]

This will redirect all requests received on port 80 to HTTPS.

Implements vs extends: When to use? What's the difference?

A class can only "implement" an interface. A class only "extends" a class. Likewise, an interface can extend another interface.

A class can only extend one other class. A class can implement several interfaces.

If instead you are more interested in knowing when to use abstract classes and interfaces, refer to this thread: Interface vs Abstract Class (general OO)

Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource

Its a CORS issue, your api cannot be accessed directly from remote or different origin, In order to allow other ip address or other origins from accessing you api, you should add the 'Access-Control-Allow-Origin' on the api's header, you can set its value to '*' if you want it to be accessible to all, or you can set specific domain or ips like '' or 'http://192. ip address ';

Include this on your api's header, it may vary depending on how you are displaying json data,

if your using ajax, to retrieve and display data your header would look like this,

   url: '',
   headers: {  'Access-Control-Allow-Origin': 'http://The web site allowed to access' },
   data: data,
   type: 'dataType',
   /* etc */
   success: function(jsondata){


Change URL parameters

my function support removing param

function updateURLParameter(url, param, paramVal, remove = false) {
        var newAdditionalURL = '';
        var tempArray = url.split('?');
        var baseURL = tempArray[0];
        var additionalURL = tempArray[1];
        var rows_txt = '';

        if (additionalURL)
            newAdditionalURL = decodeURI(additionalURL) + '&';

        if (remove)
            newAdditionalURL = newAdditionalURL.replace(param + '=' + paramVal, '');
            rows_txt = param + '=' + paramVal;

        window.history.replaceState('', '', (baseURL + "?" + newAdditionalURL + rows_txt).replace('?&', '?').replace('&&', '&').replace(/\&$/, ''));

Trying to get property of non-object in

<?php foreach ($sidemenus->mname as $sidemenu): ?>
<?php echo $sidemenu ."<br />";?>


$sidemenus = mysql_fetch_array($results);


<?php echo $sidemenu['mname']."<br />";?>

Disable and enable buttons in C#

button2.Enabled == true ;

should be

button2.Enabled = true ;

Redirect all output to file in Bash

All POSIX operating systems have 3 streams: stdin, stdout, and stderr. stdin is the input, which can accept the stdout or stderr. stdout is the primary output, which is redirected with >, >>, or |. stderr is the error output, which is handled separately so that any exceptions do not get passed to a command or written to a file that it might break; normally, this is sent to a log of some kind, or dumped directly, even when the stdout is redirected. To redirect both to the same place, use:

command &> /some/file

EDIT: thanks to Zack for pointing out that the above solution is not portable--use instead:

*command* > file 2>&1 

If you want to silence the error, do:

*command* 2> /dev/null

Dictionary of dictionaries in Python?

dictionary's setdefault is a good way to update an existing dict entry if it's there, or create a new one if it's not all in one go:

Looping style:

# This is our sample data
data = [("Milter", "Miller", 4), ("Milter", "Miler", 4), ("Milter", "Malter", 2)]

# dictionary we want for the result
dictionary = {}

# loop that makes it work
for realName, falseName, position in data:
    dictionary.setdefault(realName, {})[falseName] = position

dictionary now equals:

{'Milter': {'Malter': 2, 'Miler': 4, 'Miller': 4}}

How to simulate browsing from various locations?

DNS info is cached at many places. If you have a server in Europe you may want to try to proxy through it


Just note to anyone trying the REGEXP to use "LIKE IN" functionality.

IN allows you to do:

field IN (

In REGEXP this won't work


It has to be in one line like this:

REGEXP 'val1$|val2$|val3$'

jQuery Date Picker - disable past dates

I have created function to disable previous date, disable flexible weekend days (Like Saturday, Sunday)

We are using beforeShowDay method of jQuery UI datepicker plugin.

<script src=""></script>_x000D_
var NotBeforeToday = function(date) {_x000D_
  var now = new Date(); //this gets the current date and time_x000D_
  if (date.getFullYear() == now.getFullYear() && date.getMonth() == now.getMonth() && date.getDate() >= now.getDate() && (date.getDay() > 0 && date.getDay() < 6) )_x000D_
   return [true,""];_x000D_
  if (date.getFullYear() >= now.getFullYear() && date.getMonth() > now.getMonth() && (date.getDay() > 0 && date.getDay() < 6))_x000D_
   return [true,""];_x000D_
  if (date.getFullYear() > now.getFullYear() && (date.getDay() > 0 && date.getDay() < 6))_x000D_
   return [true,""];_x000D_
  return [false,""];_x000D_
  beforeShowDay: NotBeforeToday_x000D_

enter image description here

Here today's date is 15th Sept. I have disabled Saturday and Sunday.

Sublime Text 2 Code Formatting

I can't speak for the 2nd or 3rd, but if you install Node first, Sublime-HTMLPrettify works pretty well. You have to setup your own key shortcut once it is installed. One thing I noticed on Windows, you may need to edit your path for Node in the %PATH% variable if it is already long (I think the limit is 1024 for the %PATH% variable, and anything after that is ignored.)

There is a Windows bug, but in the issues there is a fix for it. You'll need to edit the file -

Best way to test for a variable's existence in PHP; isset() is clearly broken

I don't agree with your reasoning about NULL, and saying that you need to change your mindset about NULL is just weird.

I think isset() was not designed correctly, isset() should tell you if the variable has been set and it should not be concerned with the actual value of the variable.

What if you are checking values returned from a database and one of the columns have a NULL value, you still want to know if it exists even if the value is NULL...nope dont trust isset() here.


$a = array ('test' => 1, 'hello' => NULL);

var_dump(isset($a['test']));   // TRUE
var_dump(isset($a['foo']));    // FALSE
var_dump(isset($a['hello']));  // FALSE

isset() should have been designed to work like this:

if(isset($var) && $var===NULL){....

this way we leave it up to the programmer to check types and not leave it up to isset() to assume its not there because the value is NULL - its just stupid design

smooth scroll to top

Came up with this solution:

function scrollToTop() {
let currentOffset = window.pageYOffset;
const arr = [];

for (let i = 100; i >= 0; i--) {
    arr.push(new Promise(res => {
            setTimeout(() => {
                    res(currentOffset * (i / 100));
                2 * (100 - i))

arr.reduce((acc, curr, index, arr) => {
    return acc.then((res) => {
        if (typeof res === 'number')
            window.scrollTo(0, res)
        return curr
}, Promise.resolve(currentOffset)).then(() => {
    window.scrollTo(0, 0)

List directory tree structure in python?

Maybe faster than @ellockie ( Maybe )

import os
def file_writer(text):
    with open("folder_structure.txt","a") as f_output:
def list_files(startpath):

    for root, dirs, files in os.walk(startpath):
        level = root.replace(startpath, '').count(os.sep)
        indent = '\t' * 1 * (level)
        output_string = '{}{}/ \n'.format(indent, os.path.basename(root))
        subindent = '\t' * 1 * (level + 1)
        output_string = '%s %s \n' %(subindent,[f for f in files])


Test results in screenshot below:

enter image description here

How to test which port MySQL is running on and whether it can be connected to?

grep port /etc/mysql/my.cnf ( at least in debian/ubuntu works )


netstat -tlpn | grep mysql



in /etc/mysql/my.cnf to see possible restrictions

Target a css class inside another css class

I use div instead of tables and am able to target classes within the main class, as below:


.main {
    .width: 800px;
    .margin: 0 auto;
    .text-align: center;
.main .table {
    width: 80%;
.main .row {
   / ***something ***/
.main .column {
    font-size: 14px;
    display: inline-block;
.main .left {
    width: 140px;
    margin-right: 5px;
    font-size: 12px;
.main .right {
    width: auto;
    margin-right: 20px;
    color: #fff;
    font-size: 13px;
    font-weight: normal;


<div class="main">
    <div class="table">
        <div class="row">
            <div class="column left">Swing Over Bed</div>
            <div class="column right">650mm</div>
            <div class="column left">Swing In Gap</div>
            <div class="column right">800mm</div>

If you want to style a particular "cell" exclusively you can use another sub-class or the id of the div e.g:

.main #red { color: red; }

<div class="main">
    <div class="table">
        <div class="row">
            <div id="red" class="column left">Swing Over Bed</div>
            <div class="column right">650mm</div>
            <div class="column left">Swing In Gap</div>
            <div class="column right">800mm</div>

Best data type to store money values in MySQL

Indeed this relies on the programmer's preferences. I personally use: numeric(15,4) to conform to the Generally Accepted Accounting Principles (GAAP).

Async always WaitingForActivation

The reason is your result assigned to the returning Task which represents continuation of your method, and you have a different Task in your method which is running, if you directly assign Task like this you will get your expected results:

var task = Task.Run(() =>
            for (int i = 10; i < 432543543; i++)
                // just for a long job
                double d3 = Math.Sqrt((Math.Pow(i, 5) - Math.Pow(i, 2)) / Math.Sin(i * 8));
           return "Foo Completed.";


        while (task.Status != TaskStatus.RanToCompletion)
            Console.WriteLine("Thread ID: {0}, Status: {1}", Thread.CurrentThread.ManagedThreadId,task.Status);


        Console.WriteLine("Result: {0}", task.Result);

The output:

enter image description here

Consider this for better explanation: You have a Foo method,let's say it Task A, and you have a Task in it,let's say it Task B, Now the running task, is Task B, your Task A awaiting for Task B result.And you assing your result variable to your returning Task which is Task A, because Task B doesn't return a Task, it returns a string. Consider this:

If you define your result like this:

Task result = Foo(5);

You won't get any error.But if you define it like this:

string result = Foo(5);

You will get:

Cannot implicitly convert type 'System.Threading.Tasks.Task' to 'string'

But if you add an await keyword:

string result = await Foo(5);

Again you won't get any error.Because it will wait the result (string) and assign it to your result variable.So for the last thing consider this, if you add two task into your Foo Method:

private static async Task<string> Foo(int seconds)
    await Task.Run(() =>
            for (int i = 0; i < seconds; i++)
                Console.WriteLine("Thread ID: {0}, second {1}.", Thread.CurrentThread.ManagedThreadId, i);

            // in here don't return anything

   return await Task.Run(() =>
            for (int i = 0; i < seconds; i++)
                Console.WriteLine("Thread ID: {0}, second {1}.", Thread.CurrentThread.ManagedThreadId, i);

            return "Foo Completed.";

And if you run the application, you will get the same results.(WaitingForActivation) Because now, your Task A is waiting those two tasks.

Generating a drop down list of timezones with PHP

After trying all solutions presented here and not being satisfied, I have found a script which is matching my needs and it is more user friendly. For the record, I will save it as a possible solution. I love the copy/paste solutions :)

Script returns a select with whatever timezone you want preselected.

enter image description here


 * returns a HTML formated TimeZone select
 * PHP 5 >= 5.2.0
 * @param $selectedTimeZone string The timezone marked as "selected"
 * @return string
function displayTimeZoneSelect($selectedTimeZone = 'America/New_York'){
    $countryCodes = getCountryCodes();
    $return = null;
    foreach ($countryCodes as $country => $countryCode) {
        $timezone_identifiers = DateTimeZone::listIdentifiers(DateTimeZone::PER_COUNTRY,$countryCode);
        foreach( $timezone_identifiers as $value ){
            /* getTimeZoneOffset returns minutes and we need to display hours */
            $offset = getTimeZoneOffset($value)/60;
            /* for the GMT+1 GMT-1 display */
            $offset = ( substr($offset,0,1) == "-" ? " (GMT" : " (GMT+" ) . $offset . ")";
            /* America/New_York -> America/New York */
            $displayValue = (str_replace('_',' ',$value));
            /* Find the city */
            $ex = explode("/",$displayValue);
            $city = ( ($ex[2]) ? $ex[2] : $ex[1] );
            /* For the special names */
            $displayValue = htmlentities($country." - ".$city.$offset); 
            /* handle the $selectedTimeZone in the select form */
            $selected = ( ($value == $selectedTimeZone) ? ' selected="selected"' : null );
            $return .= '<option value="' . $value . '"' . $selected . '>'
                . $displayValue
                . '</option>' . PHP_EOL;

    return $return;

 * ISO 3166 code list
 * @return array The country codes in 'COUNTRY' => 'CODE' format
 * @link ISO Website
function getCountryCodes(){
$return = array(
return $return;

 * Calculates the offset from UTC for a given timezone
 * @return integer
function getTimeZoneOffset($timeZone) {
    $dateTimeZoneUTC = new DateTimeZone("UTC");
    $dateTimeZoneCurrent = new DateTimeZone($timeZone);

    $dateTimeUTC = new DateTime("now",$dateTimeZoneUTC);
    $dateTimeCurrent = new DateTime("now",$dateTimeZoneCurrent);

    $offset = (($dateTimeZoneCurrent->getOffset($dateTimeUTC))/60);
    return $offset;

    <label for="timeZone">Timezone<br />
        <select id="timeZone" name="timeZone">
            <?php echo displayTimeZoneSelect("America/Toronto");?>

How to match "any character" in regular expression?

There are lots of sophisticated regex testing and development tools, but if you just want a simple test harness in Java, here's one for you to play with:

    String[] tests = {
    for (String test : tests) {
        System.out.println(test + " " +test.matches(".+123"));

Now you can easily add new testcases and try new patterns. Have fun exploring regex.

See also

Best implementation for hashCode method for a collection, you said

if equals() returns true for two objects, then hashCode() should return the same value. If equals() returns false, then hashCode() should return different values

I cannot agree with you. If two objects have the same hashcode it doesn't have to mean that they are equal.

If A equals B then A.hashcode must be equal to B.hascode


if A.hashcode equals B.hascode it does not mean that A must equals B

How to only get file name with Linux 'find'?

Use -execdir which automatically holds the current file in {}, for example:

find . -type f -execdir echo '{}' ';'

You can also use $PWD instead of . (on some systems it won't produce an extra dot in the front).

If you still got an extra dot, alternatively you can run:

find . -type f -execdir basename '{}' ';'

-execdir utility [argument ...] ;

The -execdir primary is identical to the -exec primary with the exception that utility will be executed from the directory that holds the current file.

When used + instead of ;, then {} is replaced with as many pathnames as possible for each invocation of utility. In other words, it'll print all filenames in one line.

fileReader.readAsBinaryString to upload files

The best way in browsers that support it, is to send the file as a Blob, or using FormData if you want a multipart form. You do not need a FileReader for that. This is both simpler and more efficient than trying to read the data.

If you specifically want to send it as multipart/form-data, you can use a FormData object:

var xmlHttpRequest = new XMLHttpRequest();"POST", '/pushfile', true);
var formData = new FormData();
// This should automatically set the file name and type.
formData.append("file", file);
// Sending FormData automatically sets the Content-Type header to multipart/form-data

You can also send the data directly, instead of using multipart/form-data. See the documentation. Of course, this will need a server-side change as well.

// file is an instance of File, e.g. from a file input.
var xmlHttpRequest = new XMLHttpRequest();"POST", '/pushfile', true);

xmlHttpRequest.setRequestHeader("Content-Type", file.type);

// Send the binary data.
// Since a File is a Blob, we can send it directly.

For browser support, see: (most browsers, including IE 10+).

Can I set an opacity only to the background image of a div?

I implemented Marcus Ekwall's solution but was able to remove a few things to make it simpler and it still works. Maybe 2017 version of html/css?


<div id="content">
  <div id='bg'></div>
  <h2>What is Lorem Ipsum?</h2>
  <p><strong>Lorem Ipsum</strong> is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen
    book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with
    desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>


#content {
  text-align: left;
  width: 75%;
  margin: auto;
  position: relative;

#bg {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: url('') center center;
  opacity: .4;
  width: 100%;
  height: 100%;

maven-dependency-plugin (goals "copy-dependencies", "unpack") is not supported by m2e

This is a problem of M2E for Eclipse M2E plugin execution not covered.

To solve this problem, all you got to do is to map the lifecycle it doesn't recognize and instruct M2E to execute it.

You should add this after your plugins, inside the build. This will remove the error and make M2E recognize the goal copy-depencies of maven-dependency-plugin and make the POM work as expected, copying dependencies to folder every time Eclipse build it. If you just want to ignore the error, then you change <execute /> for <ignore />. No need for enclosing your maven-dependency-plugin into pluginManagement, as suggested before.

                <execute />

Android Stop Emulator from Command Line

Sometimes the command

adb -s emulator-5554 emu kill

did not work on my CI servers or desktops, for unknown reason. I think on Windows it's OK to kill the process of qemu, just like

Taskkill /IM qemu-system-x86_64.exe /F /T

Set angular scope variable in markup

$scope.$watch('myVar', function (newValue, oldValue) {
        if (typeof (newValue) !== 'undefined') {
            $scope.someothervar= newValue;
//or get some data

    }, true);

Variable initializes after controller so you need to watch over it and when it't initialized the use it.

Keeping it simple and how to do multiple CTE in a query

You can have multiple CTEs in one query, as well as reuse a CTE:

WITH    cte1 AS
        SELECT  1 AS id
        cte2 AS
        SELECT  2 AS id
FROM    cte1
FROM    cte2
FROM    cte1

Note, however, that SQL Server may reevaluate the CTE each time it is accessed, so if you are using values like RAND(), NEWID() etc., they may change between the CTE calls.

Force hide address bar in Chrome on Android

Check this has everything you need

The Chrome team has recently implemented a feature that tells the browser to launch the page fullscreen when the user has added it to the home screen. It is similar to the iOS Safari model.

<meta name="mobile-web-app-capable" content="yes">

How to attach source or JavaDoc in eclipse for any jar file e.g. JavaFX?

You can configure the Javadocs with downloading jar, basically javadocs will be referred directly from internet.

Complete steps:

  1. Open the Build Path page of the project (right click, properties, Java build path).
  2. Open the Libraries tab.
  3. Expand the node of the library in question (JavaFX).
  4. Select JavaDoc location and click edit.
  5. Enter the location to the file which contains the Javadoc. Specifically for the javaFX javadoc enter

for offline javadocs, you can download from :

After clicking Accept License Agreement you can download

How to horizontally align ul to center of div?

Following is a list of solutions to centering things in CSS horizontally. The snippet includes all of them.

html {_x000D_
  font: 1.25em/1.5 Georgia, Times, serif;_x000D_
pre {_x000D_
  color: #fff;_x000D_
  background-color: #333;_x000D_
  padding: 10px;_x000D_
blockquote {_x000D_
  max-width: 400px;_x000D_
  background-color: #e0f0d1;_x000D_
blockquote > p {_x000D_
  font-style: italic;_x000D_
blockquote > p:first-of-type::before {_x000D_
  content: open-quote;_x000D_
blockquote > p:last-of-type::after {_x000D_
  content: close-quote;_x000D_
blockquote > footer::before {_x000D_
  content: "\2014";_x000D_
blockquote {_x000D_
  position: relative;_x000D_
  padding: 20px;_x000D_
.container {_x000D_
  background-color: tomato;_x000D_
blockquote::after {_x000D_
  position: absolute;_x000D_
  right: 0;_x000D_
  bottom: 0;_x000D_
  padding: 2px 10px;_x000D_
  border: 1px dotted #000;_x000D_
  background-color: #fff;_x000D_
.container::after {_x000D_
  content: ".container-" attr(data-num);_x000D_
  z-index: 1;_x000D_
blockquote::after {_x000D_
  content: ".quote-" attr(data-num);_x000D_
  z-index: 2;_x000D_
.container-4 {_x000D_
  margin-bottom: 200px;_x000D_
 * Solution 1_x000D_
.quote-1 {_x000D_
  max-width: 400px;_x000D_
  margin-right: auto;_x000D_
  margin-left: auto;_x000D_
 * Solution 2_x000D_
.container-2 {_x000D_
  text-align: center;_x000D_
.quote-2 {_x000D_
  display: inline-block;_x000D_
  text-align: left;_x000D_
 * Solution 3_x000D_
.quote-3 {_x000D_
  display: table;_x000D_
  margin-right: auto;_x000D_
  margin-left: auto;_x000D_
 * Solution 4_x000D_
.container-4 {_x000D_
  position: relative;_x000D_
.quote-4 {_x000D_
  position: absolute;_x000D_
  left: 50%;_x000D_
  transform: translateX(-50%);_x000D_
 * Solution 5_x000D_
.container-5 {_x000D_
  display: flex;_x000D_
  justify-content: center;_x000D_
  <h1>CSS: Horizontal Centering</h1>_x000D_
  <h2>Uncentered Example</h2>_x000D_
  <p>This is the scenario: We have a container with an element inside of it that we want to center. I just added a little padding and background colors so both elements are distinquishable.</p>_x000D_
  <div class="container  container-0" data-num="0">_x000D_
    <blockquote class="quote-0" data-num="0">_x000D_
      <p>My friend Data. You see things with the wonder of a child. And that makes you more human than any of us.</p>_x000D_
      <footer>Tasha Yar about Data</footer>_x000D_
  <h2>Solution 1: Using <code>max-width</code> & <code>margin</code> (IE7)</h2>_x000D_
  <p>This method is widely used. The upside here is that only the element which one wants to center needs rules.</p>_x000D_
<pre><code>.quote-1 {_x000D_
  max-width: 400px;_x000D_
  margin-right: auto;_x000D_
  margin-left: auto;_x000D_
  <div class="container  container-1" data-num="1">_x000D_
    <blockquote class="quote  quote-1" data-num="1">_x000D_
      <p>My friend Data. You see things with the wonder of a child. And that makes you more human than any of us.</p>_x000D_
      <footer>Tasha Yar about Data</footer>_x000D_
  <h2>Solution 2: Using <code>display: inline-block</code> and <code>text-align</code> (IE8)</h2>_x000D_
  <p>This method utilizes that <code>inline-block</code> elements are treated as text and as such they are affected by the <code>text-align</code> property. This does not rely on a fixed width which is an upside. This is helpful for when you don’t know the number of elements in a container for example.</p>_x000D_
<pre><code>.container-2 {_x000D_
  text-align: center;_x000D_
.quote-2 {_x000D_
  display: inline-block;_x000D_
  text-align: left;_x000D_
  <div class="container  container-2" data-num="2">_x000D_
    <blockquote class="quote  quote-2" data-num="2">_x000D_
      <p>My friend Data. You see things with the wonder of a child. And that makes you more human than any of us.</p>_x000D_
      <footer>Tasha Yar about Data</footer>_x000D_
  <h2>Solution 3: Using <code>display: table</code> and <code>margin</code> (IE8)</h2>_x000D_
  <p>Very similar to the second solution but only requires to apply rules on the element that is to be centered.</p>_x000D_
<pre><code>.quote-3 {_x000D_
  display: table;_x000D_
  margin-right: auto;_x000D_
  margin-left: auto;_x000D_
  <div class="container  container-3" data-num="3">_x000D_
    <blockquote class="quote  quote-3" data-num="3">_x000D_
      <p>My friend Data. You see things with the wonder of a child. And that makes you more human than any of us.</p>_x000D_
      <footer>Tasha Yar about Data</footer>_x000D_
  <h2>Solution 4: Using <code>translate()</code> and <code>position</code> (IE9)</h2>_x000D_
  <p>Don’t use as a general approach for horizontal centering elements. The downside here is that the centered element will be removed from the document flow. Notice the container shrinking to zero height with only the padding keeping it visible. This is what <i>removing an element from the document flow</i> means.</p>_x000D_
  <p>There are however applications for this technique. For example, it works for <b>vertically</b> centering by using <code>top</code> or <code>bottom</code> together with <code>translateY()</code>.</p>_x000D_
<pre><code>.container-4 {_x000D_
    position: relative;_x000D_
.quote-4 {_x000D_
  position: absolute;_x000D_
  left: 50%;_x000D_
  transform: translateX(-50%);_x000D_
  <div class="container  container-4" data-num="4">_x000D_
    <blockquote class="quote  quote-4" data-num="4">_x000D_
      <p>My friend Data. You see things with the wonder of a child. And that makes you more human than any of us.</p>_x000D_
      <footer>Tasha Yar about Data</footer>_x000D_
  <h2>Solution 5: Using Flexible Box Layout Module (IE10+ with vendor prefix)</h2>_x000D_
<pre><code>.container-5 {_x000D_
  display: flex;_x000D_
  justify-content: center;_x000D_
  <div class="container  container-5" data-num="5">_x000D_
    <blockquote class="quote  quote-5" data-num="5">_x000D_
      <p>My friend Data. You see things with the wonder of a child. And that makes you more human than any of us.</p>_x000D_
      <footer>Tasha Yar about Data</footer>_x000D_

display: flex

.container {
  display: flex;
  justify-content: center;


max-width & margin

You can horizontally center a block-level element by assigning a fixed width and setting margin-right and margin-left to auto.

.container ul {
  /* for IE below version 7 use `width` instead of `max-width` */
  max-width: 800px;
  margin-right: auto;
  margin-left: auto;


  • No container needed
  • Requires (maximum) width of the centered element to be known

IE9+: transform: translatex(-50%) & left: 50%

This is similar to the quirky centering method which uses absolute positioning and negative margins.

.container {
  position: relative;

.container ul {
  position: absolute;
  left: 50%;
  transform: translatex(-50%);


  • The centered element will be removed from document flow. All elements will completely ignore of the centered element.
  • This technique allows vertical centering by using top instead of left and translateY() instead of translateX(). The two can even be combined.
  • Browser support: transform2d

IE8+: display: table & margin

Just like the first solution, you use auto values for right and left margins, but don’t assign a width. If you don’t need to support IE7 and below, this is better suited, although it feels kind of hacky to use the table property value for display.

.container ul {
  display: table;
  margin-right: auto;
  margin-left: auto;

IE8+: display: inline-block & text-align

Centering an element just like you would do with regular text is possible as well. Downside: You need to assign values to both a container and the element itself.

.container {
  text-align: center;

.container ul {
  display: inline-block;

  /* One most likely needs to realign flow content */
  text-align: initial;


  • Does not require to specify a (maximum) width
  • Aligns flow content to the center (potentially unwanted side effect)
  • Works kind of well with a dynamic number of menu items (i.e. in cases where you can’t know the width a single item will take up)

How can I pass parameters to a partial view in mvc 4

For Asp.Net core you better use

<partial name="_MyPartialView" model="MyModel" />

So for example

@foreach (var item in Model)
   <partial name="_MyItemView" model="item" />

Java Pass Method as Parameter

Use the Observer pattern (sometimes also called Listener pattern):

interface ComponentDelegate {
    void doSomething(Component component);

public void setAllComponents(Component[] myComponentArray, ComponentDelegate delegate) {
    // ...

setAllComponents(this.getComponents(), new ComponentDelegate() {
                                            void doSomething(Component component) {
                                                changeColor(component); // or do directly what you want

new ComponentDelegate()... declares an anonymous type implementing the interface.

How to automatically convert strongly typed enum into int?

A C++14 version of the answer provided by R. Martinho Fernandes would be:

#include <type_traits>

template <typename E>
constexpr auto to_underlying(E e) noexcept
    return static_cast<std::underlying_type_t<E>>(e);

As with the previous answer, this will work with any kind of enum and underlying type. I have added the noexcept keyword as it will never throw an exception.

This also appears in Effective Modern C++ by Scott Meyers. See item 10 (it is detailed in the final pages of the item within my copy of the book).

What is the difference between dict.items() and dict.iteritems() in Python2?

In Py2.x

The commands dict.items(), dict.keys() and dict.values() return a copy of the dictionary's list of (k, v) pair, keys and values. This could take a lot of memory if the copied list is very large.

The commands dict.iteritems(), dict.iterkeys() and dict.itervalues() return an iterator over the dictionary’s (k, v) pair, keys and values.

The commands dict.viewitems(), dict.viewkeys() and dict.viewvalues() return the view objects, which can reflect the dictionary's changes. (I.e. if you del an item or add a (k,v) pair in the dictionary, the view object can automatically change at the same time.)

$ python2.7

>>> d = {'one':1, 'two':2}
>>> type(d.items())
<type 'list'>
>>> type(d.keys())
<type 'list'>
>>> type(d.iteritems())
<type 'dictionary-itemiterator'>
>>> type(d.iterkeys())
<type 'dictionary-keyiterator'>
>>> type(d.viewitems())
<type 'dict_items'>
>>> type(d.viewkeys())
<type 'dict_keys'>

While in Py3.x

In Py3.x, things are more clean, since there are only dict.items(), dict.keys() and dict.values() available, which return the view objects just as dict.viewitems() in Py2.x did.


Just as @lvc noted, view object isn't the same as iterator, so if you want to return an iterator in Py3.x, you could use iter(dictview) :

$ python3.3

>>> d = {'one':'1', 'two':'2'}
>>> type(d.items())
<class 'dict_items'>
>>> type(d.keys())
<class 'dict_keys'>
>>> ii = iter(d.items())
>>> type(ii)
<class 'dict_itemiterator'>
>>> ik = iter(d.keys())
>>> type(ik)
<class 'dict_keyiterator'>

How to convert HTML to PDF using iTextSharp

I use the following code to create PDF

protected void CreatePDF(Stream stream)
            using (var document = new Document(PageSize.A4, 40, 40, 40, 30))
                var writer = PdfWriter.GetInstance(document, stream);
                writer.PageEvent = new ITextEvents();

                // instantiate custom tag processor and add to `HtmlPipelineContext`.
                var tagProcessorFactory = Tags.GetHtmlTagProcessorFactory();
                    new TableProcessor(),
                    new string[] { HTML.Tag.TABLE }

                //Register Fonts.
                XMLWorkerFontProvider fontProvider = new XMLWorkerFontProvider(XMLWorkerFontProvider.DONTLOOKFORFONTS);
                fontProvider.Register(HttpContext.Current.Server.MapPath("~/Content/Fonts/GothamRounded-Medium.ttf"), "Gotham Rounded Medium");
                CssAppliers cssAppliers = new CssAppliersImpl(fontProvider);

                var htmlPipelineContext = new HtmlPipelineContext(cssAppliers);

                var pdfWriterPipeline = new PdfWriterPipeline(document, writer);
                var htmlPipeline = new HtmlPipeline(htmlPipelineContext, pdfWriterPipeline);

                // get an ICssResolver and add the custom CSS
                var cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(true);
                cssResolver.AddCss(CSSSource, "utf-8", true);
                var cssResolverPipeline = new CssResolverPipeline(
                    cssResolver, htmlPipeline

                var worker = new XMLWorker(cssResolverPipeline, true);
                var parser = new XMLParser(worker);
                using (var stringReader = new StringReader(HTMLSource))
                    HttpContext.Current.Response.ContentType = "application /pdf";
                    if (base.View)
                        HttpContext.Current.Response.AddHeader("content-disposition", "inline;filename=\"" + OutputFileName + ".pdf\"");
                        HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=\"" + OutputFileName + ".pdf\"");

No process is on the other end of the pipe (SQL Server 2012)

Had this error too, the cause was simple, but not obvious: incorrect password. Not sure why I didn't get just "Login failed" from freshly installed SQL 2016 server.

Can't access object property, even though it shows up in a console log

Check if inside the object there's an array of objects. I had a similar issue with a JSON:

    "terms": {
        "category": [
                "ID": 4,
                "name": "Cirugia",
                "slug": "cirugia",
                "description": "",
                "taxonomy": "category",
                "parent": null,
                "count": 68,
                "link": ""

I tried to access the 'name' key from 'category' and I got the undefined error, because I was using:

var_name =

Then I realised it has got square brackets, that means that it has an array of objects inside the category key, because it can have more than one category object. So, in order to get the 'name' key I used this:

var_name = obj_array.terms.category[0].name

And That does the trick.

Maybe it's too late for this answer, but I hope someone with the same problem will find this as I did before finding the Solution :)

Best way to write to the console in PowerShell

Default behaviour of PowerShell is just to dump everything that falls out of a pipeline without being picked up by another pipeline element or being assigned to a variable (or redirected) into Out-Host. What Out-Host does is obviously host-dependent.

Just letting things fall out of the pipeline is not a substitute for Write-Host which exists for the sole reason of outputting text in the host application.

If you want output, then use the Write-* cmdlets. If you want return values from a function, then just dump the objects there without any cmdlet.

ASP.NET MVC3 - textarea with @Html.EditorFor

@Html.TextAreaFor(model => model.Text)

cast a List to a Collection

Not knowing your code, it's a bit hard to answer your question, but based on all the info here, I believe the issue is you're trying to use Collections.sort passing in an object defined as Collection, and sort doesn't support that.

First question. Why is client defined so generically? Why isn't it a List, Map, Set or something a little more specific?

If client was defined as a List, Map or Set, you wouldn't have this issue, as then you'd be able to directly use Collections.sort(client).


LaTeX package for syntax highlighting of code in various languages

You can use the listings package. It supports many different languages and there are lots of options for customising the output.



Loop through Map in Groovy?

Quite simple with a closure:

def map = [

map.each{ k, v -> println "${k}:${v}" }

System.IO.IOException: file used by another process

I realize that I is kinda late, but still better late than never. I was having similar problem recently. I used XMLWriter to subsequently update XML file and was receiving the same errors. I found the clean solution for this:

The XMLWriter uses underlying FileStream to access the modified file. Problem is that when you call XMLWriter.Close() method, the underlying stream doesn't get closed and is locking the file. What you need to do is to instantiate your XMLWriter with settings and specify that you need that underlying stream closed.


XMLWriterSettings settings = new Settings();
settings.CloseOutput = true;
XMLWriter writer = new XMLWriter(filepath, settings);

Hope it helps.

Excel: Searching for multiple terms in a cell

Another way


Also, if you keep a list of values in, say A1 to A3, then you can use


The wildcards are not necessary at all in the Search() function, since Search() returns the position of the found string.

Git : fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists


git config --global credential.helper cache

This command prevents git to ask username and password, not forever but with a default limit to 15 minutes.

git config --global credential.helper 'cache --timeout=3600'

This moves the default limit to 1 hour.

How do I make a redirect in PHP?

function Redirect($url, $permanent = false)
    if (headers_sent() === false)
        header('Location: ' . $url, true, ($permanent === true) ? 301 : 302);


Redirect('', false);

Don't forget to die()/exit()!

How to upload (FTP) files to server in a bash script?

if you want to use it inside a 'for' to copy the last generated files for a every-day bacakup...

var="`find /backup/path/ -name 'something*' -type f -mtime -1`"  
#we have in $var some files with last day change date

for i in $var  
  j=$(( $j + 1 ))  
  dirname="`dirname $i`"  
  filename="`basename $i`"  
  /usr/bin/ftp -in >> /tmp/ftp.good 2>> /tmp/ftp.bad << EOF  
    open 123.456.789.012  
    user user_name passwd  
    lcd $dirname  
    put $filename  
  EOF      #end of ftp  
done       #end of for iteration

How to make grep only match if the entire line matches?

Simply specify the regexp anchors.

grep '^ABB\.log$' a.tmp

How do I print the content of httprequest request?

In case someone also want to dump response like me. i avoided to dump response body. following code just dump the StatusCode and Headers.

static private String dumpResponse(HttpServletResponse resp){
    StringBuilder sb = new StringBuilder();

    sb.append("Response Status = [" + resp.getStatus() + "], ");
    String headers = resp.getHeaderNames().stream()
                    .map(headerName -> headerName + " : " + resp.getHeaders(headerName) )
                    .collect(Collectors.joining(", "));

    if (headers.isEmpty()) {
        sb.append("Response headers: NONE,");
    } else {
        sb.append("Response headers: "+headers+",");

    return sb.toString();

Get current URL/URI without some of $_GET variables

Try to use this variant:

<?php echo Yii::app()->createAbsoluteUrl('your_yii_application/?lg=pl', array('id'=>$model->id));?>

It is the easiest way, I guess.

Where is Xcode's build folder?

By default Build location is in Derived Data.

Please note: a path to a product can be changed if you delete DerivedData during development process and rebuild it again.

Xcode -> Preferences... -> Locations 

You can change the location of Build location. It will have an effect on the whole workspace

File -> Project/Workspace Settings... -> Advanced 

You can change the location of Target using:

Project editor -> select a target -> Build Settings -> Per-configuration Build Products Path


It makes sense if you want to create an autonomic Build location

Xcode 10.2.1

Rename Pandas DataFrame Index

The currently selected answer does not mention the rename_axis method which can be used to rename the index and column levels.

Pandas has some quirkiness when it comes to renaming the levels of the index. There is also a new DataFrame method rename_axis available to change the index level names.

Let's take a look at a DataFrame

df = pd.DataFrame({'age':[30, 2, 12],
                       'color':['blue', 'green', 'red'],
                       'food':['Steak', 'Lamb', 'Mango'],
                       'height':[165, 70, 120],
                       'score':[4.6, 8.3, 9.0],
                       'state':['NY', 'TX', 'FL']},
                       index = ['Jane', 'Nick', 'Aaron'])

enter image description here

This DataFrame has one level for each of the row and column indexes. Both the row and column index have no name. Let's change the row index level name to 'names'.


enter image description here

The rename_axis method also has the ability to change the column level names by changing the axis parameter:

df.rename_axis('names').rename_axis('attributes', axis='columns')

enter image description here

If you set the index with some of the columns, then the column name will become the new index level name. Let's append to index levels to our original DataFrame:

df1 = df.set_index(['state', 'color'], append=True)

enter image description here

Notice how the original index has no name. We can still use rename_axis but need to pass it a list the same length as the number of index levels.

df1.rename_axis(['names', None, 'Colors'])

enter image description here

You can use None to effectively delete the index level names.

Series work similarly but with some differences

Let's create a Series with three index levels

s = df.set_index(['state', 'color'], append=True)['food']

       state  color
Jane   NY     blue     Steak
Nick   TX     green     Lamb
Aaron  FL     red      Mango
Name: food, dtype: object

We can use rename_axis similarly to how we did with DataFrames


Names  States  Colors
Jane   NY      blue      Steak
Nick   TX      green      Lamb
Aaron  FL      red       Mango
Name: food, dtype: object

Notice that the there is an extra piece of metadata below the Series called Name. When creating a Series from a DataFrame, this attribute is set to the column name.

We can pass a string name to the rename method to change it


       state  color
Jane   NY     blue     Steak
Nick   TX     green     Lamb
Aaron  FL     red      Mango
Name: FOOOOOD, dtype: object

DataFrames do not have this attribute and infact will raise an exception if used like this

df.rename('my dataframe')
TypeError: 'str' object is not callable

Prior to pandas 0.21, you could have used rename_axis to rename the values in the index and columns. It has been deprecated so don't do this

Why doesn't JavaScript support multithreading?

As far as I have heared Google Chrome will have multithreaded javascript, so it is a "current implementations" problem.

Determine a user's timezone

The most popular (==standard?) way of determining the time zone I've seen around is simply asking the users themselves. If your website requires subscription, this could be saved in the users' profile data. For anon users, the dates could be displayed as UTC or GMT or some such.

I'm not trying to be a smart aleck. It's just that sometimes some problems have finer solutions outside of any programming context.

Position one element relative to another in CSS

I would suggest using absolute positioning within the element.

I've created this to help you visualize it a bit.

#parent {_x000D_
    border:2px solid blue;_x000D_
#div1 {position:absolute;bottom:0;right:0;background:green;width:100px;height:100px;}_x000D_
#div2 {width:100px;height:100px;position:absolute;bottom:0;left:0;background:red;}_x000D_
#div3 {width:100px;height:100px;position:absolute;top:0;right:0;background:yellow;}_x000D_
#div4 {width:100px;height:100px;position:absolute;top:0;left:0;background:gray;}
<div id="parent">_x000D_
<div id="div1"></div>_x000D_
<div id="div2"></div>_x000D_
<div id="div3"></div>_x000D_
<div id="div4"></div>_x000D_

Printing the value of a variable in SQL Developer

Go to the DBMS Output window (View->DBMS Output).

@Value annotation type casting to Integer from String

If you want to convert a property to an integer from properties file there are 2 solutions which I found:

Given scenario: contains = 100 as a field and you want to access it in spring configuration file as integer.The property customerId is declared as type int in the Bean Customer

Solution 1:

<property name="customerId" value="#{T(java.lang.Integer).parseInt('${}')}" />

In the above line, the string value from properties file is converted to int type.

solution 2: Use some other extension inplace of propeties.For Ex.- If your properties file name is then make it customer.details and in the configuration file use the below code

<property name="customerId"   value="${}" />

Understanding the main method of python

In Python, execution does NOT have to begin at main. The first line of "executable code" is executed first.

def main():
    print("main code")

def meth1():

if __name__ == "__main__":main() ## with if

Output -

main code

More on main() -

A module's __name__

Every module has a name and statements in a module can find out the name of its module. This is especially handy in one particular situation - As mentioned previously, when a module is imported for the first time, the main block in that module is run. What if we want to run the block only if the program was used by itself and not when it was imported from another module? This can be achieved using the name attribute of the module.

Using a module's __name__

# Filename:

if __name__ == '__main__':
    print 'This program is being run by itself'
    print 'I am being imported from another module'

Output -

$ python
This program is being run by itself
$ python
>>> import using_name
I am being imported from another module

How It Works -

Every Python module has it's __name__ defined and if this is __main__, it implies that the module is being run standalone by the user and we can do corresponding appropriate actions.

How to scroll table's "tbody" independent of "thead"?

I saw this post about a month ago when I was having similar problems. I needed y-axis scrolling for a table inside of a ui dialog (yes, you heard me right). I was lucky, in that a working solution presented itself fairly quickly. However, it wasn't long before the solution took on a life of its own, but more on that later.

The problem with just setting the top level elements (thead, tfoot, and tbody) to display block, is that browser synchronization of the column sizes between the various components is quickly lost and everything packs to the smallest permissible size. Setting the widths of the columns seems like the best course of action, but without setting the widths of all the internal table components to match the total of these columns, even with a fixed table layout, there is a slight divergence between the headers and body when a scroll bar is present.

The solution for me was to set all the widths, check if a scroll bar was present, and then take the scaled widths the browser had actually decided on, and copy those to the header and footer adjusting the last column width for the size of the scroll bar. Doing this provides some fluidity to the column widths. If changes to the table's width occur, most major browsers will auto-scale the tbody column widths accordingly. All that's left is to set the header and footer column widths from their respective tbody sizes.

$table.find("> thead,> tfoot").find("> tr:first-child")
    .each(function(i,e) {
        $(e).children().each(function(i,e) {
            if (i != column_scaled_widths.length - 1) {
                $(e).width(column_scaled_widths[i] - ($(e).outerWidth() - $(e).width()));
            } else {
                $(e).width(column_scaled_widths[i] - ($(e).outerWidth() - $(e).width()) + $.position.scrollbarWidth());

This fiddle illustrates these notions:

Note that a table wrapper or additional tables are not needed for y-axis scrolling alone. (X-axis scrolling does require a wrapping table.) Synchronization between the column sizes for the body and header will still be lost if the minimum pack size for either the header or body columns is encountered. A mechanism for minimum widths should be provided if resizing is an option or small table widths are expected.

The ultimate culmination from this starting point is fully realized here:


How to get the latest file in a folder?

Whatever is assigned to the files variable is incorrect. Use the following code.

import glob
import os

list_of_files = glob.glob('/path/to/folder/*') # * means all if need specific format then *.csv
latest_file = max(list_of_files, key=os.path.getctime)

Enabling CORS in Cloud Functions for Firebase

From so much searching, I could find this solution in the same firebase documentation, just implement the cors in the path:

import * as express from "express";
import * as cors from "cors";

const api = express();
api.use(cors({ origin: true }));
api.get("/url", function);

Link firebase doc:

How do you load custom UITableViewCells from Xib files?

If you're using Interface Builder to make cells, check that you've set the Identifier in the Inspector. Then check that it's the same when calling dequeueReusableCellWithIdentifier.

I accidentally forgot to set some identifiers in a table-heavy project, and the performance change was like night and day.

Convert ArrayList to String array in Android

try this

List<String> list = new ArrayList<String>();

String[] listArr = new String[list.size()];
listArr = list.toArray(listArr );

for(String s : listArr )

LINQ's Distinct() on a particular property

The following code is functionally equivalent to Jon Skeet's answer.

Tested on .NET 4.5, should work on any earlier version of LINQ.

public static IEnumerable<TSource> DistinctBy<TSource, TKey>(
  this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
  HashSet<TKey> seenKeys = new HashSet<TKey>();
  return source.Where(element => seenKeys.Add(keySelector(element)));

Incidentially, check out Jon Skeet's latest version of DistinctBy.cs on Google Code.

What is null in Java?

The null keyword is a literal that represents a null reference, one that does not refer to any object. null is the default value of reference-type variables.

Also maybe have a look at

null : Java Glossary

Proper MIME type for OTF fonts

One way to silence this warning from Chrome would be to update Chrome and then make sure your mime type is one of these:


This list is per the patch found at Bug 111418 at

The same patch demotes the message from a "Warning" to a "Log", so just upgrading Chrome to any post March-2013 version would get rid of the yellow triangle.

Since the question is about silencing a Chrome warning, and folks might be holding on to old Chrome versions for whatever reasons, I figured this was worth adding.

How to make a variadic macro (variable number of arguments)

#define DEBUG

#ifdef DEBUG
  #define PRINT print
  #define PRINT(...) ((void)0) //strip out PRINT instructions from code

void print(const char *fmt, ...) {

    va_list args;
    va_start(args, fmt);
    vsprintf(str, fmt, args);

        printf("%s\n", str);


int main() {
   PRINT("[%s %d, %d] Hello World", "March", 26, 2009);
   return 0;

If the compiler does not understand variadic macros, you can also strip out PRINT with either of the following:

#define PRINT //


#define PRINT if(0)print

The first comments out the PRINT instructions, the second prevents PRINT instruction because of a NULL if condition. If optimization is set, the compiler should strip out never executed instructions like: if(0) print("hello world"); or ((void)0);

How to add image background to btn-default twitter-bootstrap button?

Instead of using input type button you can use button and insert the image inside the button content.

<button class="btn btn-default">
     <img src="" width="20" /> Sign In with Facebook

The problem with doing this only with CSS is that you cannot set linear-gradient to the background you must use solid color.

.sign-in-facebook {
    background: url('') #f2f2f2;
    background-position: -9px -7px;
    background-repeat: no-repeat;
    background-size: 39px 43px;
    padding-left: 41px;
    color: #000;
  .sign-in-facebook:hover {
    background: url('') #e0e0e0;
    background-position: -9px -7px;
    background-repeat: no-repeat;
    background-size: 39px 43px;
    padding-left: 41px;
    color: #000;

body {_x000D_
  padding: 30px;_x000D_
<!-- Latest compiled and minified CSS -->_x000D_
<link rel="stylesheet" href="">_x000D_
<!-- Optional theme -->_x000D_
<link rel="stylesheet" href="">_x000D_
<!-- Latest compiled and minified JavaScript -->_x000D_
<script src=""></script>_x000D_
<style type="text/css">_x000D_
  .sign-in-facebook {_x000D_
    background: url('') #f2f2f2;_x000D_
    background-position: -9px -7px;_x000D_
    background-repeat: no-repeat;_x000D_
    background-size: 39px 43px;_x000D_
    padding-left: 41px;_x000D_
    color: #000;_x000D_
  .sign-in-facebook:hover {_x000D_
    background: url('') #e0e0e0;_x000D_
    background-position: -9px -7px;_x000D_
    background-repeat: no-repeat;_x000D_
    background-size: 39px 43px;_x000D_
    padding-left: 41px;_x000D_
    color: #000;_x000D_
<h4>Only with CSS</h4>_x000D_
<input type="button" value="Sign In with Facebook" class="btn btn-default sign-in-facebook" style="margin-top:2px; margin-bottom:2px;">_x000D_
<h4>Only with HTML</h4>_x000D_
<button class="btn btn-default">_x000D_
  <img src="" width="20" /> Sign In with Facebook_x000D_

Add CSS class to a div in code behind

What if:

 <asp:Button ID="Button1" runat="server" CssClass="test1 test3 test-test" />

To add or remove a class, instead of overwriting all classes with

   BtnventCss.CssClass = "hom_but_a"

keep the HTML correct:

    string classname = "TestClass";

    // Add a class
    BtnventCss.CssClass = String.Join(" ", Button1
               .Split(' ')
               .Except(new string[]{"",classname})
               .Concat(new string[]{classname})

     // Remove a class
     BtnventCss.CssClass = String.Join(" ", Button1
               .Split(' ')
               .Except(new string[]{"",classname})

This assures

  • The original classnames remain.
  • There are no double classnames
  • There are no disturbing extra spaces

Especially when client-side development is using several classnames on one element.

In your example, use

   string classname = "TestClass";

    // Add a class
    Button1.Attributes.Add("class", String.Join(" ", Button1
               .Split(' ')
               .Except(new string[]{"",classname})
               .Concat(new string[]{classname})

     // Remove a class
     Button1.Attributes.Add("class", String.Join(" ", Button1
               .Split(' ')
               .Except(new string[]{"",classname})

You should wrap this in a method/property ;)

git checkout tag, git pull fails in branch

You need to set up your tracking (upstream) for the current branch

git branch --set-upstream master origin/master

Is already deprecated instead of that you can use --track flag

git branch --track master origin/master

I also like the doc reference that @casey notice:

-u <upstream>
  Set up <branchname>'s tracking information so <upstream> is considered  
  <branchname>'s upstream branch. If no <branchname> is specified,  
  then it defaults to the current branch.

push() a two-dimensional array

You have some errors in your code:

  1. Use myArray[i].push( 0 ); to add a new column. Your code (myArray[i][j].push(0);) would work in a 3-dimensional array as it tries to add another element to an array at position [i][j].
  2. You only expand (col-d)-many columns in all rows, even in those, which haven't been initialized yet and thus have no entries so far.

One correct, although kind of verbose version, would be the following:

var r = 3; //start from rows 3

var rows = 8;
var cols = 7;

// expand to have the correct amount or rows
for( var i=r; i<rows; i++ ) {
  myArray.push( [] );

// expand all rows to have the correct amount of cols
for (var i = 0; i < rows; i++)
    for (var j =  myArray[i].length; j < cols; j++)

Is it ok to run docker from inside docker?

Yes, we can run docker in docker, we'll need to attach the unix sockeet "/var/run/docker.sock" on which the docker daemon listens by default as volume to the parent docker using "-v /var/run/docker.sock:/var/run/docker.sock". Sometimes, permissions issues may arise for docker daemon socket for which you can write "sudo chmod 757 /var/run/docker.sock".

And also it would require to run the docker in privileged mode, so the commands would be:

sudo chmod 757 /var/run/docker.sock

docker run --privileged=true -v /var/run/docker.sock:/var/run/docker.sock -it ...

How do I select child elements of any depth using XPath?

If you are using the XmlDocument and XmlNode.


XmlNode f = root.SelectSingleNode("//form[@id='myform']");


XmlNode s = f.SelectSingleNode(".//input[@type='submit']");

It depends on the tool that you use. But .// will select any child, any depth from a reference node.

grep from tar.gz without extracting [faster one]

If you have zgrep you can use

zgrep -a string file.tar.gz

socket.error: [Errno 48] Address already in use

By the way, to prevent this from happening in the first place, simply press Ctrl+C in terminal while SimpleHTTPServer is still running normally. This will "properly" stop the server and release the port so you don't have to find and kill the process again before restarting the server.

(Mods: I did try to put this comment on the best answer where it belongs, but I don't have enough reputation.)

Batch command to move files to a new directory

Something like this might help:

SET Today=%Date:~10,4%%Date:~4,2%%Date:~7,2%
mkdir C:\Test\Backup-%Today%
move C:\Test\Log\*.* C:\Test\Backup-%Today%\
SET Today=

The important part is the first line. It takes the output of the internal DATE value and parses it into an environmental variable named Today, in the format CCYYMMDD, as in '20110407`.

The %Date:~10,4% says to extract a *substring of the Date environmental variable 'Thu 04/07/2011' (built in - type echo %Date% at a command prompt) starting at position 10 for 4 characters (2011). It then concatenates another substring of Date: starting at position 4 for 2 chars (04), and then concats two additional characters starting at position 7 (07).

*The substring value starting points are 0-based.

You may need to adjust these values depending on the date format in your locale, but this should give you a starting point.

In Java, what is the best way to determine the size of an object?

There isn't a method call, if that's what you're asking for. With a little research, I suppose you could write your own. A particular instance has a fixed sized derived from the number of references and primitive values plus instance bookkeeping data. You would simply walk the object graph. The less varied the row types, the easier.

If that's too slow or just more trouble than it's worth, there's always good old-fashioned row counting rule-of-thumbs.

Get String in YYYYMMDD format from JS date object?

It seems that mootools provides Date().format():

I'm not sure if it worth including just for this particular task though.

"Unable to get the VLookup property of the WorksheetFunction Class" error

I was having the same problem. It seems that passing Me.ComboBox1.Value as an argument for the Vlookup function is causing the issue. What I did was assign this value to a double and then put it into the Vlookup function.

Dim x As Double
x = Me.ComboBox1.Value
Me.TextBox1.Value = Application.WorksheetFunction.VLookup(x, Worksheets("Sheet3").Range("Names"), 2, False) 

Or, for a shorter method, you can just convert the type within the Vlookup function using Cdbl(<Value>).

So it would end up being

Me.TextBox1.Value = Application.WorksheetFunction.VLookup(Cdbl(Me.ComboBox1.Value), Worksheets("Sheet3").Range("Names"), 2, False) 

Strange as it may sound, it works for me.

Hope this helps.

Border around each cell in a range

For adding borders try this, for example:

Range("C11").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("A15:D15").Borders(xlEdgeBottom).LineStyle = xlContinuous

Hope that syntax is correct because I've done this in C#.

@import vs #import - iOS 7

Nice answer you can find in book Learning Cocoa with Objective-C (ISBN: 978-1-491-90139-7)

Modules are a new means of including and linking files and libraries into your projects. To understand how modules work and what benefits they have, it is important to look back into the history of Objective-C and the #import statement Whenever you want to include a file for use, you will generally have some code that looks like this:

#import "someFile.h"

Or in the case of frameworks:

#import <SomeLibrary/SomeFile.h>

Because Objective-C is a superset of the C programming language, the #import state- ment is a minor refinement upon C’s #include statement. The #include statement is very simple; it copies everything it finds in the included file into your code during compilation. This can sometimes cause significant problems. For example, imagine you have two header files: SomeFileA.h and SomeFileB.h; SomeFileA.h includes SomeFileB.h, and SomeFileB.h includes SomeFileA.h. This creates a loop, and can confuse the coimpiler. To deal with this, C programmers have to write guards against this type of event from occurring.

When using #import, you don’t need to worry about this issue or write header guards to avoid it. However, #import is still just a glorified copy-and-paste action, causing slow compilation time among a host of other smaller but still very dangerous issues (such as an included file overriding something you have declared elsewhere in your own code.)

Modules are an attempt to get around this. They are no longer a copy-and-paste into source code, but a serialised representation of the included files that can be imported into your source code only when and where they’re needed. By using modules, code will generally compile faster, and be safer than using either #include or #import.

Returning to the previous example of importing a framework:

#import <SomeLibrary/SomeFile.h>

To import this library as a module, the code would be changed to:

@import SomeLibrary;

This has the added bonus of Xcode linking the SomeLibrary framework into the project automatically. Modules also allow you to only include the components you really need into your project. For example, if you want to use the AwesomeObject component in the AwesomeLibrary framework, normally you would have to import everything just to use the one piece. However, using modules, you can just import the specific object you want to use:

@import AwesomeLibrary.AwesomeObject;

For all new projects made in Xcode 5, modules are enabled by default. If you want to use modules in older projects (and you really should) they will have to be enabled in the project’s build settings. Once you do that, you can use both #import and @import statements in your code together without any concern.

How to plot a function curve in R

Here is a lattice version:

eq<-function(x) {x*x}

Lattice output

What is the time complexity of indexing, inserting and removing from common data structures?

Information on this topic is now available on Wikipedia at: Search data structure

|                      |  Insert  |   Delete   |  Search  | Space Usage  |
| Unsorted array       | O(1)     | O(1)       | O(n)     | O(n)         |
| Value-indexed array  | O(1)     | O(1)       | O(1)     | O(n)         |
| Sorted array         | O(n)     | O(n)       | O(log n) | O(n)         |
| Unsorted linked list | O(1)*    | O(1)*      | O(n)     | O(n)         |
| Sorted linked list   | O(n)*    | O(1)*      | O(n)     | O(n)         |
| Balanced binary tree | O(log n) | O(log n)   | O(log n) | O(n)         |
| Heap                 | O(log n) | O(log n)** | O(n)     | O(n)         |
| Hash table           | O(1)     | O(1)       | O(1)     | O(n)         |

 * The cost to add or delete an element into a known location in the list 
   (i.e. if you have an iterator to the location) is O(1). If you don't 
   know the location, then you need to traverse the list to the location
   of deletion/insertion, which takes O(n) time. 

** The deletion cost is O(log n) for the minimum or maximum, O(n) for an
   arbitrary element.

Should have subtitle controller already set Mediaplayer error Android

Also you can only set mediaPlayer.reset() and in onDestroy set it to release.

Ignore Duplicates and Create New List of Unique Values in Excel

On a sorted column, you can also try this idea:


B3 can be pasted down. It will result 0, after the last unique match. If this is unwanted, put some IF statement around to exclude this.


Easier than an IF statement, at least for text-values:


How to remove special characters from a string?

To Remove Special character

String t2 = "!@#$%^&*()-';,./?><+abdd";

t2 = t2.replaceAll("\\W+","");

Output will be : abdd.

This works perfectly.

How to get day of the month?

You'll want to do get a Calendar instance and get it's day of month

Calendar cal = Calendar.getInstance();
int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);

String dayOfMonthStr = String.valueOf(dayOfMonth);


Current time formatting with Javascript

You can use my port of strftime:

/* Port of strftime(). Compatibility notes:
 * %c - formatted string is slightly different
 * %D - not implemented (use "%m/%d/%y" or "%d/%m/%y")
 * %e - space is not added
 * %E - not implemented
 * %h - not implemented (use "%b")
 * %k - space is not added
 * %n - not implemented (use "\n")
 * %O - not implemented
 * %r - not implemented (use "%I:%M:%S %p")
 * %R - not implemented (use "%H:%M")
 * %t - not implemented (use "\t")
 * %T - not implemented (use "%H:%M:%S")
 * %U - not implemented
 * %W - not implemented
 * %+ - not implemented
 * %% - not implemented (use "%")
 * strftime() reference:
 * Day of year (%j) code based on Joe Orost's answer:
 * Week number (%V) code based on Taco van den Broek's prototype:
function strftime(sFormat, date) {
  if (!(date instanceof Date)) date = new Date();
  var nDay = date.getDay(),
    nDate = date.getDate(),
    nMonth = date.getMonth(),
    nYear = date.getFullYear(),
    nHour = date.getHours(),
    aDays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
    aMonths = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
    aDayCount = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334],
    isLeapYear = function() {
      if ((nYear&3)!==0) return false;
      return nYear%100!==0 || nYear%400===0;
    getThursday = function() {
      var target = new Date(date);
      target.setDate(nDate - ((nDay+6)%7) + 3);
      return target;
    zeroPad = function(nNum, nPad) {
      return ('' + (Math.pow(10, nPad) + nNum)).slice(1);
  return sFormat.replace(/%[a-z]/gi, function(sMatch) {
    return {
      '%a': aDays[nDay].slice(0,3),
      '%A': aDays[nDay],
      '%b': aMonths[nMonth].slice(0,3),
      '%B': aMonths[nMonth],
      '%c': date.toUTCString(),
      '%C': Math.floor(nYear/100),
      '%d': zeroPad(nDate, 2),
      '%e': nDate,
      '%F': date.toISOString().slice(0,10),
      '%G': getThursday().getFullYear(),
      '%g': ('' + getThursday().getFullYear()).slice(2),
      '%H': zeroPad(nHour, 2),
      '%I': zeroPad((nHour+11)%12 + 1, 2),
      '%j': zeroPad(aDayCount[nMonth] + nDate + ((nMonth>1 && isLeapYear()) ? 1 : 0), 3),
      '%k': '' + nHour,
      '%l': (nHour+11)%12 + 1,
      '%m': zeroPad(nMonth + 1, 2),
      '%M': zeroPad(date.getMinutes(), 2),
      '%p': (nHour<12) ? 'AM' : 'PM',
      '%P': (nHour<12) ? 'am' : 'pm',
      '%s': Math.round(date.getTime()/1000),
      '%S': zeroPad(date.getSeconds(), 2),
      '%u': nDay || 7,
      '%V': (function() {
              var target = getThursday(),
                n1stThu = target.valueOf();
              target.setMonth(0, 1);
              var nJan1 = target.getDay();
              if (nJan1!==4) target.setMonth(0, 1 + ((4-nJan1)+7)%7);
              return zeroPad(1 + Math.ceil((n1stThu-target)/604800000), 2);
      '%w': '' + nDay,
      '%x': date.toLocaleDateString(),
      '%X': date.toLocaleTimeString(),
      '%y': ('' + nYear).slice(2),
      '%Y': nYear,
      '%z': date.toTimeString().replace(/.+GMT([+-]\d+).+/, '$1'),
      '%Z': date.toTimeString().replace(/.+\((.+?)\)$/, '$1')
    }[sMatch] || sMatch;

Sample usage:

// Returns "Thursday 4:45pm 15 Sep 2016"
strftime('%A %l:%M%P %e %b %Y');

// You can optionally pass it a Date object
// Returns "Friday 2:00pm 1 Feb 2013"
strftime('%A %l:%M%P %e %b %Y', new Date('Feb 1, 2013 2:00 PM'));

The latest code is available here:

Full-screen iframe with a height of 100%

The following tested working

<iframe style="width:100%; height:100%;position:absolute;top:0px;left:0px;right:0px;bottom:0px" src="index.html" frameborder="0" height="100%" width="100%"></iframe>

how to store Image as blob in Sqlite & how to retrieve it?

in the DBAdaper i.e Data Base helper class declare the table like this

 private static final String USERDETAILS=
    "create table userdetails(usersno integer primary key autoincrement,userid text not null ,username text not null,password text not null,photo BLOB,visibility text not null);";

insert the values like this,

first convert the images as byte[]

ByteArrayOutputStream baos = new ByteArrayOutputStream();  
Bitmap bitmap = ((BitmapDrawable)getResources().getDrawable(R.drawable.common)).getBitmap();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);   
byte[] photo = baos.toByteArray(); 
db.insertUserDetails(value1,value2, value3, photo,value2);

in DEAdaper class

 public long insertUserDetails(String uname,String userid, String pass, byte[] photo,String visibility) 
    ContentValues initialValues = new ContentValues();
    initialValues.put("username", uname);
    initialValues.put("password", pass);
    return db.insert("userdetails", null, initialValues);

retrieve the image as follows

Cursor cur=your query;
     byte[] photo=cur.getBlob(index of blob cloumn);

convert the byte[] into image

ByteArrayInputStream imageStream = new ByteArrayInputStream(photo);
Bitmap theImage= BitmapFactory.decodeStream(imageStream);

I think this content may solve your problem

Can I apply a CSS style to an element name?

This is the perfect job for the query selector...

var Set1=document.querySelectorAll('input[type=button]');  // by type

var Set2=document.querySelectorAll('input[name=goButton]'); // by name

var Set3=document.querySelectorAll('input[value=Go]'); // by value

You can then loop through these collections to operate on elements found.

HTML5 and frameborder

How about using the same for technique for "fooling" the validator with Javascript by sticking a target attribute in XHTML <a onclick="'_blank'">?

  • onsomething = " this.frameborder = '0' "

<iframe onload = " this.frameborder='0' " src="menu.html" id="menu"> </iframe>

Or getElementsByTagName]("iframe")1 adding this attribute for all iframes on the page?

Haven't tested this because I've done something which means that nothing is working in IE less than 9! :) So while I'm sorting that out ... :)

Replace missing values with column mean

A relatively simple modification of your code should solve the issue:

for(i in 1:ncol(data)){
  data[[,i]), i] <- mean(data[,i], na.rm = TRUE)

Boolean operators && and ||

The shorter ones are vectorized, meaning they can return a vector, like this:

((-2:2) >= 0) & ((-2:2) <= 0)

The longer form evaluates left to right examining only the first element of each vector, so the above gives

((-2:2) >= 0) && ((-2:2) <= 0)
# [1] FALSE

As the help page says, this makes the longer form "appropriate for programming control-flow and [is] typically preferred in if clauses."

So you want to use the long forms only when you are certain the vectors are length one.

You should be absolutely certain your vectors are only length 1, such as in cases where they are functions that return only length 1 booleans. You want to use the short forms if the vectors are length possibly >1. So if you're not absolutely sure, you should either check first, or use the short form and then use all and any to reduce it to length one for use in control flow statements, like if.

The functions all and any are often used on the result of a vectorized comparison to see if all or any of the comparisons are true, respectively. The results from these functions are sure to be length 1 so they are appropriate for use in if clauses, while the results from the vectorized comparison are not. (Though those results would be appropriate for use in ifelse.

One final difference: the && and || only evaluate as many terms as they need to (which seems to be what is meant by short-circuiting). For example, here's a comparison using an undefined value a; if it didn't short-circuit, as & and | don't, it would give an error.

# Error: object 'a' not found
TRUE || a
# [1] TRUE
FALSE && a
# [1] FALSE
TRUE | a
# Error: object 'a' not found
# Error: object 'a' not found

Finally, see section 8.2.17 in The R Inferno, titled "and and andand".

HTML5 tag for horizontal line break

You can make a div that has the same attributes as the <hr> tag. This way it is fully able to be customized. Here is some sample code:


<h3>This is a header.</h3>
<div class="customHr">.</div>

<p>Here is some sample paragraph text.<br>
This demonstrates what could go below a custom hr.</p>

The CSS:

.customHr {
    width: 95%
    font-size: 1px;
    color: rgba(0, 0, 0, 0);
    line-height: 1px;

    background-color: grey;
    margin-top: -6px;
    margin-bottom: 10px;

To see how the project turns out, here is a JSFiddle for the above code:

How to write UTF-8 in a CSV file

From your shell run:

pip2 install unicodecsv

And (unlike the original question) presuming you're using Python's built in csv module, turn
import csv into
import unicodecsv as csv in your code.

How do I disable text selection with CSS or JavaScript?

 style="-moz-user-select: none; -webkit-user-select: none; -ms-user-select:none; user-select:none;-o-user-select:none;" 
 onselectstart="return false;" 
 onmousedown="return false;">

How to create a DataTable in C# and how to add rows?

You can add Row in a single line

    DataTable table = new DataTable();
    table.Columns.Add("Dosage", typeof(int));
    table.Columns.Add("Drug", typeof(string));
    table.Columns.Add("Patient", typeof(string));
    table.Columns.Add("Date", typeof(DateTime));

    // Here we add five DataRows.
    table.Rows.Add(25, "Indocin", "David", DateTime.Now);
    table.Rows.Add(50, "Enebrel", "Sam", DateTime.Now);
    table.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now);
    table.Rows.Add(21, "Combivent", "Janet", DateTime.Now);
    table.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now);

Scroll to bottom of div with Vue.js

The solution did not work for me but the following code works for me. I am working on dynamic items with class of message-box.

scrollToEnd() {
            setTimeout(() => {
                        this.$el.getElementsByClassName("message-box").length -
            }, 50);

Remember to put the method in mounted() not created() and add class message-box to the dynamic item.

setTimeout() is essential for this to work. You can refer to for more information about this.

Google Geocoding API - REQUEST_DENIED

For anyone struggling with this issue, I just found out that the Geocoding API can't be used with API keys that have referrer restrictions. Just remove all your referrer restrictions and you should be good.

If you're using any other APIs that do allow keys with referrer restrictions (like the Maps JS API), it's probably best to create a 2nd key with no restrictions to use exclusively for geocoding, because other APIs might display your key publicly and someone else could start using it on their own site.

Rotating x axis labels in R for barplot

You can simply pass your data frame into the following function:

rotate_x <- function(data, column_to_plot, labels_vec, rot_angle) {
    plt <- barplot(data[[column_to_plot]], col='steelblue', xaxt="n")
    text(plt, par("usr")[3], labels = labels_vec, srt = rot_angle, adj = c(1.1,1.1), xpd = TRUE, cex=0.6) 


rotate_x(mtcars, 'mpg', row.names(mtcars), 45)

enter image description here

You can change the rotation angle of the labels as needed.

How to download files using axios

For axios POST request, the request should be something like this: The key here is that the responseType and header fields must be in the 3rd parameter of Post. The 2nd parameter is the application parameters.

export const requestDownloadReport = (requestParams) => async dispatch => { 
  let response = null;
  try {
    response = await'createPdf', {
      requestParams: requestParams,
      responseType: 'arraybuffer', // important...because we need to convert it to a blob. If we don't specify this, will be the raw data. It cannot be converted to blob directly.
      headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/pdf'
  catch(err) {
    console.log('[requestDownloadReport][ERROR]', err);
    return err

  return response;

Is it possible to decrypt SHA1

SHA1 is a one way hash. So you can not really revert it.

That's why applications use it to store the hash of the password and not the password itself.

Like every hash function SHA-1 maps a large input set (the keys) to a smaller target set (the hash values). Thus collisions can occur. This means that two values of the input set map to the same hash value.

Obviously the collision probability increases when the target set is getting smaller. But vice versa this also means that the collision probability decreases when the target set is getting larger and SHA-1's target set is 160 bit.

Jeff Preshing, wrote a very good blog about Hash Collision Probabilities that can help you to decide which hash algorithm to use. Thanks Jeff.

In his blog he shows a table that tells us the probability of collisions for a given input set.

Hash Collision Probabilities Table

As you can see the probability of a 32-bit hash is 1 in 2 if you have 77163 input values.

A simple java program will show us what his table shows:

public class Main {

    public static void main(String[] args) {
        char[] inputValue = new char[10];

        Map<Integer, String> hashValues = new HashMap<Integer, String>();

        int collisionCount = 0;

        for (int i = 0; i < 77163; i++) {
            String asString = nextValue(inputValue);
            int hashCode = asString.hashCode();
            String collisionString = hashValues.put(hashCode, asString);
            if (collisionString != null) {
                System.out.println("Collision: " + asString + " <-> " + collisionString);

        System.out.println("Collision count: " + collisionCount);

    private static String nextValue(char[] inputValue) {
        nextValue(inputValue, 0);

        int endIndex = 0;
        for (int i = 0; i < inputValue.length; i++) {
            if (inputValue[i] == 0) {
                endIndex = i;

        return new String(inputValue, 0, endIndex);

    private static void nextValue(char[] inputValue, int index) {
        boolean increaseNextIndex = inputValue[index] == 'z';

        if (inputValue[index] == 0 || increaseNextIndex) {
            inputValue[index] = 'A';
        } else {
            inputValue[index] += 1;

        if (increaseNextIndex) {
            nextValue(inputValue, index + 1);



My output end with:

Collision: RvV <-> SWV
Collision: SvV <-> TWV
Collision: TvV <-> UWV
Collision: UvV <-> VWV
Collision: VvV <-> WWV
Collision: WvV <-> XWV
Collision count: 35135

It produced 35135 collsions and that's the nearly the half of 77163. And if I ran the program with 30084 input values the collision count is 13606. This is not exactly 1 in 10, but it is only a probability and the example program is not perfect, because it only uses the ascii chars between A and z.

Let's take the last reported collision and check


My output is



If you have a SHA-1 value and you want to get the input value back you can try a brute force attack. This means that you have to generate all possible input values, hash them and compare them with the SHA-1 you have. But that will consume a lot of time and computing power. Some people created so called rainbow tables for some input sets. But these do only exist for some small input sets.

And remember that many input values map to a single target hash value. So even if you would know all mappings (which is impossible, because the input set is unbounded) you still can't say which input value it was.

Serializing a list to JSON

If using .Net Core 3.0 or later;

Default to using the built in System.Text.Json parser implementation.


using System.Text.Json;

var json = JsonSerializer.Serialize(aList);

alternatively, other, less mainstream options are available like Utf8Json parser and Jil: These may offer superior performance, if you really need it but, you will need to install their respective packages.

If stuck using .Net Core 2.2 or earlier;

Default to using Newtonsoft JSON.Net as your first choice JSON Parser.


using Newtonsoft.Json;

var json = JsonConvert.SerializeObject(aList);

you may need to install the package first.

PM> Install-Package Newtonsoft.Json

For more details see and upvote the answer that is the source of this information.

For reference only, this was the original answer, many years ago;

// you need to reference System.Web.Extensions

using System.Web.Script.Serialization;

var jsonSerialiser = new JavaScriptSerializer();
var json = jsonSerialiser.Serialize(aList);

Upload file to FTP using C#

This works for me,this method will SFTP a file to a location within your network. It uses SSH.NET.2013.4.7 library.One can just download it for free.

    //Secure FTP
    public void SecureFTPUploadFile(string destinationHost,int port,string username,string password,string source,string destination)

        ConnectionInfo ConnNfo = new ConnectionInfo(destinationHost, port, username, new PasswordAuthenticationMethod(username, password));

        var temp = destination.Split('/');
        string destinationFileName = temp[temp.Count() - 1];
        string parentDirectory = destination.Remove(destination.Length - (destinationFileName.Length + 1), destinationFileName.Length + 1);

        using (var sshclient = new SshClient(ConnNfo))
            using (var cmd = sshclient.CreateCommand("mkdir -p " + parentDirectory + " && chmod +rw " + parentDirectory))

        using (var sftp = new SftpClient(ConnNfo))
            using (var uplfileStream = System.IO.File.OpenRead(source))
                sftp.UploadFile(uplfileStream, destinationFileName, true);

How to check iOS version?

I know this is an old question, but someone should have mentioned the compile-time macros in Availability.h. All of the other methods here are runtime solutions, and will not work in a header file, class category, or ivar definition.

For these situations, use

  // iOS 6+ code here
  // Pre iOS 6 code here

h/t this answer

receiver type *** for instance message is a forward declaration

You are using

States states;

where as you should use

States *states;

Your init method should be like this

-(id)init {
  if( (self = [super init]) ) {
      pickedGlasses = 0;
  return self;

Now finally when you are going to create an object for States class you should do it like this.

State *states = [[States alloc] init];

I am not saying this is the best way of doing this. But it may help you understand the very basic use of initializing objects.

What are the specific differences between .msi and setup.exe file?

.msi files are windows installer files without the windows installer runtime, setup.exe can be any executable programm (probably one that installs stuff on your computer)

Best IDE for HTML5, Javascript, CSS, Jquery support with GUI building tools

My personal experience to build website with html, css en javascript is just to stick with plain text editors with ftp support. I am using Espresso or/and Coda on my mac. But Textmate with Cyberduck(ftp client) is also a great combination, imo. For developing in Windows I recommend notepad++.

PHP isset() with multiple parameters

The parameter(s) to isset() must be a variable reference and not an expression (in your case a concatenation); but you can group multiple conditions together like this:

if (isset($_POST['search_term'], $_POST['postcode'])) {

This will return true only if all arguments to isset() are set and do not contain null.

Note that isset($var) and isset($var) == true have the same effect, so the latter is somewhat redundant.


The second part of your expression uses empty() like this:

empty ($_POST['search_term'] . $_POST['postcode']) == false

This is wrong for the same reasons as above. In fact, you don't need empty() here, because by that time you would have already checked whether the variables are set, so you can shortcut the complete expression like so:

isset($_POST['search_term'], $_POST['postcode']) && 
    $_POST['search_term'] && 

Or using an equivalent expression:

!empty($_POST['search_term']) && !empty($_POST['postcode'])

Final thoughts

You should consider using filter functions to manage the inputs:

$data = filter_input_array(INPUT_POST, array(
    'search_term' => array(
        'filter' => FILTER_UNSAFE_RAW,
        'flags' => FILTER_NULL_ON_FAILURE,
    'postcode' => array(
        'filter' => FILTER_UNSAFE_RAW,
        'flags' => FILTER_NULL_ON_FAILURE,

if ($data === null || in_array(null, $data, true)) {
    // some fields are missing or their values didn't pass the filter
    die("You did something naughty");

// $data['search_term'] and $data['postcode'] contains the fields you want

Btw, you can customize your filters to check for various parts of the submitted values.

Convert date from String to Date format in Dataframes

I solved the same problem without the temp table/view and with dataframe functions.

Of course I found that only one format works with this solution and that's yyyy-MM-DD.

For example:

val df = sc.parallelize(Seq("2016-08-26")).toDF("Id")
val df2 = df.withColumn("Timestamp", (col("Id").cast("timestamp")))
val df3 = df2.withColumn("Date", (col("Id").cast("date")))


 |-- Id: string (nullable = true)
 |-- Timestamp: timestamp (nullable = true)
 |-- Date: date (nullable = true)

|        Id|           Timestamp|      Date|
|2016-08-26|2016-08-26 00:00:...|2016-08-26|

The timestamp of course has 00:00:00.0 as a time value.

Parallel.ForEach vs Task.Factory.StartNew

In my view the most realistic scenario is when tasks have a heavy operation to complete. Shivprasad's approach focuses more on object creation/memory allocation than on computing itself. I made a research calling the following method:

public static double SumRootN(int root)
    double result = 0;
    for (int i = 1; i < 10000000; i++)
            result += Math.Exp(Math.Log(i) / root);
        return result; 

Execution of this method takes about 0.5sec.

I called it 200 times using Parallel:

Parallel.For(0, 200, (int i) =>

Then I called it 200 times using the old-fashioned way:

List<Task> tasks = new List<Task>() ;
for (int i = 0; i < loopCounter; i++)
    Task t = new Task(() => SumRootN(10));


First case completed in 26656ms, the second in 24478ms. I repeated it many times. Everytime the second approach is marginaly faster.

PHP Swift mailer: Failed to authenticate on SMTP using 2 possible authenticators

I really have the same problem, finally, i solved it.

its likey not the Swift Mail's problem. It's Yaml parser's problem. if your password only the digits, the password senmd to swift finally not the same one.

    transport:  smtp
    encryption: ssl
    auth_mode:  login
    username:   your_username
    password:   61548921

you need fix it with double quotes password: "61548921"

Send FormData and String Data Together Through JQuery AJAX?

For Multiple file input : Try this code :

 <form name="form" id="form" method="post" enctype="multipart/form-data">
    <input type="file" name="file[]">
    <input type="file" name="file[]" >
    <input type="text" name="name" id="name">
    <input type="text" name="name1" id="name1">
    <input type="button" name="submit" value="upload" id="upload">

 $('#upload').on('click', function() {
  var fd = new FormData();
    var c=0;
    var file_data;
        file_data = $('input[type="file"]')[c].files; // for multiple files

     for(var i = 0;i<file_data.length;i++){
         fd.append("file_"+c, file_data[i]);
     var other_data = $('form').serializeArray();
         url: 'work.php',
         data: fd,
         contentType: false,
         processData: false,
         type: 'POST',
         success: function(data){

How to write dynamic variable in Ansible playbook

I would first suggest that you step back and look at organizing your plays to not require such complexity, but if you really really do, use the following:

    myvariable: "{{[param1|default(''), param2|default(''), param3|default('')]|join(',')}}"

How can I get the day of a specific date with PHP

$date = strtotime('2016-2-3');
$date = date('l', $date);

(i added format 'l' so it will return full name of day)

Why should I use a pointer rather than the object itself?

Well the main question is Why should I use a pointer rather than the object itself? And my answer, you should (almost) never use pointer instead of object, because C++ has references, it is safer then pointers and guarantees the same performance as pointers.

Another thing you mentioned in your question:

Object *myObject = new Object;

How does it work? It creates pointer of Object type, allocates memory to fit one object and calls default constructor, sounds good, right? But actually it isn't so good, if you dynamically allocated memory (used keyword new), you also have to free memory manually, that means in code you should have:

delete myObject;

This calls destructor and frees memory, looks easy, however in big projects may be difficult to detect if one thread freed memory or not, but for that purpose you can try shared pointers, these slightly decreases performance, but it is much easier to work with them.

And now some introduction is over and go back to question.

You can use pointers instead of objects to get better performance while transferring data between function.

Take a look, you have std::string (it is also object) and it contains really much data, for example big XML, now you need to parse it, but for that you have function void foo(...) which can be declarated in different ways:

  1. void foo(std::string xml); In this case you will copy all data from your variable to function stack, it takes some time, so your performance will be low.
  2. void foo(std::string* xml); In this case you will pass pointer to object, same speed as passing size_t variable, however this declaration has error prone, because you can pass NULL pointer or invalid pointer. Pointers usually used in C because it doesn't have references.
  3. void foo(std::string& xml); Here you pass reference, basically it is the same as passing pointer, but compiler does some stuff and you cannot pass invalid reference (actually it is possible to create situation with invalid reference, but it is tricking compiler).
  4. void foo(const std::string* xml); Here is the same as second, just pointer value cannot be changed.
  5. void foo(const std::string& xml); Here is the same as third, but object value cannot be changed.

What more I want to mention, you can use these 5 ways to pass data no matter which allocation way you have chosen (with new or regular).

Another thing to mention, when you create object in regular way, you allocate memory in stack, but while you create it with new you allocate heap. It is much faster to allocate stack, but it is kind a small for really big arrays of data, so if you need big object you should use heap, because you may get stack overflow, but usually this issue is solved using STL containers and remember std::string is also container, some guys forgot it :)