Programs & Examples On #Change password

This tag refers to the process of setting a new password on a system, thereby making the old password obsolete and no longer usable.

PostgreSQL: How to change PostgreSQL user password?

This was the first result on google, when I was looking how to rename a user, so:

ALTER USER <username> WITH PASSWORD '<new_password>';  -- change password
ALTER USER <old_username> RENAME TO <new_username>;    -- rename user

A couple of other commands helpful for user management:

CREATE USER <username> PASSWORD '<password>' IN GROUP <group>;
DROP USER <username>;

Move user to another group

ALTER GROUP <old_group> DROP USER <username>;
ALTER GROUP <new_group> ADD USER <username>;

Git credential helper - update password

Working solution for Windows:

Control Panel > User Accounts > Credential Manager > Generic Credentials

enter image description here

How do I turn off the mysql password validation?

For references and the future, one should read the doc here

Then you should edit your mysqld.cnf file, for instance :

vim /etc/mysql/mysql.conf.d/mysqld.cnf

Then, add in the [mysqld] part, the following :

Basically, if you edit your default, it will looks like :

# * Basic Settings
user            = mysql
pid-file        = /var/run/mysqld/
socket          = /var/run/mysqld/mysqld.sock
port            = 3306
basedir         = /usr
datadir         = /var/lib/mysql
tmpdir          = /tmp
lc-messages-dir = /usr/share/mysql

Then, you can restart:

systemctl restart mysql

If you forget the part, you will it an error at restart.

Enjoy !

How do I update the password for Git?

For those who are looking for how to reset access to the repository. By the example of GitHub. You can change your GitHub profile password and revoke all "Personal access tokens" in "Settings -> Developer settings" of your profile. Also you can optionally wipe all your SSH/PGP keys and OAuth/GitHub apps to be sure that access to the repository is completely blocked. Thus, all the credential managers, on any system will fail at authorisation and prompt you to enter the new credentials.

How to convert a string variable containing time to time_t type in c++?

You can use strptime(3) to parse the time, and then mktime(3) to convert it to a time_t:

const char *time_details = "16:35:12";
struct tm tm;
strptime(time_details, "%H:%M:%S", &tm);
time_t t = mktime(&tm);  // t is now your desired time_t

Link vs compile vs controller

A directive allows you to extend the HTML vocabulary in a declarative fashion for building web components. The ng-app attribute is a directive, so is ng-controller and all of the ng- prefixed attributes. Directives can be attributes, tags or even class names, comments.

How directives are born (compilation and instantiation)

Compile: We’ll use the compile function to both manipulate the DOM before it’s rendered and return a link function (that will handle the linking for us). This also is the place to put any methods that need to be shared around with all of the instances of this directive.

link: We’ll use the link function to register all listeners on a specific DOM element (that’s cloned from the template) and set up our bindings to the page.

If set in the compile() function they would only have been set once (which is often what you want). If set in the link() function they would be set every time the HTML element is bound to data in the object.

<div ng-repeat="i in [0,1,2]">
        <div>Inner content</div>

app.directive("simple", function(){
   return {
     restrict: "EA",
     template:"<div>{{label}}<div ng-transclude></div></div>",        
     compile: function(element, attributes){  
     return {
             pre: function(scope, element, attributes, controller, transcludeFn){

             post: function(scope, element, attributes, controller, transcludeFn){

     controller: function($scope){


Compile function returns the pre and post link function. In the pre link function we have the instance template and also the scope from the controller, but yet the template is not bound to scope and still don't have transcluded content.

Post link function is where post link is the last function to execute. Now the transclusion is complete, the template is linked to a scope, and the view will update with data bound values after the next digest cycle. The link option is just a shortcut to setting up a post-link function.

controller: The directive controller can be passed to another directive linking/compiling phase. It can be injected into other directices as a mean to use in inter-directive communication.

You have to specify the name of the directive to be required – It should be bound to same element or its parent. The name can be prefixed with:

? – Will not raise any error if a mentioned directive does not exist.
^ – Will look for the directive on parent elements, if not available on the same element.

Use square bracket [‘directive1', ‘directive2', ‘directive3'] to require multiple directives controller.

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

app.controller('MainCtrl', function($scope, $element) {

app.directive('parentDirective', function() {
  return {
    restrict: 'E',
    template: '<child-directive></child-directive>',
    controller: function($scope, $element){
      this.variable = "Hi Vinothbabu"

app.directive('childDirective', function() {
  return {
    restrict:  'E',
    template: '<h1>I am child</h1>',
    replace: true,
    require: '^parentDirective',
    link: function($scope, $element, attr, parentDirectCtrl){
      //you now have access to parentDirectCtrl.variable

Why does python use 'else' after for and while loops?

It's a strange construct even to seasoned Python coders. When used in conjunction with for-loops it basically means "find some item in the iterable, else if none was found do ...". As in:

found_obj = None
for obj in objects:
    if obj.key == search_key:
        found_obj = obj
    print('No object found.')

But anytime you see this construct, a better alternative is to either encapsulate the search in a function:

def find_obj(search_key):
    for obj in objects:
        if obj.key == search_key:
            return obj

Or use a list comprehension:

matching_objs = [o for o in objects if o.key == search_key]
if matching_objs:
    print('Found {}'.format(matching_objs[0]))
    print('No object found.')

It is not semantically equivalent to the other two versions, but works good enough in non-performance critical code where it doesn't matter whether you iterate the whole list or not. Others may disagree, but I personally would avoid ever using the for-else or while-else blocks in production code.

See also [Python-ideas] Summary of for...else threads

Check for false

You can use something simpler:

    console.log('var is false'); 

What is the purpose of nameof?

Most common usage will be in input validation, such as

void Foo(string par) {
   if (par == null) throw new ArgumentNullException("par");

//C# 6 nameof
void Foo(string par) {
   if (par == null) throw new ArgumentNullException(nameof(par));

In first case, if you refactor the method changing par parameter's name, you'll probably forget to change that in the ArgumentNullException. With nameof you don't have to worry about that.

See also: nameof (C# and Visual Basic Reference)

CSS position:fixed inside a positioned element

I achieved to have an element with a fixed position (wiewport) but relative to the width of its parent.

I just had to wrap my fixed element and give the parent a width 100%. At the same time, the wrapped fixed element and the parent are in a div which width changes depending on the page, containing the content of the website. With this approach I can have the fixed element always at the same distance of the content, depending on the width of this one. In my case this was a 'to top' button, always showing at 15px from the bottom and 15px right from the content.

<div class="body">
  <div class="content">
    <p>Some content...</p>
    <div class="top-wrapper">
      <a class="top">Top</a>

.content {
  width: 600px; /*change this width to play with the top element*/
  background-color: wheat;
  height: 9999px;
  margin: auto;
  padding: 20px;
.top-wrapper {
  width: 100%;
  display: flex;
  justify-content: flex-end;
  z-index: 9;
  .top {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 60px;
    height: 60px;
    border-radius: 100%;
    background-color: yellowgreen;
    position: fixed;
    bottom: 20px;
    margin-left: 100px;
    cursor: pointer;
    &:hover {
      opacity: .6;

correct way to use super (argument passing)

Sometimes two classes may have some parameter names in common. In that case, you can't pop the key-value pairs off of **kwargs or remove them from *args. Instead, you can define a Base class which unlike object, absorbs/ignores arguments:

class Base(object):
    def __init__(self, *args, **kwargs): pass

class A(Base):
    def __init__(self, *args, **kwargs):
        print "A"
        super(A, self).__init__(*args, **kwargs)

class B(Base):
    def __init__(self, *args, **kwargs):
        print "B"
        super(B, self).__init__(*args, **kwargs)

class C(A):
    def __init__(self, arg, *args, **kwargs):
        print "C","arg=",arg
        super(C, self).__init__(arg, *args, **kwargs)

class D(B):
    def __init__(self, arg, *args, **kwargs):
        print "D", "arg=",arg
        super(D, self).__init__(arg, *args, **kwargs)

class E(C,D):
    def __init__(self, arg, *args, **kwargs):
        print "E", "arg=",arg
        super(E, self).__init__(arg, *args, **kwargs)

print "MRO:", [x.__name__ for x in E.__mro__]


MRO: ['E', 'C', 'A', 'D', 'B', 'Base', 'object']
E arg= 10
C arg= 10
D arg= 10

Note that for this to work, Base must be the penultimate class in the MRO.

How do I empty an array in JavaScript?

In case you are interested in the memory allocation, you may compare each approach using something like this jsfiddle in conjunction with chrome dev tools' timeline tab. You will want to use the trash bin icon at the bottom to force a garbage collection after 'clearing' the array. This should give you a more definite answer for the browser of your choice. A lot of answers here are old and I wouldn't rely on them but rather test as in @tanguy_k's answer above.

(for an intro to the aforementioned tab you can check out here)

Stackoverflow forces me to copy the jsfiddle so here it is:

var size = 1000*100
window.onload = function() {
  document.getElementById("quantifier").value = size

function scaffold()
  console.log("processing Scaffold...");
  a = new Array
function start()
  size = document.getElementById("quantifier").value
  console.log("Starting... quantifier is " + size);
  console.log("starting test")
  for (i=0; i<size; i++){

function tearDown()
  console.log("processing teardown");

    <span style="color:green;">Quantifier:</span>
    <input id="quantifier" style="color:green;" type="text"></input>
    <button onclick="scaffold()">Scaffold</button>
    <button onclick="start()">Start</button>
    <button onclick="tearDown()">Clean</button>

And you should take note that it may depend on the type of the array elements, as javascript manages strings differently than other primitive types, not to mention arrays of objects. The type may affect what happens.

How to increase dbms_output buffer?

You can Enable DBMS_OUTPUT and set the buffer size. The buffer size can be between 1 and 1,000,000.

dbms_output.enable(buffer_size IN INTEGER DEFAULT 20000);
exec dbms_output.enable(1000000);

Check this


As per the comment posted by Frank and Mat, you can also enable it with Null

exec dbms_output.enable(NULL);

buffer_size : Upper limit, in bytes, the amount of buffered information. Setting buffer_size to NULL specifies that there should be no limit. The maximum size is 1,000,000, and the minimum is 2,000 when the user specifies buffer_size (NOT NULL).

View contents of database file in Android Studio

Follow the above steps to open the database folder of your app in Android Device explorer and in there you can see six files, The first three is named as android and the last three is named as your database name. You only have to work with the last three files, save these three files at your preferred location. You can save these files by right-clicking to the file and click save as button (like I have my database named as room_database and so three files are named as room_database, room_database-shm, and room_database-wal. Rename the corresponding file as follows:-

1) room_database to room_database.db 2) room_database-shm to room_database.db-shm 3) room_database-wal to room_database.db-wal

Now open the 1st file in any SQLite browser and all the three files will be populated in the browser.

How do I do word Stemming or Lemmatization?

If I may quote my answer to the question StompChicken mentioned:

The core issue here is that stemming algorithms operate on a phonetic basis with no actual understanding of the language they're working with.

As they have no understanding of the language and do not run from a dictionary of terms, they have no way of recognizing and responding appropriately to irregular cases, such as "run"/"ran".

If you need to handle irregular cases, you'll need to either choose a different approach or augment your stemming with your own custom dictionary of corrections to run after the stemmer has done its thing.

How do you create optional arguments in php?

If you don't know how many attributes need to be processed, you can use the variadic argument list token(...) introduced in PHP 5.6 (see full documentation here).


function <functionName> ([<type> ]...<$paramName>) {}

For example:

function someVariadricFunc(...$arguments) {
  foreach ($arguments as $arg) {
    // do some stuff with $arg...

someVariadricFunc();           // an empty array going to be passed
someVariadricFunc('apple');    // provides a one-element array
someVariadricFunc('apple', 'pear', 'orange', 'banana');

As you can see, this token basically turns all parameters to an array, which you can process in any way you like.

Python import csv to list

Unfortunately I find none of the existing answers particularly satisfying.

Here is a straightforward and complete Python 3 solution, using the csv module.

import csv

with open('../resources/temp_in.csv', newline='') as f:
    reader = csv.reader(f, skipinitialspace=True)
    rows = list(reader)


Notice the skipinitialspace=True argument. This is necessary since, unfortunately, OP's CSV contains whitespace after each comma.


[['This is the first line', 'Line1'], ['This is the second line', 'Line2'], ['This is the third line', 'Line3']]

In SQL Server, what does "SET ANSI_NULLS ON" mean?

It means that no rows will be returned if @region is NULL, when used in your first example, even if there are rows in the table where Region is NULL.

When ANSI_NULLS is on (which you should always set on anyway, since the option to not have it on is going to be removed in the future), any comparison operation where (at least) one of the operands is NULL produces the third logic value - UNKNOWN (as opposed to TRUE and FALSE).

UNKNOWN values propagate through any combining boolean operators if they're not already decided (e.g. AND with a FALSE operand or OR with a TRUE operand) or negations (NOT).

The WHERE clause is used to filter the result set produced by the FROM clause, such that the overall value of the WHERE clause must be TRUE for the row to not be filtered out. So, if an UNKNOWN is produced by any comparison, it will cause the row to be filtered out.

@user1227804's answer includes this quote:

If both sides of the comparison are columns or compound expressions, the setting does not affect the comparison.


However, I'm not sure what point it's trying to make, since if two NULL columns are compared (e.g. in a JOIN), the comparison still fails:

create table #T1 (
    ID int not null,
    Val1 varchar(10) null
insert into #T1(ID,Val1) select 1,null

create table #T2 (
    ID int not null,
    Val1 varchar(10) null
insert into #T2(ID,Val1) select 1,null

select * from #T1 t1 inner join #T2 t2 on t1.ID = t2.ID and t1.Val1 = t2.Val1

The above query returns 0 rows, whereas:

select * from #T1 t1 inner join #T2 t2 on t1.ID = t2.ID and (t1.Val1 = t2.Val1 or t1.Val1 is null and t2.Val1 is null)

Returns one row. So even when both operands are columns, NULL does not equal NULL. And the documentation for = doesn't have anything to say about the operands:

When you compare two NULL expressions, the result depends on the ANSI_NULLS setting:

If ANSI_NULLS is set to ON, the result is NULL1, following the ANSI convention that a NULL (or unknown) value is not equal to another NULL or unknown value.

If ANSI_NULLS is set to OFF, the result of NULL compared to NULL is TRUE.

Comparing NULL to a non-NULL value always results in FALSE2.

However, both 1 and 2 are incorrect - the result of both comparisons is UNKNOWN.

*The cryptic meaning of this text was finally discovered years later. What it actually means is that, for those comparisons, the setting has no effect and it always acts as if the setting were ON. Would have been clearer if it had stated that SET ANSI_NULLS OFF was the setting that had no affect.

Subtract two dates in Java

Assuming that you're constrained to using Date, you can do the following:

Date diff = new Date(d2.getTime() - d1.getTime());

Here you're computing the differences in milliseconds since the "epoch", and creating a new Date object at an offset from the epoch. Like others have said: the answers in the duplicate question are probably better alternatives (if you aren't tied down to Date).

R define dimensions of empty data frame

You may use NULL instead of NA. This creates a truly empty data frame.

Is there an auto increment in sqlite?

Have you read this? How do I create an AUTOINCREMENT field.

VALUES (NULL, "John", "Smith");

CSS z-index not working (position absolute)


You have to put the second div on top of the first one because the both have an z-index of zero so that the order in the dom will decide which is on top. This also affects the relative positioned div because its z-index relates to elements inside the parent div.

<div class="absolute" style="top: 54px"></div>
<div class="absolute">
    <div id="relative"></div>

Css stays the same.

Why use the INCLUDE clause when creating an index?

An additional consideraion that I have not seen in the answers already given, is that included columns can be of data types that are not allowed as index key columns, such as varchar(max).

This allows you to include such columns in a covering index. I recently had to do this to provide a nHibernate generated query, which had a lot of columns in the SELECT, with a useful index.

How do I force a vertical scrollbar to appear?

html { overflow-y: scroll; }

This css rule causes a vertical scrollbar to always appear.


How to create an installer for a .net Windows Service using Visual Studio

For VS2017 you will need to add the "Microsoft Visual Studio 2017 Installer Projects" VS extension. This will give you additional Visual Studio Installer project templates.

To install the windows service you can add a new setup wizard type project and follow the steps from Kelsey's answer

How can I set the maximum length of 6 and minimum length of 6 in a textbox?

Addition to Alex' answer:


$(function() {
    $('input[type="submit"]').prop('disabled', true);
    $('#check').on('input', function(e) {
        if(this.value.length === 6) {
            $('input[type="submit"]').prop('disabled', false);
        } else {
            $('input[type="submit"]').prop('disabled', true);


<input type="text" maxlength="6" id="check" data-minlength="6" /><br />
<input type="submit" value="send" />


But: You should always remember to validate the user input on the server side again. The user could modify the local HTML or disable JavaScript.

Why do we use arrays instead of other data structures?

Time to go back in time for a lesson. While we don't think about these things much in our fancy managed languages today, they are built on the same foundation, so let's look at how memory is managed in C.

Before I dive in, a quick explanation of what the term "pointer" means. A pointer is simply a variable that "points" to a location in memory. It doesn't contain the actual value at this area of memory, it contains the memory address to it. Think of a block of memory as a mailbox. The pointer would be the address to that mailbox.

In C, an array is simply a pointer with an offset, the offset specifies how far in memory to look. This provides O(1) access time.

  MyArray   [5]
     ^       ^
  Pointer  Offset

All other data structures either build upon this, or do not use adjacent memory for storage, resulting in poor random access look up time (Though there are other benefits to not using sequential memory).

For example, let's say we have an array with 6 numbers (6,4,2,3,1,5) in it, in memory it would look like this:

|  6  |  4  |  2  |  3  |  1  |  5  |

In an array, we know that each element is next to each other in memory. A C array (Called MyArray here) is simply a pointer to the first element:

|  6  |  4  |  2  |  3  |  1  |  5  |

If we wanted to look up MyArray[4], internally it would be accessed like this:

   0     1     2     3     4 
|  6  |  4  |  2  |  3  |  1  |  5  |
MyArray + 4 ---------------/
(Pointer + Offset)

Because we can directly access any element in the array by adding the offset to the pointer, we can look up any element in the same amount of time, regardless of the size of the array. This means that getting MyArray[1000] would take the same amount of time as getting MyArray[5].

An alternative data structure is a linked list. This is a linear list of pointers, each pointing to the next node

========    ========    ========    ========    ========
| Data |    | Data |    | Data |    | Data |    | Data |
|      | -> |      | -> |      | -> |      | -> |      | 
|  P1  |    |  P2  |    |  P3  |    |  P4  |    |  P5  |        
========    ========    ========    ========    ========

P(X) stands for Pointer to next node.

Note that I made each "node" into its own block. This is because they are not guaranteed to be (and most likely won't be) adjacent in memory.

If I want to access P3, I can't directly access it, because I don't know where it is in memory. All I know is where the root (P1) is, so instead I have to start at P1, and follow each pointer to the desired node.

This is a O(N) look up time (The look up cost increases as each element is added). It is much more expensive to get to P1000 compared to getting to P4.

Higher level data structures, such as hashtables, stacks and queues, all may use an array (or multiple arrays) internally, while Linked Lists and Binary Trees usually use nodes and pointers.

You might wonder why anyone would use a data structure that requires linear traversal to look up a value instead of just using an array, but they have their uses.

Take our array again. This time, I want to find the array element that holds the value '5'.

|  6  |  4  |  2  |  3  |  1  |  5  |
   ^     ^     ^     ^     ^   FOUND!

In this situation, I don't know what offset to add to the pointer to find it, so I have to start at 0, and work my way up until I find it. This means I have to perform 6 checks.

Because of this, searching for a value in an array is considered O(N). The cost of searching increases as the array gets larger.

Remember up above where I said that sometimes using a non sequential data structure can have advantages? Searching for data is one of these advantages and one of the best examples is the Binary Tree.

A Binary Tree is a data structure similar to a linked list, however instead of linking to a single node, each node can link to two children nodes.

         |  Root  |         
        /          \ 
  =========       =========
  | Child |       | Child |
  =========       =========
                  /       \
            =========    =========
            | Child |    | Child |
            =========    =========

 Assume that each connector is really a Pointer

When data is inserted into a binary tree, it uses several rules to decide where to place the new node. The basic concept is that if the new value is greater than the parents, it inserts it to the left, if it is lower, it inserts it to the right.

This means that the values in a binary tree could look like this:

         |   100  |         
        /          \ 
  =========       =========
  |  200  |       |   50  |
  =========       =========
                  /       \
            =========    =========
            |   75  |    |   25  |
            =========    =========

When searching a binary tree for the value of 75, we only need to visit 3 nodes ( O(log N) ) because of this structure:

  • Is 75 less than 100? Look at Right Node
  • Is 75 greater than 50? Look at Left Node
  • There is the 75!

Even though there are 5 nodes in our tree, we did not need to look at the remaining two, because we knew that they (and their children) could not possibly contain the value we were looking for. This gives us a search time that at worst case means we have to visit every node, but in the best case we only have to visit a small portion of the nodes.

That is where arrays get beat, they provide a linear O(N) search time, despite O(1) access time.

This is an incredibly high level overview on data structures in memory, skipping over a lot of details, but hopefully it illustrates an array's strength and weakness compared to other data structures.

YouTube Video Embedded via iframe Ignoring z-index?

All you need on the iframe is:


and in the URL:

How to stop an unstoppable zombie job on Jenkins without restarting the server?

Enter the blue-ocean UI. Try to stop the job from there.

Repeat table headers in print mode

Some browsers repeat the thead element on each page, as they are supposed to. Others need some help: Add this to your CSS:

thead {display: table-header-group;}
tfoot {display: table-header-group;}

Opera 7.5 and IE 5 won't repeat headers no matter what you try.


Difference between char* and const char*?

Actually, char* name is not a pointer to a constant, but a pointer to a variable. You might be talking about this other question.

What is the difference between char * const and const char *?

Forward declaration of a typedef in C++

I replaced the typedef (using to be specific) with inheritance and constructor inheritance (?).


using CallStack = std::array<StackFrame, MAX_CALLSTACK_DEPTH>;


struct CallStack // Not a typedef to allow forward declaration.
  : public std::array<StackFrame, MAX_CALLSTACK_DEPTH>
  typedef std::array<StackFrame, MAX_CALLSTACK_DEPTH> Base;
  using Base::Base;

This way I was able to forward declare CallStack with:

class CallStack;

Merge some list items in a Python List

my telepathic abilities are not particularly great, but here is what I think you want:

def merge(list_of_strings, indices):
    list_of_strings[indices[0]] = ''.join(list_of_strings[i] for i in indices)
    list_of_strings = [s for i, s in enumerate(list_of_strings) if i not in indices[1:]]
    return list_of_strings

I should note, since it might be not obvious, that it's not the same as what is proposed in other answers.

How to overcome "datetime.datetime not JSON serializable"?

Generally there are several ways to serialize datetimes, like:

  1. ISO string, short and can include timezone info, e.g. @jgbarah's answer
  2. Timestamp (timezone data is lost), e.g. @JayTaylor's answer
  3. Dictionary of properties (including timezone).

If you're okay with the last way, the json_tricks package handles dates, times and datetimes including timezones.

from datetime import datetime
from json_tricks import dumps
foo = {'title': 'String', 'datetime': datetime(2012, 8, 8, 21, 46, 24, 862000)}

which gives:

{"title": "String", "datetime": {"__datetime__": null, "year": 2012, "month": 8, "day": 8, "hour": 21, "minute": 46, "second": 24, "microsecond": 862000}}

So all you need to do is

`pip install json_tricks`

and then import from json_tricks instead of json.

The advantage of not storing it as a single string, int or float comes when decoding: if you encounter just a string or especially int or float, you need to know something about the data to know if it's a datetime. As a dict, you can store metadata so it can be decoded automatically, which is what json_tricks does for you. It's also easily editable for humans.

Disclaimer: it's made by me. Because I had the same problem.

Where is the <conio.h> header file on Linux? Why can't I find <conio.h>?

conio.h is a C header file used in old MS-DOS compilers to create text user interfaces. Compilers that targeted non-DOS operating systems, such as Linux, Win32 and OS/2, provided different implementations of these functions.

The #include <curses.h> will give you almost all the functionalities that was provided in conio.h

nucurses need to be installed at the first place

In deb based Distros use

sudo apt-get install libncurses5-dev libncursesw5-dev

And in rpm based distros use

sudo yum install ncurses-devel ncurses

For getch() class of functions, you can try this

Directory.GetFiles: how to get only filename, not full path?

Have a look at using FileInfo.Name Property

something like

string[] files = Directory.GetFiles(dir); 

for (int iFile = 0; iFile < files.Length; iFile++)
    string fn = new FileInfo(files[iFile]).Name;

Also have a look at using DirectoryInfo Class and FileInfo Class

Convert time in HH:MM:SS format to seconds only?

No need to explode anything:

$str_time = "23:12:95";

$str_time = preg_replace("/^([\d]{1,2})\:([\d]{2})$/", "00:$1:$2", $str_time);

sscanf($str_time, "%d:%d:%d", $hours, $minutes, $seconds);

$time_seconds = $hours * 3600 + $minutes * 60 + $seconds;

And if you don't want to use regular expressions:

$str_time = "2:50";

sscanf($str_time, "%d:%d:%d", $hours, $minutes, $seconds);

$time_seconds = isset($seconds) ? $hours * 3600 + $minutes * 60 + $seconds : $hours * 60 + $minutes;

How to convert ZonedDateTime to Date?

The accepted answer did not work for me. The Date returned is always the local Date and not the Date for the original Time Zone. I live in UTC+2.

//This did not work for me

I have come up with two alternative ways to get the correct Date from a ZonedDateTime.

Say you have this ZonedDateTime for Hawaii

LocalDateTime ldt =;
ZonedDateTime zdt = ldt.atZone(ZoneId.of("US/Hawaii"); // UTC-10

or for UTC as asked originally

Instant zulu =; // GMT, UTC+0
ZonedDateTime zdt = zulu.atZone(ZoneId.of("UTC"));

Alternative 1

We can use java.sql.Timestamp. It is simple but it will probably also make a dent in your programming integrity

Date date1 = Timestamp.valueOf(zdt.toLocalDateTime());

Alternative 2

We create the Date from millis (answered here earlier). Note that local ZoneOffset is a must.

ZoneOffset localOffset = ZoneOffset.systemDefault().getRules().getOffset(;
long zonedMillis = 1000L * zdt.toLocalDateTime().toEpochSecond(localOffset) + zdt.toLocalDateTime().getNano() / 1000000L;
Date date2 = new Date(zonedMillis);

Change label text using JavaScript

Use .textContent instead.

I was struggling with changing the value of a label as well, until I tried this.

If this doesn't solve try inspecting the object to see what properties you can set by logging it to the console with console.dir as shown on this question: How can I log an HTML element as a JavaScript object?

Why is jquery's .ajax() method not sending my session cookie?

After trying out the other solutions and still not getting it to work, I found out what the problem was in my case. I changed contentType from "application/json" to "text/plain".

$.ajax(fullUrl, {
    type: "GET",
    contentType: "text/plain",
    xhrFields: {
         withCredentials: true
    crossDomain: true

How to get method parameter names?

Take a look at the inspect module - this will do the inspection of the various code object properties for you.

>>> inspect.getfullargspec(a_method)
(['arg1', 'arg2'], None, None, None)

The other results are the name of the *args and **kwargs variables, and the defaults provided. ie.

>>> def foo(a, b, c=4, *arglist, **keywords): pass
>>> inspect.getfullargspec(foo)
(['a', 'b', 'c'], 'arglist', 'keywords', (4,))

Note that some callables may not be introspectable in certain implementations of Python. For Example, in CPython, some built-in functions defined in C provide no metadata about their arguments. As a result, you will get a ValueError if you use inspect.getfullargspec() on a built-in function.

Since Python 3.3, you can use inspect.signature() to see the call signature of a callable object:

>>> inspect.signature(foo)
<Signature (a, b, c=4, *arglist, **keywords)>

What is the meaning of "POSIX"?

POSIX is a standard for operating systems that was supposed to make it easier to write cross-platform software. It's an especially big deal in the world of Unix.

How to execute Ant build in command line

is it still actual?

As I can see you wrote <target depends="build-subprojects,build-project" name="build"/>, then you wrote <target name="build-subprojects"/> (it does nothing). Could it be a reason? Does this <echo message="${}: ${ant.file}"/> print appropriate message? If no then target is not running. Take a look at the next link

Unable to create Android Virtual Device

Had to restart the Eclipse after completing the installation of ARM EABI v7a system image.

FailedPreconditionError: Attempting to use uninitialized in Tensorflow

The FailedPreconditionError comes because the session is trying to read a variable that hasn"t been initialized.

As of Tensorflow version 1.11.0, you need to take this :

init_op = tf.global_variables_initializer()

sess = tf.Session()

numpy division with RuntimeWarning: invalid value encountered in double_scalars

You can use np.logaddexp (which implements the idea in @gg349's answer):

In [33]: d = np.array([[1089, 1093]])

In [34]: e = np.array([[1000, 4443]])

In [35]: log_res = np.logaddexp(-3*d[0,0], -3*d[0,1]) - np.logaddexp(-3*e[0,0], -3*e[0,1])

In [36]: log_res
Out[36]: -266.99999385580668

In [37]: res = exp(log_res)

In [38]: res
Out[38]: 1.1050349147204485e-116

Or you can use scipy.special.logsumexp:

In [52]: from scipy.special import logsumexp

In [53]: res = np.exp(logsumexp(-3*d) - logsumexp(-3*e))

In [54]: res
Out[54]: 1.1050349147204485e-116

How to remove html special chars?

Use html_entity_decode to convert HTML entities.

You'll need to set charset to make it work correctly.

How to get only time from date-time C#

This works for me. I discovered it when I had to work with DateTime.Date to get only the date part.

var wholeDate = DateTime.Parse("6/22/2009 10:00:00 AM");
var time = wholeDate - wholeDate.Date;

SQL How to remove duplicates within select query?

Do you need any other information except the date? If not:

SELECT DISTINCT start_date FROM table;

Python list sort in descending order

This will give you a sorted version of the array.

sorted(timestamps, reverse=True)

If you want to sort in-place:


Does Android support near real time push notification?

If you can depend on the Google libraries being there for you target market, then you may want to piggy back on GTalk functionality (registering a resource on the existing username - the intercepting it the messages as they come in with a BroadcastReceiver).

If not, and I expect you can't, then you're into bundling your own versions of XMPP. This is a pain, but may be made easier if XMPP is bundled separately as a standalone library.

You may also consider PubSubHubub, but I have no idea the network usage of it. I believe it is built atop of XMPP.

SDK location not found. Define location with sdk.dir in the file or with an ANDROID_HOME environment variable

There is not a single reason for this error.

  1. settings.gradle may be missing or the content in it may be wrong.
  2. may be missing or the sdk path may be wrongly written.

Crop image in android

This library: Android-Image-Cropper is very powerful to CropImages. It has 3,731 stars on github at this time.

You will crop your images with a few lines of code.

1 - Add the dependecies into buid.gradle (Module: app)

compile 'com.theartofdev.edmodo:android-image-cropper:2.7.+'

2 - Add the permissions into AndroidManifest.xml

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

3 - Add CropImageActivity into AndroidManifest.xml

<activity android:name="com.theartofdev.edmodo.cropper.CropImageActivity"

4 - Start the activity with one of the cases below, depending on your requirements.

// start picker to get image for cropping and then use the image in cropping activity

// start cropping activity for pre-acquired image saved on the device

// for fragment (DO NOT use `getActivity()`)
.start(getContext(), this);

5 - Get the result in onActivityResult

public void onActivityResult(int requestCode, int resultCode, Intent data) {
  if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
    CropImage.ActivityResult result = CropImage.getActivityResult(data);
    if (resultCode == RESULT_OK) {
      Uri resultUri = result.getUri();
    } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
      Exception error = result.getError();

You can do several customizations, as set the Aspect Ratio or the shape to RECTANGLE, OVAL and a lot more.

Is there a way to get the source code from an APK file?

apktool is THE way to go. Online apktool service exists as well:

Some limitations, obviously, exist due to the service ‘online nature’: you may extract and research assets and the manifest file, but it is impossible to recompile the application at the moment.

Still, this is a no-hassle way to 'open' the android application.

Java Wait for thread to finish

Generally, when you want to wait for a thread to finish, you should call join() on it.

Access-Control-Allow-Origin Multiple Origin Domains?

If you are having trouble with fonts, use:

<FilesMatch "\.(ttf|ttc|otf|eot|woff)$">
    <IfModule mod_headers>
        Header set Access-Control-Allow-Origin "*"

How to make an array of arrays in Java

there is the class I mentioned in the comment we had with Sean Patrick Floyd : I did it with a peculiar use which needs WeakReference, but you can change it by any object with ease.

Hoping this can help someone someday :)

import java.lang.ref.WeakReference;
import java.util.LinkedList;
import java.util.NoSuchElementException;
import java.util.Queue;

 * @author leBenj
public class Array2DWeakRefsBuffered<T>
    private final WeakReference<T>[][] _array;
    private final Queue<T> _buffer;

    private final int _width;

    private final int _height;

    private final int _bufferSize;

    @SuppressWarnings( "unchecked" )
    public Array2DWeakRefsBuffered( int w , int h , int bufferSize )
        _width = w;
        _height = h;
        _bufferSize = bufferSize;
        _array = new WeakReference[_width][_height];
        _buffer = new LinkedList<T>();

     * Tests the existence of the encapsulated object
     * /!\ This DOES NOT ensure that the object will be available on next call !
     * @param x
     * @param y
     * @return
     * @throws IndexOutOfBoundsException
     */public boolean exists( int x , int y ) throws IndexOutOfBoundsException
        if( x >= _width || x < 0 )
            throw new IndexOutOfBoundsException( "Index out of bounds (get) : [ x = " + x + "]" );
        if( y >= _height || y < 0 )
            throw new IndexOutOfBoundsException( "Index out of bounds (get) : [ y = " + y + "]" );
        if( _array[x][y] != null )
            T elem = _array[x][y].get();
            if( elem != null )
            return true;
        return false;

     * Gets the encapsulated object
     * @param x
     * @param y
     * @return
     * @throws IndexOutOfBoundsException
     * @throws NoSuchElementException
    public T get( int x , int y ) throws IndexOutOfBoundsException , NoSuchElementException
        T retour = null;
        if( x >= _width || x < 0 )
            throw new IndexOutOfBoundsException( "Index out of bounds (get) : [ x = " + x + "]" );
        if( y >= _height || y < 0 )
            throw new IndexOutOfBoundsException( "Index out of bounds (get) : [ y = " + y + "]" );
        if( _array[x][y] != null )
            retour = _array[x][y].get();
            if( retour == null )
            throw new NoSuchElementException( "Dereferenced WeakReference element at [ " + x + " ; " + y + "]" );
            throw new NoSuchElementException( "No WeakReference element at [ " + x + " ; " + y + "]" );
        return retour;

     * Add/replace an object
     * @param o
     * @param x
     * @param y
     * @throws IndexOutOfBoundsException
    public void set( T o , int x , int y ) throws IndexOutOfBoundsException
        if( x >= _width || x < 0 )
            throw new IndexOutOfBoundsException( "Index out of bounds (set) : [ x = " + x + "]" );
        if( y >= _height || y < 0 )
            throw new IndexOutOfBoundsException( "Index out of bounds (set) : [ y = " + y + "]" );
        _array[x][y] = new WeakReference<T>( o );

        // store local "visible" references : avoids deletion, works in FIFO mode
        _buffer.add( o );
        if(_buffer.size() > _bufferSize)


Example of how to use it :

// a 5x5 array, with at most 10 elements "bufferized" -> the last 10 elements will not be taken by GC process
Array2DWeakRefsBuffered<Image> myArray = new Array2DWeakRefsBuffered<Image>(5,5,10);
Image img = myArray.set(anImage,0,0);
    System.out.println("Image at 3,3 is still in memory");

Adding Image to xCode by dragging it from File

Add the image to Your project by clicking File -> "Add Files to ...".

Then choose the image in ImageView properties (Utilities -> Attributes Inspector).

How to get MAC address of your machine using a C program?

Using getifaddrs you can get MAC address from the family AF_PACKET.

In order to display the MAC address to each interface, you can proceed like this:

#include <stdio.h>
#include <ifaddrs.h>
#include <netpacket/packet.h>

int main (int argc, const char * argv[])
    struct ifaddrs *ifaddr=NULL;
    struct ifaddrs *ifa = NULL;
    int i = 0;

    if (getifaddrs(&ifaddr) == -1)
         for ( ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next)
             if ( (ifa->ifa_addr) && (ifa->ifa_addr->sa_family == AF_PACKET) )
                  struct sockaddr_ll *s = (struct sockaddr_ll*)ifa->ifa_addr;
                  printf("%-8s ", ifa->ifa_name);
                  for (i=0; i <s->sll_halen; i++)
                      printf("%02x%c", (s->sll_addr[i]), (i+1!=s->sll_halen)?':':'\n');
    return 0;


Java: How to read a text file

You can use Files#readAllLines() to get all lines of a text file into a List<String>.

for (String line : Files.readAllLines(Paths.get("/path/to/file.txt"))) {
    // ...

Tutorial: Basic I/O > File I/O > Reading, Writing and Creating text files

You can use String#split() to split a String in parts based on a regular expression.

for (String part : line.split("\\s+")) {
    // ...

Tutorial: Numbers and Strings > Strings > Manipulating Characters in a String

You can use Integer#valueOf() to convert a String into an Integer.

Integer i = Integer.valueOf(part);

Tutorial: Numbers and Strings > Strings > Converting between Numbers and Strings

You can use List#add() to add an element to a List.


Tutorial: Interfaces > The List Interface

So, in a nutshell (assuming that the file doesn't have empty lines nor trailing/leading whitespace).

List<Integer> numbers = new ArrayList<>();
for (String line : Files.readAllLines(Paths.get("/path/to/file.txt"))) {
    for (String part : line.split("\\s+")) {
        Integer i = Integer.valueOf(part);

If you happen to be at Java 8 already, then you can even use Stream API for this, starting with Files#lines().

List<Integer> numbers = Files.lines(Paths.get("/path/to/test.txt"))
    .map(line -> line.split("\\s+")).flatMap(Arrays::stream)

Tutorial: Processing data with Java 8 streams

Git commit -a "untracked files"?

For others having the same problem, try running

git add . which will add all files of the current directory to track (including untracked) and then use

git commit -a to commit all tracked files.

As suggested by @Pacerier, one liner that does the same thing is

git add -A

Simplest way to serve static data from outside the application server in a Java web application

You can do it by putting your images on a fixed path (for example: /var/images, or c:\images), add a setting in your application settings (represented in my example by the Settings.class), and load them like that, in a HttpServlet of yours:

String filename = Settings.getValue("images.path") + request.getParameter("imageName")
FileInputStream fis = new FileInputStream(filename);

int b = 0;
while ((b = != -1) {

Or if you want to manipulate the image:

String filename = Settings.getValue("images.path") + request.getParameter("imageName")
File imageFile = new File(filename);
BufferedImage image =;
ImageIO.write(image, "image/png", response.getOutputStream());

then the html code would be <img src="imageServlet?imageName=myimage.png" />

Of course you should think of serving different content types - "image/jpeg", for example based on the file extension. Also you should provide some caching.

In addition you could use this servlet for quality rescaling of your images, by providing width and height parameters as arguments, and using image.getScaledInstance(w, h, Image.SCALE_SMOOTH), considering performance, of course.

Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints

To fix this error, i took off the troubling table adapter from the Dataset designer, and saved the dataset, and then dragged a fresh copy of the table adapter from the server explorer and that fixed it

How SID is different from Service name in Oracle tnsnames.ora

As per Oracle Glossary :

SID is a unique name for an Oracle database instance. ---> To switch between Oracle databases, users must specify the desired SID <---. The SID is included in the CONNECT DATA parts of the connect descriptors in a TNSNAMES.ORA file, and in the definition of the network listener in the LISTENER.ORA file. Also known as System ID. Oracle Service Name may be anything descriptive like "MyOracleServiceORCL". In Windows, You can your Service Name running as a service under Windows Services.

You should use SID in TNSNAMES.ORA as a better approach.

Android: How to use webcam in emulator?

Follow the below steps in Eclipse.

  1. Goto -> AVD Manager
  2. Create/Edit the AVD.
  3. Hardware > New:
  4. Configures camera facing back
  5. Click on the property value and choose = "webcam0".
  6. Once done all the above the webcam should be connected. If it doesnt then you need to check your WebCam drivers.

Check here for more information : How to use web camera in android emulator to capture a live image?

enter image description here

How do I prevent an Android device from going to sleep programmatically?

Set flags on Activity's Window as below

@Override public void onResume() {

@Override public void onPause() {

Angular JS break ForEach

I would use return instead of break.

angular.forEach([0,1,2], function(count){
  if(count == 1){

Works like a charm.

How can I add a variable to console.log?

You can use another console method:

let name = prompt("what is your name?");
console.log(`story ${name} story`);

MySQL Removing Some Foreign keys

The foreign keys are there to ensure data integrity, so you can't drop a column as long as it's part of a foreign key. You need to drop the key first.

I would think the following query would do it:

ALTER TABLE assignmentStuff DROP FOREIGN KEY assignmentIDX;

Regular expression to validate US phone numbers?

The easiest way to match both




is to use alternation ((...|...)): specify them as two mostly-separate options:


By the way, when Americans put the area code in parentheses, we actually put a space after that; for example, I'd write (123) 123-1234, not (123)123-1234. So you might want to write:

^(\([0-9]{3}\) |[0-9]{3}-)[0-9]{3}-[0-9]{4}$

(Though it's probably best to explicitly demonstrate the format that you expect phone numbers to be in.)

Center a button in a Linear layout

You can use the RelativeLayout.

How should I print types like off_t and size_t?

Which version of C are you using?

In C90, the standard practice is to cast to signed or unsigned long, as appropriate, and print accordingly. I've seen %z for size_t, but Harbison and Steele don't mention it under printf(), and in any case that wouldn't help you with ptrdiff_t or whatever.

In C99, the various _t types come with their own printf macros, so something like "Size is " FOO " bytes." I don't know details, but that's part of a fairly large numeric format include file.

Create a sample login page using servlet and JSP?

You aren't really using the doGet() method. When you're opening the page, it issues a GET request, not POST.

Try changing doPost() to service() instead... then you're using the same method to handle GET and POST requests.


How do I use JDK 7 on Mac OSX?

Get cask

brew tap caskroom/cask

Install java7:

brew tap caskroom/versions
brew cask install java7

(I had difficulty finding the download link of java7 on oracle website, as they're just "recommending" java8 )

EDIT January 2018 (As pointed by Ankur):

Use zulu7 cask. Zulu is a certified build of OpenJDK produced by Azul Systems that should be around for a long time (they even offer JDK6 builds still).

brew cask install caskroom/versions/zulu7

How do I iterate over an NSArray?

The three ways are:

    NSArray *arrData = @[@1,@2,@3,@4];

    // 1.Classical
    for (int i=0; i< [arrData count]; i++){

    // 2.Fast iteration
    for (id element in arrData){

    // 3.Blocks
    [arrData enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
         // Set stop to YES in case you want to break the iteration
  1. Is the fastest way in execution, and 3. with autocompletion forget about writing iteration envelope.

Throw away local commits in Git

Use any number of times, to revert back to the last commit without deleting any files that you have recently created.

git reset --soft HEAD~1

Then use

git reset HEAD <name-of-file/files*>

to unstage, or untrack.

Toggle visibility property of div

According to the jQuery docs, calling toggle() without parameters will toggle visibility.


ORA-01882: timezone region not found

  1. in eclipse go run - > run configuration

  2. in there go to JRE tab in right side panels

  3. in VM Arguments section paste this


  4. then Apply - > Run

PHP compare two arrays and get the matched values not the difference

Simple, use array_intersect() instead:

$result = array_intersect($array1, $array2);

Which to use <div class="name"> or <div id="name">?

ID's must be unique (only be given to one element in the DOM at a time), whereas classes don't have to be. You've already discovered the CSS . class and # ID prefixes, so that's pretty much it.

535-5.7.8 Username and Password not accepted

First, You need to use a valid Gmail account with your credentials.

Second, In my app I don't use TLS auto, try without this line:

config.action_mailer.smtp_settings = {
  address:              '',
  port:                 587,
  domain:               '',
  user_name:            '[email protected]',
  password:             'YOUR_PASSWORD',
  authentication:       'plain'
  # enable_starttls_auto: true
  # ^ ^ remove this option ^ ^

UPDATE: (See answer below for details) now you need to enable "less secure apps" on your Google Account

Add column with number of days between dates in DataFrame pandas

A list comprehension is your best bet for the most Pythonic (and fastest) way to do this:

[int(i.days) for i in (df.B - df.A)]
  1. i will return the timedelta(e.g. '-58 days')
  2. i.days will return this value as a long integer value(e.g. -58L)
  3. int(i.days) will give you the -58 you seek.

If your columns aren't in datetime format. The shorter syntax would be: df.A = pd.to_datetime(df.A)

How do I add multiple "NOT LIKE '%?%' in the WHERE clause of sqlite3?

If you have any problems with the "not like" query, Consider that you may have a null in the database. In this case, Use:

IFNULL(word, '') NOT LIKE '%something%'

What causes the error "_pickle.UnpicklingError: invalid load key, ' '."?

pickling is recursive, not sequential. Thus, to pickle a list, pickle will start to pickle the containing list, then pickle the first element… diving into the first element and pickling dependencies and sub-elements until the first element is serialized. Then moves on to the next element of the list, and so on, until it finally finishes the list and finishes serializing the enclosing list. In short, it's hard to treat a recursive pickle as sequential, except for some special cases. It's better to use a smarter pattern on your dump, if you want to load in a special way.

The most common pickle, it to pickle everything with a single dump to a file -- but then you have to load everything at once with a single load. However, if you open a file handle and do multiple dump calls (e.g. one for each element of the list, or a tuple of selected elements), then your load will mirror that… you open the file handle and do multiple load calls until you have all the list elements and can reconstruct the list. It's still not easy to selectively load only certain list elements, however. To do that, you'd probably have to store your list elements as a dict (with the index of the element or chunk as the key) using a package like klepto, which can break up a pickled dict into several files transparently, and enables easy loading of specific elements.

Saving and loading multiple objects in pickle file?

How to create a directive with a dynamic template in AngularJS?

I have been in the same situation, my complete solution has been posted here

Basically I load a template in the directive in this way

var tpl = '' + 
    <div ng-if="maxLength" 
    </div>' +
    '<div ng-if="required" 

then according to the value of maxLength and required I can dynamically load one of the 2 templates, only one of them at a time is shown if necessary.

I heope it helps.

How to define several include path in Makefile

You need to use -I with each directory. But you can still delimit the directories with whitespace if you use (GNU) make's foreach:

INC=$(DIR1) $(DIR2) ...
INC_PARAMS=$(foreach d, $(INC), -I$d)

Getting a UnhandledPromiseRejectionWarning when testing using mocha/chai

I got this error when stubbing with sinon.

The fix is to use npm package sinon-as-promised when resolving or rejecting promises with stubs.

Instead of ...

sinon.stub(Database, 'connect').returns(Promise.reject( Error('oops') ))

Use ...

sinon.stub(Database, 'connect').rejects(Error('oops'));

There is also a resolves method (note the s on the end).


using scp in terminal

Simple :::

scp remoteusername@remoteIP:/path/of/file /Local/path/to/copy

scp -r remoteusername@remoteIP:/path/of/folder /Local/path/to/copy

Wi-Fi Direct and iOS Support

The official list of current iOS Wi-Fi Management APIs

There is no Wi-Fi Direct type of connection available. The primary issue being that Apple does not allow programmatic setting of the Wi-Fi network SSID and password. However, this improves substantially in iOS 11 where you can at least prompt the user to switch to another WiFi network.

QA1942 - iOS Wi-Fi Management APIs

Entitlement option

This technology is useful if you want to provide a list of Wi-Fi networks that a user might want to connect to in a manager type app. It requires that you apply for this entitlement with Apple and the email address is in the documentation.

MFi Program options

These technologies allow the accessory connect to the same network as the iPhone and are not for setting up a peer-to-peer connection.

  • Wireless Accessory Configuration (WAC)
  • HomeKit

Peer-to-peer between Apple devices

These APIs come close to what you want, but they're Apple-to-Apple only.

WiTap Example Code

iOS 11 NEHotspotConfiguration

Brought up at WWDC 2017 Advances in Networking, Part 1 is NEHotspotConfiguration which allows the app to specify and prompt to connect to a specific network.

The model backing the <Database> context has changed since the database was created

It means that there were some changes on the context which have not been executed. Please run Add-Migration first to generate the changes that we have done (the changes that we might not aware) And then run Update-Database

Easy way to print Perl array? (with a little formatting)

This might not be what you're looking for, but here's something I did for an assignment:

$" = ", ";
print "@ArrayName\n";

404 Not Found The requested URL was not found on this server

In Ubuntu I did not found httpd.conf, It may not exit longer now. Edit in apache2.conf file working for me.

cd /etc/apache2
sudo gedit apache2.conf

Here in apache2.conf change

<Directory /var/www/>
     Options Indexes FollowSymLinks
     AllowOverride None
     Require all granted


<Directory /var/www/>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted

How do I restart a program based on user input?

You can do this simply with a function. For example:

def script():
    # program code here...
    restart = raw_input("Would you like to restart this program?")
    if restart == "yes" or restart == "y":
    if restart == "n" or restart == "no":
        print "Script terminating. Goodbye."

Of course you can change a lot of things here. What is said, what the script will accept as a valid input, the variable and function names. You can simply nest the entire program in a user-defined function (Of course you must give everything inside an extra indent) and have it restart at anytime using this line of code: myfunctionname(). More on this here.

Modulo operator with negative values

From ISO14882:2011(e) 5.6-4:

The binary / operator yields the quotient, and the binary % operator yields the remainder from the division of the first expression by the second. If the second operand of / or % is zero the behavior is undefined. For integral operands the / operator yields the algebraic quotient with any fractional part discarded; if the quotient a/b is representable in the type of the result, (a/b)*b + a%b is equal to a.

The rest is basic math:

(-7/3) => -2
-2 * 3 => -6
so a%b => -1

(7/-3) => -2
-2 * -3 => 6
so a%b => 1

Note that

If both operands are nonnegative then the remainder is nonnegative; if not, the sign of the remainder is implementation-defined.

from ISO14882:2003(e) is no longer present in ISO14882:2011(e)

How to find my realm file?

First, I acknowledge that this is an Android thread but it is the first search result for this issue in general.

To open the most recently created Xcode Simulator Realm db in Realm Browser you can use this script in Automator or type it all in at the terminal. By using Automator, I have one-click access to my current realm.

    cd ~/Library/Developer/CoreSimulator/Devices/
    cd `ls -t | head -n 1`/data/Containers/Data/Application
    cd `ls -t | head -n 1`/Documents    
    open -a 'Realm Browser' ./default.realm

Install Realm Browser. In Automator, click New, select Run Shell Script, paste in code, change Realm Db name, Click Run to test, save file somewhere convenient for quick click access.

I don't know where I found this tip the first time but this thread reminded me how I was accessing my live data in the past.

Unrecognized escape sequence for path string containing backslashes

var foo = @"D:\Projects\Some\Kind\Of\Pathproblem\wuhoo.xml";

Print content of JavaScript object?

If you just want to have a string representation of an object, you could use the JSON.stringify function, using a JSON library.

Missing Microsoft RDLC Report Designer in Visual Studio

Below Different tools for Editing Rdlc report:

  1. ReportBuilder 3.0 : Microsoft Editor for Rdlc report.
  2. Microsoft® SQL Server® 2008 Express with Advanced Services: Another tool is to use Sql Server Business intelligence for reporting that can be installed with Sql Server Express with Advanced Sevices.
  3. fyiReporting: It is opensource tool presented for editing Rdlc reports .

Get the Id of current table row with Jquery

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">


<script type="text/javascript"><!--

function getVal(e) {
    var targ;
    if (!e) var e = window.event;
    if ( targ =;
    else if (e.srcElement) targ = e.srcElement;
    if (targ.nodeType == 3) // defeat Safari bug
        targ = targ.parentNode;


onload = function() {
    var t = document.getElementById("main").getElementsByTagName("td");
    for ( var i = 0; i < t.length; i++ )
        t[i].onclick = getVal;



<table id="main"><tr>


Getting the class name of an instance?

Good question.

Here's a simple example based on GHZ's which might help someone:

>>> class person(object):
        def init(self,name):
        def info(self)
            print "My name is {0}, I am a {1}".format(,self.__class__.__name__)
>>> bob = person(name='Robert')
My name is Robert, I am a person

SELECT list is not in GROUP BY clause and contains nonaggregated column .... incompatible with sql_mode=only_full_group_by

> sudo nano /etc/mysql/my.cnf

Enter below

sql_mode = ""

Ctrl + O => Y = Ctrl + X

> sudo service mysql restart

Python: Append item to list N times

l = []
x = 0

Numpy array dimensions

The shape method requires that a be a Numpy ndarray. But Numpy can also calculate the shape of iterables of pure python objects:


How to make a shape with left-top round rounded corner and left-bottom rounded corner?

You can also use extremely small numbers for your radius'.

  android:bottomRightRadius="0.1dp" android:bottomLeftRadius="2dp" 
 android:topLeftRadius="2dp" android:topRightRadius="0.1dp" />

Copy file from source directory to binary directory using CMake

If you want to put the content of example into install folder after build:


try add the following to your CMakeLists.txt:

install(DIRECTORY example/ DESTINATION example)

How to access private data members outside the class without making "friend"s?

this guy's blog shows you how to do it using templates. With some modifications, you can adapt this method to access a private data member, although I found it tricky despite having 10+ years experience.

I wanted to point out like everyone else, that there is an extremely few number of cases where doing this is legitimate. However, I want to point out one: I was writing unit tests for a software suite. A federal regulatory agency requires every single line of code to be exercised and tested, without modifying the original code. Due to (IMHO) poor design, a static constant was in the 'private' section, but I needed to use it in the unit test. So the method seemed to me like the best way to do it.

I'm sure the way could be simplified, and I'm sure there are other ways. I'm not posting this for the OP, since it's been 5 months, but hopefully this will be useful to some future googler.

What's the C# equivalent to the With statement in VB?

Aside from object initializers (usable only in constructor calls), the best you can get is:

var it = Stuff.Elements.Foo;
it.Name = "Bob Dylan";
it.Age = 68;

Writing an input integer into a cell

I've done this kind of thing with a form that contains a TextBox.

So if you wanted to put this in say cell H1, then use:

ActiveSheet.Range("H1").Value = txtBoxName.Text

Use PHP composer to clone git repo

In my case, I use Symfony2.3.x and the minimum-stability parameter is by default "stable" (which is good). I wanted to import a repo not in packagist but had the same issue "Your requirements could not be resolved to an installable set of packages.". It appeared that the composer.json in the repo I tried to import use a minimum-stability "dev".

So to resolve this issue, don't forget to verify the minimum-stability. I solved it by requiring a dev-master version instead of master as stated in this post.

How to connect from windows command prompt to mysql command line

You are logging in incorrectly; you should not include = in your login. So to log in, type:

mysql.exe -uroot -padmin

If that doesn't work, then you may not have your system configured. If so, then here's a good tutorial on getting started with the MySQL prompt:

How to improve a case statement that uses two columns

Just change your syntax ever so slightly:

CASE WHEN STATE = 2 AND RetailerProcessType = 1 THEN '"AUTHORISED"'
     WHEN STATE = 1 AND RetailerProcessType = 2 THEN '"PENDING"'
     WHEN STATE = 2 AND RetailerProcessType = 2 THEN '"AUTHORISED"'

If you don't put the field expression before the CASE statement, you can put pretty much any fields and comparisons in there that you want. It's a more flexible method but has slightly more verbose syntax.

How to make for loops in Java increase by increments other than 1

You can also write code as

for(int i=0;i<n;i++)
      i=i+2;//cause you want to increment i by 3 

how to make a cell of table hyperlink

Easy with onclick-function and a javascript link:

<td onclick="location.href='yourpage.html'">go to yourpage</td>

How to use ESLint with Jest

Add environment only for __tests__ folder

You could add a .eslintrc.yml file in your __tests__ folders, that extends you basic configuration:

extends: <relative_path to .eslintrc>
    jest: true

If you have only one __tests__folder, this solution is the best since it scope jest environment only where it is needed.

Dealing with many test folders

If you have more test folders (OPs case), I'd still suggest to add those files. And if you have tons of those folders can add them with a simple zsh script:

#!/usr/bin/env zsh

for folder in **/__tests__/ ;do
    count=$(($(tr -cd '/' <<< $folder | wc -c)))
    echo $folder : $count
    cat <<EOF > $folder.eslintrc.yml
extends: $(printf '../%.0s' {1..$count}).eslintrc
    jest: true

This script will look for __tests__ folders and add a .eslintrc.yml file with to configuration shown above. This script has to be launched within the folder containing your parent .eslintrc.

Flask SQLAlchemy query, specify column names

You can use load_only function:

from sqlalchemy.orm import load_only

fields = ['name', 'addr', 'phone', 'url']
companies = session.query(SomeModel).options(load_only(*fields)).all()

How to call a JavaScript function from PHP?

You may not be able to directly do this, but the Xajax library is pretty close to what you want. I will demonstrate with an example. Here's a button on a webpage:

<button onclick="xajax_addCity();">Add New City</button> 

Our intuitive guess would be that xajax_addCity() is a Javascript function, right? Well, right and wrong. The cool thing Xajax allows is that we don't have any JS function called xajax_addCity(), but what we do have is a PHP function called addCity() that can do whatever PHP does!

<?php function addCity() { echo "Wow!"; } ?>

Think about it for a minute. We are virtually invoking a PHP function from Javascript code! That over-simplified example was just to whet the appetite, a better explanation is on the Xajax site, have fun!

How to rename with prefix/suffix?

I know there is great answers here but I found no reference to handle filename extensions when adding suffix.

I needed to add '_en' suffix to all wav files in a folder before the file extension.

The magic is here: %.*

for filename in *.wav; do mv $filename ${filename%.*}_en.wav; done;

If you need to handle different file extensions, check this answer. A bit less intuitive.

How do you convert Html to plain text?

I had the same question, just my html had a simple pre-known layout, like:


So I ended up using such simple code:

string.Join (Environment.NewLine, XDocument.Parse (html).Root.Elements ().Select (el => el.Value))

Which outputs:


Java integer list

code that works, but output is:



    List<Integer> myCoords = new ArrayList<Integer>();
    for (Integer number : myCoords) {
        try {
        } catch (InterruptedException e) {

iPhone - Grand Central Dispatch main thread

One place where it's useful is for UI activities, like setting a spinner before a lengthy operation:

- (void) handleDoSomethingButton{

    [mySpinner startAnimating];

    (do something lengthy)
    [mySpinner stopAnimating];

will not work, because you are blocking the main thread during your lengthy thing and not letting UIKit actually start the spinner.

- (void) handleDoSomethingButton{
     [mySpinner startAnimating];

     dispatch_async (dispatch_get_main_queue(), ^{
          (do something lengthy)
          [mySpinner stopAnimating];

will return control to the run loop, which will schedule UI updating, starting the spinner, then will get the next thing off the dispatch queue, which is your actual processing. When your processing is done, the animation stop is called, and you return to the run loop, where the UI then gets updated with the stop.

Get environment variable value in Dockerfile

So you can do: cat Dockerfile | envsubst | docker build -t my-target -

Then have a Dockerfile with something like:


I guess there might be a problem with some special characters, but this works for most cases at least.

The controller for path was not found or does not implement IController

in my case, the problem was that the controller class has not been publicly announced.

class WorkPlaceController : Controller

the solution was

public class WorkPlaceController : Controller

How do I clear/delete the current line in terminal?

Another nice complete list:

TERINAL Shortcuts Lists:

Left            Move back one character
Right           Move forward one character
Ctrl+b          Move back one character
Ctrl+f          Move forward one character

Alt+Left        Move back one word
Alt+Right       Move forward one word
Alt+b           Move back one word
Alt+f           Move forward one word

Cmd+Left        Move cursor to start of line
Cmd+Right       Move cursor to end of line
Ctrl+a          Move cursor to start of line
Ctrl+e          Move cursor to end of line

Ctrl+d          Delete character after cursor
Backspace       Delete character before cursor

Alt+Backspace   Delete word before cursor
Ctrl+w          Delete word before cursor
Alt+w           Delete word before the cursor
Alt+d           Delete word after the cursor

Cmd+Backspace   Delete everything before the cursor
Ctrl+u          Delete everything before the cursor
Ctrl+k          Delete everything after the cursor

Ctrl+l          Clear the terminal

Ctrl+c          Cancel the command
Ctrl+y          Paste the last deleted command
Ctrl+_          Undo

Ctrl+r          Search command in history - type the search term
Ctrl+j          End the search at current history entry and run command
Ctrl+g          Cancel the search and restore original line

Up              previous command from the History
Down            Next command from the History
Ctrl+n          Next command from the History
Ctrl+p          previous command from the History

Ctrl+xx         Toggle between first and current position

JavaScript get window X/Y position for scroll

Using pure javascript you can use Window.scrollX and Window.scrollY

window.addEventListener("scroll", function(event) {
    var top = this.scrollY,
        left =this.scrollX;
}, false);


The pageXOffset property is an alias for the scrollX property, and The pageYOffset property is an alias for the scrollY property:

window.pageXOffset == window.scrollX; // always true
window.pageYOffset == window.scrollY; // always true

Here is a quick demo

window.addEventListener("scroll", function(event) {_x000D_
    var top = this.scrollY,_x000D_
        left = this.scrollX;_x000D_
    var horizontalScroll = document.querySelector(".horizontalScroll"),_x000D_
        verticalScroll = document.querySelector(".verticalScroll");_x000D_
    horizontalScroll.innerHTML = "Scroll X: " + left + "px";_x000D_
      verticalScroll.innerHTML = "Scroll Y: " + top + "px";_x000D_
}, false);
*{box-sizing: border-box}_x000D_
:root{height: 200vh;width: 200vw}_x000D_
    position: fixed;_x000D_
    background: black;_x000D_
    color: green;_x000D_
    height: 64px;_x000D_
.wrapper div{_x000D_
    display: inline;_x000D_
    width: 50%;_x000D_
    float: left;_x000D_
    text-align: center;_x000D_
    line-height: 64px_x000D_
.horizontalScroll{color: orange}
<div class=wrapper>_x000D_
    <div class=horizontalScroll>Scroll (x,y) to </div>_x000D_
    <div class=verticalScroll>see me in action</div>_x000D_

How do I execute a stored procedure once for each row returned by query?

Use a table variable or a temporary table.

As has been mentioned before, a cursor is a last resort. Mostly because it uses lots of resources, issues locks and might be a sign you're just not understanding how to use SQL properly.

Side note: I once came across a solution that used cursors to update rows in a table. After some scrutiny, it turned out the whole thing could be replaced with a single UPDATE command. However, in this case, where a stored procedure should be executed, a single SQL-command won't work.

Create a table variable like this (if you're working with lots of data or are short on memory, use a temporary table instead):

    id INT IDENTITY(1,1),
    parent NVARCHAR(128),
    child NVARCHAR(128));

The id is important.

Replace parent and child with some good data, e.g. relevant identifiers or the whole set of data to be operated on.

Insert data in the table, e.g.:

INSERT INTO @menus (parent, child) 
  VALUES ('Some name',  'Child name');
INSERT INTO @menus (parent,child) 
  VALUES ('Some other name', 'Some other child name');

Declare some variables:

DECLARE @id INT = 1;
DECLARE @parentName NVARCHAR(128);
DECLARE @childName NVARCHAR(128);

And finally, create a while loop over the data in the table:

    SELECT @parentName = parent,
           @childName = child 
        FROM @menus WHERE id = @id;

    EXEC myProcedure @parent=@parentName, @child=@childName;

    SELECT @id = MIN(id) FROM @menus WHERE id > @id;

The first select fetches data from the temporary table. The second select updates the @id. MIN returns null if no rows were selected.

An alternative approach is to loop while the table has rows, SELECT TOP 1 and remove the selected row from the temp table:

    SELECT TOP 1 @menuID = menuID FROM @menuIDs;

    EXEC myProcedure @menuID=@menuID;

    DELETE FROM @menuIDs WHERE menuID = @menuID;

Change URL parameters

I've extended Sujoy's code to make up a function.

function updateURLParameter(url, param, paramVal){
    var newAdditionalURL = "";
    var tempArray = url.split("?");
    var baseURL = tempArray[0];
    var additionalURL = tempArray[1];
    var temp = "";
    if (additionalURL) {
        tempArray = additionalURL.split("&");
        for (var i=0; i<tempArray.length; i++){
            if(tempArray[i].split('=')[0] != param){
                newAdditionalURL += temp + tempArray[i];
                temp = "&";

    var rows_txt = temp + "" + param + "=" + paramVal;
    return baseURL + "?" + newAdditionalURL + rows_txt;

Function Calls:

var newURL = updateURLParameter(window.location.href, 'locId', 'newLoc');
newURL = updateURLParameter(newURL, 'resId', 'newResId');

window.history.replaceState('', '', updateURLParameter(window.location.href, "param", "value"));

Updated version that also take care of the anchors on the URL.

function updateURLParameter(url, param, paramVal)
    var TheAnchor = null;
    var newAdditionalURL = "";
    var tempArray = url.split("?");
    var baseURL = tempArray[0];
    var additionalURL = tempArray[1];
    var temp = "";

    if (additionalURL) 
        var tmpAnchor = additionalURL.split("#");
        var TheParams = tmpAnchor[0];
            TheAnchor = tmpAnchor[1];
            additionalURL = TheParams;

        tempArray = additionalURL.split("&");

        for (var i=0; i<tempArray.length; i++)
            if(tempArray[i].split('=')[0] != param)
                newAdditionalURL += temp + tempArray[i];
                temp = "&";
        var tmpAnchor = baseURL.split("#");
        var TheParams = tmpAnchor[0];
            TheAnchor  = tmpAnchor[1];

            baseURL = TheParams;

        paramVal += "#" + TheAnchor;

    var rows_txt = temp + "" + param + "=" + paramVal;
    return baseURL + "?" + newAdditionalURL + rows_txt;

Config Error: This configuration section cannot be used at this path

To fix this open up the IIS Express applicationhost.config. This file is stored at C:\Users[your user name]\Documents\IISExpress\config\applicationhost.config

Update for VS2015+: config file location is $(solutionDir).vs\config\applicationhost.config

Look for the following lines

<section name="windowsAuthentication" overrideModeDefault="Deny" />
<section name="anonymousAuthentication" overrideModeDefault="Deny" />
<add name="WindowsAuthenticationModule" lockItem="true" />
<add name="AnonymousAuthenticationModule" lockItem="true" />

Change those lines to

<section name="windowsAuthentication" overrideModeDefault="Allow" />
<section name="anonymousAuthentication" overrideModeDefault="Allow" />
<add name="WindowsAuthenticationModule" lockItem="false" />
<add name="AnonymousAuthenticationModule" lockItem="false" />

Save it and refresh Page.

How to install psycopg2 with "pip" on Python?

I was having this problem, the main reason was with 2 equal versions installed. One by and one by HomeBrew.

If you choose to keep only the APP:

brew unlink postgresql
pip3 install psycopg2

Joining three tables using MySQL

Just adding a point to previous answers that in MySQL we can either use

table_factor syntax 


joined_table syntax

mysql documentation

Table_factor example

FROM products prd, buyers b

Joined Table example

FROM products prd
 left join buyers b on =;

FYI: Please ignore the fact the the left join on the joined table example doesnot make much sense (in reality we would use some sort of join table to link buyer to the product table instead of saving buyerID in product table).

PHP: Count a stdClass object

The count function is meant to be used on

  1. Arrays
  2. Objects that are derived from classes that implement the countable interface

A stdClass is neither of these. The easier/quickest way to accomplish what you're after is

$count = count(get_object_vars($some_std_class_object));

This uses PHP's get_object_vars function, which will return the properties of an object as an array. You can then use this array with PHP's count function.

size of struct in C

Aligning to 6 bytes is not weird, because it is aligning to addresses multiple to 4.

So basically you have 34 bytes in your structure and the next structure should be placed on the address, that is multiple to 4. The closest value after 34 is 36. And this padding area counts into the size of the structure.

jquery select option click handler

its working for me

<select name="" id="select">
    <option value="1"></option>
    <option value="2"></option>
    <option value="3"></option>

    $("#select > option").on("click", function () {

How to get height of <div> in px dimension

There is a built-in method to get the bounding rectangle: Element.getBoundingClientRect.

The result is the smallest rectangle which contains the entire element, with the read-only left, top, right, bottom, x, y, width, and height properties.

See the example below:

let innerBox = document.getElementById("myDiv").getBoundingClientRect().height;_x000D_
document.getElementById("data_box").innerHTML = "height: " + innerBox;
body {_x000D_
  margin: 0;_x000D_
.relative {_x000D_
  width: 220px;_x000D_
  height: 180px;_x000D_
  position: relative;_x000D_
  background-color: purple;_x000D_
.absolute {_x000D_
  position: absolute;_x000D_
  top: 30px;_x000D_
  left: 20px;_x000D_
  background-color: orange;_x000D_
  padding: 30px;_x000D_
  overflow: hidden;_x000D_
#myDiv {_x000D_
  margin: 20px;_x000D_
  padding: 10px;_x000D_
  color: red;_x000D_
  font-weight: bold;_x000D_
  background-color: yellow;_x000D_
#data_box {_x000D_
  font: 30px arial, sans-serif;_x000D_
Get height of <mark>myDiv</mark> in px dimension:_x000D_
<div id="data_box"></div>_x000D_
<div class="relative">_x000D_
  <div class="absolute">_x000D_
    <div id="myDiv">myDiv</div>_x000D_


use Illuminate\Database\Eloquent\Builder;

$query = Customers::with('orders');
$query = $query->whereHas('orders', function (Builder $query) use ($request) {
     $query = $query->where('orders.customer_id', 'NULL') 
    $query = $query->get();

Angular @ViewChild() error: Expected 2 arguments, but got 1

Use this

@ViewChild(ChildDirective, {static: false}) Component

ERROR 1044 (42000): Access denied for 'root' With All Privileges

First, Identify the user you are logged in as:

 select user();
 select current_user();

The result for the first command is what you attempted to login as, the second is what you actually connected as. Confirm that you are logged in as root@localhost in mysql.

Grant_priv to root@localhost. Here is how you can check.

mysql> SELECT host,user,password,Grant_priv,Super_priv FROM mysql.user;
| host      | user             | password                                  | Grant_priv | Super_priv |
| localhost | root             | ***************************************** | N          | Y          |
| localhost | debian-sys-maint | ***************************************** | Y          | Y          |
| localhost | staging          | ***************************************** | N          | N          |

You can see that the Grant_priv is set to N for root@localhost. This needs to be Y. Below is how to fixed this:

UPDATE mysql.user SET Grant_priv='Y', Super_priv='Y' WHERE User='root';
GRANT ALL ON *.* TO 'root'@'localhost';

I logged back in, it was fine.

Why doesn't importing java.util.* include Arrays and Lists?

The difference between

import java.util.*;


import java.util.*;
import java.util.List;
import java.util.Arrays;

becomes apparent when the code refers to some other List or Arrays (for example, in the same package, or also imported generally). In the first case, the compiler will assume that the Arrays declared in the same package is the one to use, in the latter, since it is declared specifically, the more specific java.util.Arrays will be used.

WPF Label Foreground Color

I checked your XAML, it works fine - e.g. both labels have a gray foreground.
My guess is that you have some style which is affecting the way it looks...

Try moving your XAML to a brand-new window and see for yourself... Then, check if you have any themes or styles (in the Window.Resources for instance) which might be affecting the labels...

How to check if an item is selected from an HTML drop down list?

<label class="paylabel" for="cardtype">Card Type:</label>
<select id="cardtype" name="cards">
<option value="selectcard">--- Please select ---</option>
<option value="mastercard" selected="selected">Mastercard</option>
<option value="maestro">Maestro</option>
<option value="solo">Solo (UK only)</option>
<option value="visaelectron">Visa Electron</option>
<option value="visadebit">Visa Debit</option>
</select><br />

    var card = document.getElementById("cardtype");
    if (card.options[card.selectedIndex].value == 'selectcard') {
          alert("Please select a card type");
          return false;

Android DialogFragment vs Dialog

Yes, use DialogFragment and in onCreateDialog you can simply use an AlertDialog builder anyway to create a simple AlertDialog with Yes/No confirmation buttons. Not very much code at all.

With regards handling events in your fragment there would be various ways of doing it but I simply define a message Handler in my Fragment, pass it into the DialogFragment via its constructor and then pass messages back to my fragment's handler as approprirate on the various click events. Again various ways of doing that but the following works for me.

In the dialog hold a message and instantiate it in the constructor:

private Message okMessage;
okMessage = handler.obtainMessage(MY_MSG_WHAT, MY_MSG_OK);

Implement the onClickListener in your dialog and then call the handler as appropriate:

public void onClick(.....
    if (which == DialogInterface.BUTTON_POSITIVE) {
        final Message toSend = Message.obtain(okMessage);


And as Message is parcelable you can save it out in onSaveInstanceState and restore it

outState.putParcelable("okMessage", okMessage);

Then in onCreate

if (savedInstanceState != null) {
    okMessage = savedInstanceState.getParcelable("okMessage");

Where is my m2 folder on Mac OS X Mavericks

If you search directly it won't appear so please follow as below steps to see .M2 repository path.

Go-> Find folder ->  type this "~/.m2" and click go

If Maven is already installed and used, the .m2 will be listed.


Where does Oracle SQL Developer store connections?

For OS X my connection.xml files are in


Update row values where certain condition is met in pandas

I think you can use loc if you need update two columns to same value:

df1.loc[df1['stream'] == 2, ['feat','another_feat']] = 'aaaa'
print df1
   stream        feat another_feat
a       1  some_value   some_value
b       2        aaaa         aaaa
c       2        aaaa         aaaa
d       3  some_value   some_value

If you need update separate, one option is use:

df1.loc[df1['stream'] == 2, 'feat'] = 10
print df1
   stream        feat another_feat
a       1  some_value   some_value
b       2          10   some_value
c       2          10   some_value
d       3  some_value   some_value

Another common option is use numpy.where:

df1['feat'] = np.where(df1['stream'] == 2, 10,20)
print df1
   stream  feat another_feat
a       1    20   some_value
b       2    10   some_value
c       2    10   some_value
d       3    20   some_value

EDIT: If you need divide all columns without stream where condition is True, use:

print df1
   stream  feat  another_feat
a       1     4             5
b       2     4             5
c       2     2             9
d       3     1             7

#filter columns all without stream
cols = [col for col in df1.columns if col != 'stream']
print cols
['feat', 'another_feat']

df1.loc[df1['stream'] == 2, cols ] = df1 / 2
print df1
   stream  feat  another_feat
a       1   4.0           5.0
b       2   2.0           2.5
c       2   1.0           4.5
d       3   1.0           7.0

If working with multiple conditions is possible use multiple numpy.where or

df0 = pd.DataFrame({'Col':[5,0,-6]})

df0['New Col1'] = np.where((df0['Col'] > 0), 'Increasing', 
                          np.where((df0['Col'] < 0), 'Decreasing', 'No Change'))

df0['New Col2'] =[df0['Col'] > 0, df0['Col'] < 0],
                            ['Increasing',  'Decreasing'], 
                            default='No Change')

print (df0)
   Col    New Col1    New Col2
0    5  Increasing  Increasing
1    0   No Change   No Change
2   -6  Decreasing  Decreasing

Remove spaces from std::string in C++

The best thing to do is to use the algorithm remove_if and isspace:

remove_if(str.begin(), str.end(), isspace);

Now the algorithm itself can't change the container(only modify the values), so it actually shuffles the values around and returns a pointer to where the end now should be. So we have to call string::erase to actually modify the length of the container:

str.erase(remove_if(str.begin(), str.end(), isspace), str.end());

We should also note that remove_if will make at most one copy of the data. Here is a sample implementation:

template<typename T, typename P>
T remove_if(T beg, T end, P pred)
    T dest = beg;
    for (T itr = beg;itr != end; ++itr)
        if (!pred(*itr))
            *(dest++) = *itr;
    return dest;

OR, AND Operator

Logical OR is ||, logical AND is &&. If you need the negation NOT, prefix your expression with !.


X = (A && B) || C || !D;

Then X will be true when either A and B are true or if C is true or if D is not true (i.e. false).

If you wanted bit-wise AND/OR/NOT, you would use &, | and ~. But if you are dealing with boolean/truth values, you do not want to use those. They do not provide short-circuit evaluation for example due to the way a bitwise operation works.

Why does this SQL code give error 1066 (Not unique table/alias: 'user')?

You need to give the user table an alias the second time you join to it


SELECT article . * , section.title, category.title,, 
FROM article 
INNER JOIN section ON article.section_id = 
INNER JOIN category ON article.category_id = 
INNER JOIN user ON article.author_id = 
LEFT JOIN user u2 ON article.modified_by = 
WHERE = '1'

Can I write into the console in a unit test? If yes, why doesn't the console window open?

There are several ways to write output from a Visual Studio unit test in C#:

  • Console.Write - The Visual Studio test harness will capture this and show it when you select the test in the Test Explorer and click the Output link. Does not show up in the Visual Studio Output Window when either running or debugging a unit test (arguably this is a bug).
  • Debug.Write - The Visual Studio test harness will capture this and show it in the test output. Does appear in the Visual Studio Output Window when debugging a unit test, unless Visual Studio Debugging options are configured to redirect Output to the Immediate Window. Nothing will appear in the Output (or Immediate) Window if you simply run the test without debugging. By default only available in a Debug build (that is, when DEBUG constant is defined).
  • Trace.Write - The Visual Studio test harness will capture this and show it in the test output. Does appear in the Visual Studio Output (or Immediate) Window when debugging a unit test (but not when simply running the test without debugging). By default available in both Debug and Release builds (that is, when TRACE constant is defined).

Confirmed in Visual Studio 2013 Professional.

Accessing Redux state in an action creator?

I would like to point out that it is not that bad to read from the store -- it might be just much more convenient to decide what should be done based on the store, than to pass everything to the component and then as a parameter of a function. I agree with Dan completely, that it is much better not to use store as a singletone, unless you are 100% sure that you will use only for client-side rendering (otherwise hard to trace bugs might appear).

I have created a library recently to deal with verbosity of redux, and I think it is a good idea to put everything in the middleware, so you have everyhing as a dependency injection.

So, your example will look like that:

import { createSyncTile } from 'redux-tiles';

const someTile = createSyncTile({
  type: ['some', 'tile'],
  fn: ({ params, selectors, getState }) => {
    return {
      items: selectors.another.tile(getState())

However, as you can see, we don't really modify data here, so there is a good chance that we can just use this selector in other place to combine it somewhere else.

How do I access named capturing groups in a .NET Regex?

Use the group collection of the Match object, indexing it with the capturing group name, e.g.

foreach (Match m in mc){

Difference between xcopy and robocopy

The differences I could see is that Robocopy has a lot more options, but I didn't find any of them particularly helpful unless I'm doing something special.

I did some benchmarking of several copy routines and found XCOPY and ROBOCOPY to be the fastest, but to my surprise, XCOPY consistently edged out Robocopy.

It's ironic that robocopy retries a copy that fails, but it also failed a lot in my benchmark tests, where xcopy never did.

I did full file (byte by byte) file compares after my benchmark tests.

Here are the switches I used with robocopy in my tests:

 **"/E /R:1 /W:1 /NP /NFL /NDL"**.  

If anyone knows a faster combination (other than removing /E, which I need), I'd love to hear.

Another interesting/disappointing thing with robocopy is that if a copy does fail, by default it retries 1,000,000 times with a 30 second delay between each try. If you are running a long batch file unattended, you may be very disappointed when you come back after a few hours to find it's still trying to copy a particular file.

The /R and /W switches let you change this behavior.

  • With /R you can tell it how many times to retry,
  • /W let's you specify the wait time before retries.

If there's a way to attach files here, I can share my results.

  • My tests were all done on the same computer and
  • copied files from one external drive to another external,
  • both on USB 3.0 ports.

I also included FastCopy and Windows Copy in my tests and each test was run 10 times. Note, the differences were pretty significant. The 95% confidence intervals had no overlap.

How to drop a table if it exists?

Have seen so many that don't really work. when a temp table is created it must be deleted from the tempdb!

The only code that works is:

IF OBJECT_ID('tempdb..#tempdbname') IS NOT NULL     --Remove dbo here 
    DROP TABLE #tempdbname   -- Remoeve "tempdb.dbo"

Apache won't start in wamp

I had the same problem. My port 80 was not in use.

After thorough research, all I did was to download Update for Universal C Runtime.

Once installed and my PC restarted, all was OK.

How to implement my very own URI scheme on Android

Complementing the @DanielLew answer, to get the values of the parameteres you have to do this:

URI example: myapp://path/to/what/i/want?keyOne=valueOne&keyTwo=valueTwo

in your activity:

Intent intent = getIntent();
if (Intent.ACTION_VIEW.equals(intent.getAction())) {
  Uri uri = intent.getData();
  String valueOne = uri.getQueryParameter("keyOne");
  String valueTwo = uri.getQueryParameter("keyTwo");

What is the difference between background and background-color

The difference is that the background shorthand property sets several background-related properties. It sets them all, even if you only specify e.g. a color value, since then the other properties are set to their initial values, e.g. background-image to none.

This does not mean that it would always override any other settings for those properties. This depends on the cascade according to the usual, generally misunderstood rules.

In practice, the shorthand tends to be somewhat safer. It is a precaution (not complete, but useful) against accidentally getting some unexpected background properties, such as a background image, from another style sheet. Besides, it’s shorter. But you need to remember that it really means “set all background properties”.

What is the difference between C++ and Visual C++?

Key differences:

C++ is a general-purpose programming language, but is developed from the originally C programming language. It was developed by Bjarne Stroustrup at Bell Labs starting in 1979. C++ was originally named C with Classes. It was renamed C++ in 1983.

Visual C++, on the other hand, is not a programming language at all. It is in fact a development environment. It is an “integrated development environment (IDE) product from Microsoft for the C, C++, and C++/CLI programming languages.” Microsoft Visual C++, also known as MSVC or VC++, is sold as part of the Microsoft Visual Studio app.

ASP.NET MVC Page Won't Load and says "The resource cannot be found"

You should carefully review your Route Values.

   "Default", // Route name
   "{controller}/{action}/{id}", // URL with parameters
   new { controller = "Home", action = "Index", id = UrlParameter.Optional } 

In this case, ensure you have your Controller 'Home' as the application will fail to load if there is no HomeController with Index Action. In My case I had HomesController and I missed the 's' infront of the Home. I Fixed the Name mismatch and this resolved the issue on both my local environment and on my server.

Debugging WebSocket in Google Chrome

Chrome Canary and Chromium now have WebSocket message frame inspection feature. Here are the steps to test it quickly:

  1. Navigate to the WebSocket Echo demo, hosted on the site.
  2. Turn on the Chrome Developer Tools.
  3. Click Network, and to filter the traffic shown by the Dev Tools, click WebSockets.
  4. In the Echo demo, click Connect. On the Headers tab in Google Dev Tool you can inspect the WebSocket handshake.
  5. Click the Send button in the Echo demo.
  6. THIS STEP IS IMPORTANT: To see the WebSocket frames in the Chrome Developer Tools, under Name/Path, click the entry, representing your WebSocket connection. This refreshes the main panel on the right and makes the WebSocket Frames tab show up with the actual WebSocket message content.

Note: Every time you send or receive new messages, you have to refresh the main panel by clicking on the entry on the left.

I also posted the steps with screen shots and video.

My recently published book, The Definitive Guide to HTML5 WebSocket, also has a dedicated appendix covering the various inspection tools, including Chrome Dev Tools, Chrome net-internals, and Wire Shark.

How to write "Html.BeginForm" in Razor

The following code works fine:

@using (Html.BeginForm("Upload", "Upload", FormMethod.Post, 
                                      new { enctype = "multipart/form-data" }))
        Select a file <input type="file" name="file" />
        <input type="submit" value="Upload" />

and generates as expected:

<form action="/Upload/Upload" enctype="multipart/form-data" method="post">    
        Select a file <input type="file" name="file" />
        <input type="submit" value="Upload" />

On the other hand if you are writing this code inside the context of other server side construct such as an if or foreach you should remove the @ before the using. For example:

@if (SomeCondition)
    using (Html.BeginForm("Upload", "Upload", FormMethod.Post, 
                                      new { enctype = "multipart/form-data" }))
            Select a file <input type="file" name="file" />
            <input type="submit" value="Upload" />

As far as your server side code is concerned, here's how to proceed:

public ActionResult Upload(HttpPostedFileBase file) 
    if (file != null && file.ContentLength > 0) 
        var fileName = Path.GetFileName(file.FileName);
        var path = Path.Combine(Server.MapPath("~/content/pics"), fileName);
    return RedirectToAction("Upload");

Difference between Inheritance and Composition

Are Composition and Inheritance the same?

They are not same.

Composition : It enables a group of objects have to be treated in the same way as a single instance of an object. The intent of a composite is to "compose" objects into tree structures to represent part-whole hierarchies

Inheritance: A class inherits fields and methods from all its superclasses, whether direct or indirect. A subclass can override methods that it inherits, or it can hide fields or methods that it inherits.

If I want to implement the composition pattern, how can I do that in Java?

Wikipedia article is good enough to implement composite pattern in java.

enter image description here

Key Participants:


  1. Is the abstraction for all components, including composite ones
  2. Declares the interface for objects in the composition


  1. Represents leaf objects in the composition
  2. Implements all Component methods


  1. Represents a composite Component (component having children)
  2. Implements methods to manipulate children
  3. Implements all Component methods, generally by delegating them to its children

Code example to understand Composite pattern:

import java.util.List;
import java.util.ArrayList;

interface Part{
    public double getPrice();
    public String getName();
class Engine implements Part{
    String name;
    double price;
    public Engine(String name,double price){ = name;
        this.price = price;
    public double getPrice(){
        return price;
    public String getName(){
        return name;
class Trunk implements Part{
    String name;
    double price;
    public Trunk(String name,double price){ = name;
        this.price = price;
    public double getPrice(){
        return price;
    public String getName(){
        return name;
class Body implements Part{
    String name;
    double price;
    public Body(String name,double price){ = name;
        this.price = price;
    public double getPrice(){
        return price;
    public String getName(){
        return name;
class Car implements Part{
    List<Part> parts;
    String name;

    public Car(String name){ = name;
        parts = new ArrayList<Part>();
    public void addPart(Part part){
    public String getName(){
        return name;
    public String getPartNames(){
        StringBuilder sb = new StringBuilder();
        for ( Part part: parts){
            sb.append(part.getName()).append(" ");
        return sb.toString();
    public double getPrice(){
        double price = 0;
        for ( Part part: parts){
            price += part.getPrice();
        return price;

public class CompositeDemo{
    public static void main(String args[]){
        Part engine = new Engine("DiselEngine",15000);
        Part trunk = new Trunk("Trunk",10000);
        Part body = new Body("Body",12000);

        Car car = new Car("Innova");

        double price = car.getPrice();

        System.out.println("Car name:"+car.getName());
        System.out.println("Car parts:"+car.getPartNames());
        System.out.println("Car price:"+car.getPrice());



Car name:Innova
Car parts:DiselEngine Trunk Body
Car price:37000.0


  1. Part is a leaf
  2. Car contains many Parts
  3. Different Parts of the car have been added to Car
  4. The price of Car = sum of ( Price of each Part )

Refer to below question for Pros and Cons of Composition and Inheritance.

Prefer composition over inheritance?

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

First off, it's helpful to create a database named the same as your current use, to prevent the error when you just want to use the default database and create new tables without declaring the name of a db explicitly.

Replace "skynotify" with your username:

psql -d postgres -c "CREATE DATABASE skynotify ENCODING 'UTF-8';"

-d explicitly declares which database to use as the default for SQL statements that don't explicitly include a db name during this interactive session.


You must connect to an existing database to use psql interactively. Fortunately, you can ask psql for a list of databases:

psql -l


                                          List of databases
               Name               | Owner  | Encoding |   Collate   |    Ctype    | Access privileges 
 skynotify                        | skynotify | UTF8     | en_US.UTF-8 | en_US.UTF-8 | 
 myapp_dev                        | skynotify | UTF8     | en_US.UTF-8 | en_US.UTF-8 | 
 postgres                         | skynotify | UTF8     | en_US.UTF-8 | en_US.UTF-8 | 
 ruby-getting-started_development | skynotify | UTF8     | en_US.UTF-8 | en_US.UTF-8 | 
 template0                        | skynotify | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/skynotify          +
                                  |           |          |             |             | skynotify=CTc/skynotify
 template1                        | skynotify | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/skynotify          +
                                  |           |          |             |             | skynotify=CTc/skynotify
(6 rows)

This does NOT start the interactive console, it just outputs a text based table to the terminal.

As another answers says, postgres is always created, so you should use it as your failsafe database when you just want to get the console started to work on other databases. If it isn't there, then list the databases and then use any one of them.

In a similar fashion, select tables from a database:

psql -d postgres -c "\dt;"

My "postgres" database has no tables, but any database that does will output a text based table to the terminal (standard out).

And for completeness, we can select all rows from a table too:

psql -d ruby-getting-started_development -c "SELECT * FROM widgets;"


 id | name | description | stock | created_at | updated_at 
(0 rows)

Even if there are zero rows returned, you'll get the field names.

If your tables have more than a dozen rows, or you're not sure, it'll be more useful to start with a count of rows to understand how much data is in your database:

 psql -d ruby-getting-started_development -c "SELECT count(*) FROM widgets;"


(1 row)

And don't that that "1 row" confuse you, it just represents how many rows are returned by the query, but the 1 row contains the count you want, which is 0 in this example.

NOTE: a db created without an owner defined will be owned by the current user.

Eclipse/Java code completion not working

Maybe this helps other people who come across the same issue.

My setup: old Gradle project (version Gradle 2.12) made by someone else, imported using the Gradle Import Wizard into STS (Eclipse Oxygen.2 (4.7.2)).

Code completion did not work either (and I still have hollow Js at the Java files), but at least I got the code completion to work by doing:

  • right click on the project folder > Properties > Gradle > Configure Workspace Settings > Java > Editor > Content Assist > Advanced
  • check "Java Proposals in upper window.
  • 2x Apply & Close

Drawing an SVG file on a HTML5 canvas

Mozilla has a simple way for drawing SVG on canvas called "Drawing DOM objects into a canvas"

Keyword not supported: "data source" initializing Entity Framework Context

The real reason you were getting this error is because of the &quot; values in your connection string.

If you replace those with single quotes then it will work fine.

(Posted so others can get the fix faster than I did.)

Apache server keeps crashing, "caught SIGTERM, shutting down"

from this page:

I found this info:

The mod_fastcgi process manager isn't particularly patient though (there's room for improvement here) and since it has to shutdown too, sends a SIGTERM to all of the FastCGI applications it is responsible for. Apache will restart the process manager and it will restart its managed applications (as if the server was just started). SIGTERM is, well, SIGTERM - your application should exit quickly.

What this implies to me is that if Database I/O, or some other part of the CGI script, fails to respond in a timely fashion (ie getting slower with data-volume growth), that mod_fastcgi is killing the that how other people interpret these docs or what am I missing..

Monitor the Graphics card usage

If you develop in Visual Studio 2013 and 2015 versions, you can use their GPU Usage tool:

Screenshot from MSDN: enter image description here

Moreover, it seems you can diagnose any application with it, not only Visual Studio Projects:

In addition to Visual Studio projects you can also collect GPU usage data on any loose .exe applications that you have sitting around. Just open the executable as a solution in Visual Studio and then start up a diagnostics session and you can target it with GPU usage. This way if you are using some type of engine or alternative development environment you can still collect data on it as long as you end up with an executable.


Swing JLabel text change on the running application

import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.event.*;
public class Test extends JFrame implements ActionListener
    private JLabel label;
    private JTextField field;
    public Test()
        super("The title");
        setPreferredSize(new Dimension(400, 90));
        ((JPanel) getContentPane()).setBorder(new EmptyBorder(13, 13, 13, 13) );
        setLayout(new FlowLayout());
        JButton btn = new JButton("Change");
        label = new JLabel("flag");
        field = new JTextField(5);
    public void actionPerformed(ActionEvent e)
    public static void main(String[] args)
        new Test();

Bootstrap-select - how to fire event on change

This is what I did.

$('.selectpicker').on('', function (e, clickedIndex, newValue, oldValue) {
    var selected = $(e.currentTarget).val();


Since this question was closed, I'm posting here for how you do it using SQLAlchemy. Via recursion, it retries a bulk insert or update to combat race conditions and validation errors.

First the imports

import itertools as it

from functools import partial
from operator import itemgetter

from sqlalchemy.exc import IntegrityError
from app import session
from models import Posts

Now a couple helper functions

def chunk(content, chunksize=None):
    """Groups data into chunks each with (at most) `chunksize` items.
    if chunksize:
        i = iter(content)
        generator = (list(it.islice(i, chunksize)) for _ in it.count())
        generator = iter([content])

    return it.takewhile(bool, generator)

def gen_resources(records):
    """Yields a dictionary if the record's id already exists, a row object 
    ids = {item[0] for item in session.query(}

    for record in records:
        is_row = hasattr(record, 'to_dict')

        if is_row and in ids:
            # It's a row but the id already exists, so we need to convert it 
            # to a dict that updates the existing record. Since it is duplicate,
            # also yield True
            yield record.to_dict(), True
        elif is_row:
            # It's a row and the id doesn't exist, so no conversion needed. 
            # Since it's not a duplicate, also yield False
            yield record, False
        elif record['id'] in ids:
            # It's a dict and the id already exists, so no conversion needed. 
            # Since it is duplicate, also yield True
            yield record, True
            # It's a dict and the id doesn't exist, so we need to convert it. 
            # Since it's not a duplicate, also yield False
            yield Posts(**record), False

And finally the upsert function

def upsert(data, chunksize=None):
    for records in chunk(data, chunksize):
        resources = gen_resources(records)
        sorted_resources = sorted(resources, key=itemgetter(1))

        for dupe, group in it.groupby(sorted_resources, itemgetter(1)):
            items = [g[0] for g in group]

            if dupe:
                _upsert = partial(session.bulk_update_mappings, Posts)
                _upsert = session.add_all

            except IntegrityError:
                # A record was added or deleted after we checked, so retry
                # modify accordingly by adding additional exceptions, e.g.,
                # except (IntegrityError, ValidationError, ValueError)
            except Exception as e:
                # Some other error occurred so reduce chunksize to isolate the 
                # offending row(s)
                num_items = len(items)

                if num_items > 1:
                    upsert(items, num_items // 2)
                    print('Error adding record {}'.format(items[0]))

Here's how you use it

>>> data = [
...     {'id': 1, 'text': 'updated post1'}, 
...     {'id': 5, 'text': 'updated post5'}, 
...     {'id': 1000, 'text': 'new post1000'}]
>>> upsert(data)

The advantage this has over bulk_save_objects is that it can handle relationships, error checking, etc on insert (unlike bulk operations).

Java regex email

you can use a simple regular expression for validating email id,

public boolean validateEmail(String email){
  return Pattern.matches("[_a-zA-Z1-9]+(\\.[A-Za-z0-9]*)*@[A-Za-z0-9]+\\.[A-Za-z0-9]+(\\.[A-Za-z0-9]*)*", email)

Description :

  1. [_a-zA-Z1-9]+ - it will accept all A-Z,a-z, 0-9 and _ (+ mean it must be occur)
  2. (\.[A-Za-z0-9]) - it's optional which will accept . and A-Z, a-z, 0-9( * mean its optional)
  3. @[A-Za-z0-9]+ - it wil accept @ and A-Z,a-z,0-9
  4. \.[A-Za-z0-9]+ - its for . and A-Z,a-z,0-9
  5. (\.[A-Za-z0-9]) - it occur, . but its optional

Should MySQL have its timezone set to UTC?

It seems that it does not matter what timezone is on the server as long as you have the time set right for the current timezone, know the timezone of the datetime columns that you store, and are aware of the issues with daylight savings time.

On the other hand if you have control of the timezones of the servers you work with then you can have everything set to UTC internally and never worry about timezones and DST.

Here are some notes I collected of how to work with timezones as a form of cheatsheet for myself and others which might influence what timezone the person will choose for his/her server and how he/she will store date and time.

MySQL Timezone Cheatsheet


  1. Changing the timezone will not change the stored datetime or timestamp, but it will select a different datetime from timestamp columns
  2. Warning! UTC has leap seconds, these look like '2012-06-30 23:59:60' and can be added randomly, with 6 months prior notice, due to the slowing of the earths rotation
  3. GMT confuses seconds, which is why UTC was invented.

  4. Warning! different regional timezones might produce the same datetime value due to daylight savings time

  5. The timestamp column only supports dates 1970-01-01 00:00:01 to 2038-01-19 03:14:07 UTC, due to a limitation.
  6. Internally a MySQL timestamp column is stored as UTC but when selecting a date MySQL will automatically convert it to the current session timezone.

    When storing a date in a timestamp, MySQL will assume that the date is in the current session timezone and convert it to UTC for storage.

  7. MySQL can store partial dates in datetime columns, these look like "2013-00-00 04:00:00"
  8. MySQL stores "0000-00-00 00:00:00" if you set a datetime column as NULL, unless you specifically set the column to allow null when you create it.
  9. Read this

To select a timestamp column in UTC format

no matter what timezone the current MySQL session is in:

CONVERT_TZ(`timestamp_field`, @@session.time_zone, '+00:00') AS `utc_datetime` 
FROM `table_name`

You can also set the sever or global or current session timezone to UTC and then select the timestamp like so:

SELECT `timestamp_field` FROM `table_name`

To select the current datetime in UTC:

SELECT CONVERT_TZ(NOW(), @@session.time_zone, '+00:00');

Example result: 2015-03-24 17:02:41

To select the current datetime in the session timezone


To select the timezone that was set when the server launched

SELECT @@system_time_zone;

Returns "MSK" or "+04:00" for Moscow time for example, there is (or was) a MySQL bug where if set to a numerical offset it would not adjust the Daylight savings time

To get the current timezone


It will return 02:00:00 if your timezone is +2:00.

To get the current UNIX timestamp (in seconds):


To get the timestamp column as a UNIX timestamp

SELECT UNIX_TIMESTAMP(`timestamp`) FROM `table_name`

To get a UTC datetime column as a UNIX timestamp

SELECT UNIX_TIMESTAMP(CONVERT_TZ(`utc_datetime`, '+00:00', @@session.time_zone)) FROM `table_name`

Get a current timezone datetime from a positive UNIX timestamp integer

SELECT FROM_UNIXTIME(`unix_timestamp_int`) FROM `table_name`

Get a UTC datetime from a UNIX timestamp

SELECT CONVERT_TZ(FROM_UNIXTIME(`unix_timestamp_int`), @@session.time_zone, '+00:00') 
FROM `table_name`

Get a current timezone datetime from a negative UNIX timestamp integer

SELECT DATE_ADD('1970-01-01 00:00:00',INTERVAL -957632400 SECOND) 

There are 3 places where the timezone might be set in MySQL:

Note: A timezone can be set in 2 formats:

  1. an offset from UTC: '+00:00', '+10:00' or '-6:00'
  2. as a named time zone: 'Europe/Helsinki', 'US/Eastern', or 'MET'

Named time zones can be used only if the time zone information tables in the mysql database have been created and populated.

in the file "my.cnf"




@@global.time_zone variable

To see what value they are set to

SELECT @@global.time_zone;

To set a value for it use either one:

SET GLOBAL time_zone = '+8:00';
SET GLOBAL time_zone = 'Europe/Helsinki';
SET @@global.time_zone='+00:00';

@@session.time_zone variable

SELECT @@session.time_zone;

To set it use either one:

SET time_zone = 'Europe/Helsinki';
SET time_zone = "+00:00";
SET @@session.time_zone = "+00:00";

both "@@global.time_zone variable" and "@@session.time_zone variable" might return "SYSTEM" which means that they use the timezone set in "my.cnf".

For timezone names to work (even for default-time-zone) you must setup your timezone information tables need to be populated:

Note: you can not do this as it will return NULL:

CONVERT_TZ(`timestamp_field`, TIMEDIFF(NOW(), UTC_TIMESTAMP), '+00:00') AS `utc_datetime` 
FROM `table_name`

Setup mysql timezone tables

For CONVERT_TZ to work, you need the timezone tables to be populated

SELECT * FROM mysql.`time_zone` ;
SELECT * FROM mysql.`time_zone_leap_second` ;
SELECT * FROM mysql.`time_zone_name` ;
SELECT * FROM mysql.`time_zone_transition` ;
SELECT * FROM mysql.`time_zone_transition_type` ;

If they are empty, then fill them up by running this command

mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql -u root -p mysql

if this command gives you the error "data too long for column 'abbreviation' at row 1", then it might be caused by a NULL character being appended at the end of the timezone abbreviation

the fix being to run this

mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql -u root -p mysql
(if the above gives error "data too long for column 'abbreviation' at row 1")
mysql_tzinfo_to_sql /usr/share/zoneinfo > /tmp/zut.sql

echo "SET SESSION SQL_MODE = '';" > /tmp/mysql_tzinfo_to.sql
cat /tmp/zut.sql >> /tmp/mysql_tzinfo_to.sql

mysql --defaults-file=/etc/mysql/my.cnf --user=verifiedscratch -p mysql < /tmp/mysql_tzinfo_to.sql

(make sure your servers dst rules are up to date zdump -v Europe/Moscow | grep 2011

See the full DST (Daylight Saving Time) transition history for every timezone

tzn.Name AS tz_name,
tztt.Abbreviation AS tz_abbr,
tztt.Is_DST AS is_dst,
tztt.`Offset` AS `offset`,
DATE_ADD('1970-01-01 00:00:00',INTERVAL tzt.Transition_time SECOND)  AS transition_date
FROM mysql.`time_zone_transition` tzt
INNER JOIN mysql.`time_zone_transition_type` tztt USING(Time_zone_id, Transition_type_id)
INNER JOIN mysql.`time_zone_name` tzn USING(Time_zone_id)
-- WHERE tzn.Name LIKE 'Europe/Moscow' -- Moscow has weird DST changes
ORDER BY tzt.Transition_time ASC

CONVERT_TZ also applies any necessary DST changes based on the rules in the above tables and the date that you use.

According to the docs, the value you set for time_zone does not change, if you set it as "+01:00" for example, then the time_zone will be set as an offset from UTC, which does not follow DST, so it will stay the same all year round.

Only the named timezones will change time during daylight savings time.

Abbreviations like CET will always be a winter time and CEST will be summer time while +01:00 will always be UTC time + 1 hour and both won't change with DST.

The system timezone will be the timezone of the host machine where mysql is installed (unless mysql fails to determine it)

You can read more about working with DST here

related questions:


ISO C90 forbids mixed declarations and code in C

Make sure the variable is on the top part of the block, and in case you compile it with -ansi-pedantic, make sure it looks like this:

function() {
    int i;
    i = 0;


PHP multidimensional array search by value

$a = ['x' => ['eee', 'ccc'], 'b' => ['zzz']];

$found = null;
$search = 'eee';

array_walk($a, function ($k, $v) use ($search, &$found) {
    if (in_array($search, $k)) {
        $found = $v;


Array.sort() doesn't sort numbers correctly

try this:

a = new Array();


function Test(a,b)
    return a > b ? true : false;

Count the number of occurrences of each letter in string

for (int i=0;i<word.length();i++){
         int counter=0;
         for (int j=0;j<word.length();j++){
             }// inner for
             JOptionPane.showMessageDialog( null,word.charAt(i)+" found "+ counter +" times");
         }// outer for

Interface defining a constructor signature?

The purpose of an interface is to enforce a certain object signature. It should explicitly not be concerned with how an object works internally. Therefore, a constructor in an interface does not really make sense from a conceptual point of view.

There are some alternatives though:

  • Create an abstract class that acts as a minimal default implementation. That class should have the constructors you expect implementing classes to have.

  • If you don't mind the overkill, use the AbstractFactory pattern and declare a method in the factory class interface that has the required signatures.

  • Pass the GraphicsDeviceManager as a parameter to the Update and Draw methods.

  • Use a Compositional Object Oriented Programming framework to pass the GraphicsDeviceManager into the part of the object that requires it. This is a pretty experimental solution in my opinion.

The situation you describe is not easy to handle in general. A similar case would be entities in a business application that require access to the database.

C read file line by line

//open and get the file handle
FILE* fh;
fopen_s(&fh, filename, "r");

//check if file exists
if (fh == NULL){
    printf("file does not exists %s", filename);
    return 0;

//read line by line
const size_t line_size = 300;
char* line = malloc(line_size);
while (fgets(line, line_size, fh) != NULL)  {
free(line);    // dont forget to free heap memory

How to Code Double Quotes via HTML Codes

There really aren't any differences.

&quot; is processed as &#34; which is the decimal equivalent of &x22; which is the ISO 8859-1 equivalent of ".

The only reason you may be against using &quot; is because it was mistakenly omitted from the HTML 3.2 specification.

Otherwise it all boils down to personal preference.

Last Key in Python Dictionary

It doesn't make sense to ask for the "last" key in a dictionary, because dictionary keys are unordered. You can get the list of keys and get the last one if you like, but that's not in any sense the "last key in a dictionary".

Interfaces with static fields in java for sharing 'constants'

I do not pretend the right to be right, but lets see this small example:

public interface CarConstants {

      static final String ENGINE = "mechanical";
      static final String WHEEL  = "round";
      // ...


public interface ToyotaCar extends CarConstants //, ICar, ... {
      void produce();

public interface FordCar extends CarConstants //, ICar, ... {
      void produce();

// and this is implementation #1
public class CamryCar implements ToyotaCar {

      public void produce() {
           System.out.println("the engine is " + ENGINE );
           System.out.println("the wheel is " + WHEEL);

// and this is implementation #2
public class MustangCar implements FordCar {

      public void produce() {
           System.out.println("the engine is " + ENGINE );
           System.out.println("the wheel is " + WHEEL);

ToyotaCar doesnt know anything about FordCar, and FordCar doesnt know about ToyotaCar. principle CarConstants should be changed, but...

Constants should not be changed, because the wheel is round and egine is mechanical, but... In the future Toyota's research engineers invented electronic engine and flat wheels! Lets see our new interface

public interface InnovativeCarConstants {

          static final String ENGINE = "electronic";
          static final String WHEEL  = "flat";
          // ...

and now we can change our abstraction:

public interface ToyotaCar extends CarConstants


public interface ToyotaCar extends InnovativeCarConstants 

And now if we ever need to change the core value if the ENGINE or WHEEL we can change the ToyotaCar Interface on abstraction level, dont touching implementations

Its NOT SAFE, I know, but I still want to know that do you think about this

FormData.append("key", "value") is not working

form data doesn't appear in web browser console

for (var data of formData) {

try this way it will show

Disable the postback on an <ASP:LinkButton>

Just been through this, the correct way to do it is to use:

  1. OnClientClick
  2. return false

as in the following example line of code:

<asp:LinkButton ID="lbtnNext" runat="server" OnClientClick="findAllOccurences(); return false;" />

When should I use cross apply over inner join?

Cross apply can be used to replace subquery's where you need a column of the subquery


select * from person p where
p.companyId in(select c.companyId from company c where c.companyname like '%yyy%')

here i won't be able to select the columns of company table so, using cross apply

select P.*,T.CompanyName
from Person p
cross apply (
    select *
    from Company C
    where p.companyid = c.companyId and c.CompanyName like '%yyy%'
) T

How to draw a filled triangle in android canvas?

Using @Pavel's answer as guide, here's a helper method if you don't have the points but have start x,y and height and width. Also can draw inverted/upside down - which is useful for me as it was used as end of vertical barchart.

 private void drawTriangle(int x, int y, int width, int height, boolean inverted, Paint paint, Canvas canvas){

        Point p1 = new Point(x,y);
        int pointX = x + width/2;
        int pointY = inverted?  y + height : y - height;

        Point p2 = new Point(pointX,pointY);
        Point p3 = new Point(x+width,y);

        Path path = new Path();

        canvas.drawPath(path, paint);

How can I convert a DOM element to a jQuery element?

var elm = document.createElement("div");
var jelm = $(elm);//convert to jQuery Element
var htmlElm = jelm[0];//convert to HTML Element

Fine control over the font size in Seaborn plots for academic papers

You are right. This is a badly documented issue. But you can change the font size parameter (by opposition to font scale) directly after building the plot. Check the following example:

import seaborn as sns
tips = sns.load_dataset("tips")

b = sns.boxplot(x=tips["total_bill"])
b.set_xlabel("X Label",fontsize=30)
b.set_ylabel("Y Label",fontsize=20)

, which results in this:

Different font sizes for different labels

To make it consistent in between plots I think you just need to make sure the DPI is the same. By the way it' also a possibility to customize a bit the rc dictionaries since "font.size" parameter exists but I'm not too sure how to do that.

NOTE: And also I don't really understand why they changed the name of the font size variables for axis labels and ticks. Seems a bit un-intuitive.

TypeScript error: Type 'void' is not assignable to type 'boolean'

It means that the callback function you passed to should return a boolean and have 3 parameters, two of which can be optional:

  • value: Conversations
  • index: number
  • obj: Conversation[]

However, your callback function does not return anything (returns void). You should pass a callback function with the correct return value:, index, obj) => {
    // ...

    return true; // or false

or: => {
    // ...

    return true; // or false

Reason why it's this way: the function you pass to the find method is called a predicate. The predicate here defines a boolean outcome based on conditions defined in the function itself, so that the find method can determine which value to find.

In practice, this means that the predicate is called for each item in data, and the first item in data for which your predicate returns true is the value returned by find.

Sass calculate percent minus px

IF you know the width of the container, you could do like this:

  width: #{200}px
    width: #{(0.25 * 200) - 5}px

I'm aware that in many cases #container could have a relative width. Then this wouldn't work.

Using async/await with a forEach loop

Similar to Antonio Val's p-iteration, an alternative npm module is async-af:

const AsyncAF = require('async-af');
const fs = require('fs-promise');

function printFiles() {
  // since AsyncAF accepts promises or non-promises, there's no need to await here
  const files = getFilePaths();

  AsyncAF(files).forEach(async file => {
    const contents = await fs.readFile(file, 'utf8');


Alternatively, async-af has a static method (log/logAF) that logs the results of promises:

const AsyncAF = require('async-af');
const fs = require('fs-promise');

function printFiles() {
  const files = getFilePaths();

  AsyncAF(files).forEach(file => {
    AsyncAF.log(fs.readFile(file, 'utf8'));


However, the main advantage of the library is that you can chain asynchronous methods to do something like:

const aaf = require('async-af');
const fs = require('fs-promise');

const printFiles = () => aaf(getFilePaths())
  .map(file => fs.readFile(file, 'utf8'))
  .forEach(file => aaf.log(file));



NPM doesn't install module dependencies

I had very similar issue, removing entire node_modules folder and re-installing worked for me. Learned this trick from the IT Crowd show!

rm -rf node_modules
npm install

Difference between decimal, float and double in .NET?

float and double are floating binary point types. In other words, they represent a number like this:


The binary number and the location of the binary point are both encoded within the value.

decimal is a floating decimal point type. In other words, they represent a number like this:


Again, the number and the location of the decimal point are both encoded within the value – that's what makes decimal still a floating point type instead of a fixed point type.

The important thing to note is that humans are used to representing non-integers in a decimal form, and expect exact results in decimal representations; not all decimal numbers are exactly representable in binary floating point – 0.1, for example – so if you use a binary floating point value you'll actually get an approximation to 0.1. You'll still get approximations when using a floating decimal point as well – the result of dividing 1 by 3 can't be exactly represented, for example.

As for what to use when:

  • For values which are "naturally exact decimals" it's good to use decimal. This is usually suitable for any concepts invented by humans: financial values are the most obvious example, but there are others too. Consider the score given to divers or ice skaters, for example.

  • For values which are more artefacts of nature which can't really be measured exactly anyway, float/double are more appropriate. For example, scientific data would usually be represented in this form. Here, the original values won't be "decimally accurate" to start with, so it's not important for the expected results to maintain the "decimal accuracy". Floating binary point types are much faster to work with than decimals.

Preventing scroll bars from being hidden for MacOS trackpad users in WebKit/Blink

For a one-page web application where I add scrollable sections dynamically, I trigger OSX's scrollbars by programmatically scrolling one pixel down and back up:

// Plain JS:
var el = document.getElementById('scrollable-section');
el.scrollTop = 1;
el.scrollTop = 0;

// jQuery:

This triggers the visual cue fading in and out.

Map implementation with duplicate keys

We don't need to depend on the Google Collections external library. You can simply implement the following Map:

Map<String, ArrayList<String>> hashMap = new HashMap<String, ArrayList>();

public static void main(String... arg) {
   // Add data with duplicate keys
   addValues("A", "a1");
   addValues("A", "a2");
   addValues("B", "b");
   // View data.
   Iterator it = hashMap.keySet().iterator();
   ArrayList tempList = null;

   while (it.hasNext()) {
      String key =;             
      tempList = hashMap.get(key);
      if (tempList != null) {
         for (String value: tempList) {
            System.out.println("Key : "+key+ " , Value : "+value);

private void addValues(String key, String value) {
   ArrayList tempList = null;
   if (hashMap.containsKey(key)) {
      tempList = hashMap.get(key);
      if(tempList == null)
         tempList = new ArrayList();
   } else {
      tempList = new ArrayList();

Please make sure to fine tune the code.

Choice between vector::resize() and vector::reserve()

From your description, it looks like that you want to "reserve" the allocated storage space of vector t_Names.

Take note that resize initialize the newly allocated vector where reserve just allocates but does not construct. Hence, 'reserve' is much faster than 'resize'

You can refer to the documentation regarding the difference of resize and reserve

Homebrew: Could not symlink, /usr/local/bin is not writable

For me the solution was to run brew update.


This might be normal practice for people familiar with homebrew, but I'm not one of those people.

Edit: I discovered that I needed to update by running brew doctor as suggested by @kinnth's answer to this same question.

A general troubleshooting workflow might look like this: 1. run brew update 2. if that doesn't help run brew doctor and follow its directions 3. if that doesn't help check stack overflow

What is the difference between the operating system and the kernel?

The kernel is part of the operating system and closer to the hardware it provides low level services like:

  • device driver
  • process management
  • memory management
  • system calls

An operating system also includes applications like the user interface (shell, gui, tools, and services).

How to get file creation date/time in Bash/Debian?

ls -i menus.xml

94490 menus.xml Here the number 94490 represents inode

Then do a:

df -h

Filesystem            Size  Used Avail Use% Mounted on
/dev/mapper/vg-root   4.0G  3.4G  408M  90% /
tmpfs                 1.9G     0  1.9G   0% /dev/shm
/dev/sda1             124M   27M   92M  23% /boot
/dev/mapper/vg-var    7.9G  1.1G  6.5G  15% /var

To find the mounting point of the root "/" filesystem, because the file menus.xml is on '/' that is '/dev/mapper/vg-root'

debugfs -R 'stat <94490>' /dev/mapper/vg-root

The output may be like the one below:

debugfs -R 'stat <94490>' /dev/mapper/vg-root

debugfs 1.41.12 (17-May-2010)
Inode: 94490   Type: regular    Mode:  0644   Flags: 0x0
Generation: 2826123170    Version: 0x00000000
User:     0   Group:     0   Size: 4441
File ACL: 0    Directory ACL: 0
Links: 1   Blockcount: 16
Fragment:  Address: 0    Number: 0    Size: 0
ctime: 0x5266e438 -- Wed Oct 23 09:46:48 2013
atime: 0x5266e47b -- Wed Oct 23 09:47:55 2013
mtime: 0x5266e438 -- Wed Oct 23 09:46:48 2013
Size of extra inode fields: 4
Extended attributes stored in inode body: 
  selinux = "unconfined_u:object_r:usr_t:s0\000" (31)

Where you can see the creation time:

ctime: 0x5266e438 -- Wed Oct 23 09:46:48 2013

I get "Http failure response for (unknown url): 0 Unknown Error" instead of actual error message in Angular

You must use --port when serve server ng serve --open --port 4200

    export class DatabaseService {
  baseUrl: String = "http://localhost:8080/";
  constructor(private http: HttpClient) { }

  saveTutorial(response) {
    var fullUrl = this.baseUrl + "api/tutorials";

What are the differences and similarities between ffmpeg, libav, and avconv?

Confusing messages

These messages are rather misleading and understandably a source of confusion. Older Ubuntu versions used Libav which is a fork of the FFmpeg project. FFmpeg returned in Ubuntu 15.04 "Vivid Vervet".

The fork was basically a non-amicable result of conflicting personalities and development styles within the FFmpeg community. It is worth noting that the maintainer for Debian/Ubuntu switched from FFmpeg to Libav on his own accord due to being involved with the Libav fork.

The real ffmpeg vs the fake one

For a while both Libav and FFmpeg separately developed their own version of ffmpeg.

Libav then renamed their bizarro ffmpeg to avconv to distance themselves from the FFmpeg project. During the transition period the "not developed anymore" message was displayed to tell users to start using avconv instead of their counterfeit version of ffmpeg. This confused users into thinking that FFmpeg (the project) is dead, which is not true. A bad choice of words, but I can't imagine Libav not expecting such a response by general users.

This message was removed upstream when the fake "ffmpeg" was finally removed from the Libav source, but, depending on your version, it can still show up in Ubuntu because the Libav source Ubuntu uses is from the ffmpeg-to-avconv transition period.

In June 2012, the message was re-worded for the package libav - 4:0.8.3-0ubuntu0.12.04.1. Unfortunately the new "deprecated" message has caused additional user confusion.

Starting with Ubuntu 15.04 "Vivid Vervet", FFmpeg's ffmpeg is back in the repositories again.

libav vs Libav

To further complicate matters, Libav chose a name that was historically used by FFmpeg to refer to its libraries (libavcodec, libavformat, etc). For example the libav-user mailing list, for questions and discussions about using the FFmpeg libraries, is unrelated to the Libav project.

How to tell the difference

If you are using avconv then you are using Libav. If you are using ffmpeg you could be using FFmpeg or Libav. Refer to the first line in the console output to tell the difference: the copyright notice will either mention FFmpeg or Libav.

Secondly, the version numbering schemes differ. Each of the FFmpeg or Libav libraries contains a version.h header which shows a version number. FFmpeg will end in three digits, such as 57.67.100, and Libav will end in one digit such as 57.67.0. You can also view the library version numbers by running ffmpeg or avconv and viewing the console output.

If you want to use the real ffmpeg

Ubuntu 15.04 "Vivid Vervet" or newer

The real ffmpeg is in the repository, so you can install it with:

apt-get install ffmpeg

For older Ubuntu versions

Your options are:

These methods are non-intrusive, reversible, and will not interfere with the system or any repository packages.

Another possible option is to upgrade to Ubuntu 15.04 "Vivid Vervet" or newer and just use ffmpeg from the repository.

Also see

For an interesting blog article on the situation, as well as a discussion about the main technical differences between the projects, see The FFmpeg/Libav situation.

ASP.NET / C#: DropDownList SelectedIndexChanged in server control not firing

You need to set AutoPostBack to true for the Country DropDownList.

protected override void OnLoad(EventArgs e)
    // base stuff

    ddlCountries.AutoPostBack = true;

    // other stuff


I missed that you had done this. In that case you need to check that ViewState is enabled.

How to find sum of multiple columns in a table in SQL Server 2005?

use a trigges it will work:-

->CREATE TRIGGER trigger_name BEFORE INSERT ON table_name

FOR EACH ROW SET NEW.column_name3 = NEW.column_name1 + NEW.column_name2;

this will only work only when you will insert a row in table not when you will be updating your table for such a pupose create another trigger of different name and use UPDATE on the place of INSERT in the above syntax