Programs & Examples On #Shift

Questions related to the usage of the right and/or left shift key on the keyboard. For questions regarding bitwise shift operations use [bit-shift]

Java, Shifting Elements in an Array

Just for completeness: Stream solution since Java 8.

final String[] shiftedArray =

I think I sticked with the System.arraycopy() in your situtation. But the best long-term solution might be to convert everything to Immutable Collections (Guava, Vavr), as long as those collections are short-lived.

Move column by name to front of table in pandas

We can use ix to reorder by passing a list:

In [27]:
# get a list of columns
cols = list(df)
# move the column to head of list using index, pop and insert
cols.insert(0, cols.pop(cols.index('Mid')))
['Mid', 'Net', 'Upper', 'Lower', 'Zsore']
In [28]:
# use ix to reorder
df = df.ix[:, cols]
                      Mid Net  Upper   Lower  Zsore
More_than_once_a_day    2  0%  0.22%  -0.12%     65
Once_a_day              3  0%  0.32%  -0.19%     45
Several_times_a_week    4  2%  2.45%   1.10%     78
Once_a_week             6  1%  1.63%  -0.40%     65

Another method is to take a reference to the column and reinsert it at the front:

In [39]:
mid = df['Mid']
df.drop(labels=['Mid'], axis=1,inplace = True)
df.insert(0, 'Mid', mid)
                      Mid Net  Upper   Lower  Zsore
More_than_once_a_day    2  0%  0.22%  -0.12%     65
Once_a_day              3  0%  0.32%  -0.19%     45
Several_times_a_week    4  2%  2.45%   1.10%     78
Once_a_week             6  1%  1.63%  -0.40%     65

You can also use loc to achieve the same result as ix will be deprecated in a future version of pandas from 0.20.0 onwards:

df = df.loc[:, cols]

How to check if "Radiobutton" is checked?

Check if they're checked with the el.checked attribute.

Docs or this Question

let radio1 = document.querySelector('.radio1');
let radio2 = document.querySelector('.radio2');
let output = document.querySelector('.output');

function update() {
  if (radio1.checked) {
    output.innerHTML = "radio1";
  else {
    output.innerHTML = "radio2";

<div class="radios">
  <input class="radio1" type="radio" name="radios" onchange="update()" checked>
  <input class="radio2" type="radio" name="radios" onchange="update()">
<div class="output"></div>

How to hide a div element depending on Model value? MVC


<div style="@(Model.booleanVariable ? "display:block" : "display:none")">Some links</div>

Use the "Display" style attribute with your bool model attribute to define the div's visibility.

AWS S3: how do I see how much disk space is using

I'm not sure when this was added to the AWSCLI given that the original question was 3 years ago, but the command line tool gives a nice summary by running:

aws s3 ls s3://mybucket --recursive --human-readable --summarize

Adding default parameter value with type hint in Python

If you're using typing (introduced in Python 3.5) you can use typing.Optional, where Optional[X] is equivalent to Union[X, None]. It is used to signal that the explicit value of None is allowed . From typing.Optional:

def foo(arg: Optional[int] = None) -> None:

Countdown timer using Moment js

Here are some other solutions. No need to use additional plugins.

Snippets down below uses .subtract API and requires moment 2.1.0+

Snippets are also available in here

Formatting with the .format API:

const duration = moment.duration(9, 's');

const intervalId = setInterval(() => {
  duration.subtract(1, "s");

  const inMilliseconds = duration.asMilliseconds();

  // "mm:ss:SS" will include milliseconds

  if (inMilliseconds !== 0) return;

  console.warn("Times up!");
}, 1000);
<script src=""></script>

Manuel formatting by .hours, .minutes and .seconds API in a template string

const duration = moment.duration(9, 's');

const intervalId = setInterval(() => {
  duration.subtract(1, "s");

  // `:${duration.milliseconds()}` to add milliseconds

  if (duration.asMilliseconds() !== 0) return;

  console.warn("Times up!");
}, 1000);
<script src=""></script>

delete all record from table in mysql

It’s because you tried to update a table without a WHERE that uses a KEY column.

The quick fix is to add SET SQL_SAFE_UPDATES=0; before your query :



close the safe update mode. Edit -> Preferences -> SQL Editor -> SQL Editor remove Forbid UPDATE and DELETE statements without a WHERE clause (safe updates) .

BTW you can use TRUNCATE TABLE tablename; to delete all the records .

Uninitialized constant ActiveSupport::Dependencies::Mutex (NameError)

I was able to fix this by downgrading RubyGems to 1.5.3, since it happens with RubyGems 1.6.0+ and Rails < 2.3.11:

gem update --system 1.5.3

If you had previously downgraded to an even earlier version and want to update to 1.5.3, you might get the following when trying to run that:

Updating RubyGems
ERROR:  While executing gem ... (RuntimeError)
    No gem names are allowed with the --system option

If you get that error, then update, so that it lets you specify the version, and then downgrade again:

gem update --system
gem update --system 1.5.3

Where can I download english dictionary database in a text format?

Check if these free resources fit your need -

How to send a simple string between two programs using pipes?

From Creating Pipes in C, this shows you how to fork a program to use a pipe. If you don't want to fork(), you can use named pipes.

In addition, you can get the effect of prog1 | prog2 by sending output of prog1 to stdout and reading from stdin in prog2. You can also read stdin by opening a file named /dev/stdin (but not sure of the portability of that).

 Excerpt from "Linux Programmer's Guide - Chapter 6"
 (C)opyright 1994-1995, Scott Burkett
 MODULE: pipe.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>

int main(void)
        int     fd[2], nbytes;
        pid_t   childpid;
        char    string[] = "Hello, world!\n";
        char    readbuffer[80];


        if((childpid = fork()) == -1)

        if(childpid == 0)
                /* Child process closes up input side of pipe */

                /* Send "string" through the output side of pipe */
                write(fd[1], string, (strlen(string)+1));
                /* Parent process closes up output side of pipe */

                /* Read in a string from the pipe */
                nbytes = read(fd[0], readbuffer, sizeof(readbuffer));
                printf("Received string: %s", readbuffer);


What is "entropy and information gain"?

I can't give you graphics, but maybe I can give a clear explanation.

Suppose we have an information channel, such as a light that flashes once every day either red or green. How much information does it convey? The first guess might be one bit per day. But what if we add blue, so that the sender has three options? We would like to have a measure of information that can handle things other than powers of two, but still be additive (the way that multiplying the number of possible messages by two adds one bit). We could do this by taking log2(number of possible messages), but it turns out there's a more general way.

Suppose we're back to red/green, but the red bulb has burned out (this is common knowledge) so that the lamp must always flash green. The channel is now useless, we know what the next flash will be so the flashes convey no information, no news. Now we repair the bulb but impose a rule that the red bulb may not flash twice in a row. When the lamp flashes red, we know what the next flash will be. If you try to send a bit stream by this channel, you'll find that you must encode it with more flashes than you have bits (50% more, in fact). And if you want to describe a sequence of flashes, you can do so with fewer bits. The same applies if each flash is independent (context-free), but green flashes are more common than red: the more skewed the probability the fewer bits you need to describe the sequence, and the less information it contains, all the way to the all-green, bulb-burnt-out limit.

It turns out there's a way to measure the amount of information in a signal, based on the the probabilities of the different symbols. If the probability of receiving symbol xi is pi, then consider the quantity

-log pi

The smaller pi, the larger this value. If xi becomes twice as unlikely, this value increases by a fixed amount (log(2)). This should remind you of adding one bit to a message.

If we don't know what the symbol will be (but we know the probabilities) then we can calculate the average of this value, how much we will get, by summing over the different possibilities:

I = -Σ pi log(pi)

This is the information content in one flash.

Red bulb burnt out: pred = 0, pgreen=1, I = -(0 + 0)  = 0
Red and green equiprobable: pred = 1/2, pgreen = 1/2, I = -(2 * 1/2 * log(1/2)) = log(2)
Three colors, equiprobable: pi=1/3, I = -(3 * 1/3 * log(1/3)) = log(3)
Green and red, green twice as likely: pred=1/3, pgreen=2/3, I = -(1/3 log(1/3) + 2/3 log(2/3)) = log(3) - 2/3 log(2)

This is the information content, or entropy, of the message. It is maximal when the different symbols are equiprobable. If you're a physicist you use the natural log, if you're a computer scientist you use log2 and get bits.

Parsing string as JSON with single quotes?

Something like this:

var div = document.getElementById("result");_x000D_
var str = "{'a':1}";_x000D_
  str = str.replace(/\'/g, '"');_x000D_
  var parsed = JSON.parse(str);_x000D_
  div.innerText = parsed.a;
<div id="result"></div>

MySql Inner Join with WHERE clause

Yes you are right. You have placed WHERE clause wrong. You can only use one WHERE clause in single query so try AND for multiple conditions like this:

 SELECT table1.f_id  FROM table1 
   INNER JOIN table2
     ON table2.f_id = table1.f_id
 WHERE table2.f_type = 'InProcess'
   AND f_com_id = '430'
   AND f_status = 'Submitted' 

How to get a user's client IP address in ASP.NET?

IP addresses are part of the Network layer in the "seven-layer stack". The Network layer can do whatever it wants to do with the IP address. That's what happens with a proxy server, NAT, relay, or whatever.

The Application layer should not depend on the IP address in any way. In particular, an IP Address is not meant to be an identifier of anything other than the idenfitier of one end of a network connection. As soon as a connection is closed, you should expect the IP address (of the same user) to change.

Difference between IsNullOrEmpty and IsNullOrWhiteSpace in C#

IsNullOrWhiteSpace is a convenience method that is similar to the following code, except that it offers superior performance:

return String.IsNullOrEmpty(value) || value.Trim().Length == 0;

White-space characters are defined by the Unicode standard. The IsNullOrWhiteSpace method interprets any character that returns a value of true when it is passed to the Char.IsWhiteSpace method as a white-space character.

How do I diff the same file between two different commits on the same branch?

From the git-diff manpage:

git diff [--options] <commit> <commit> [--] [<path>...]

For instance, to see the difference for a file "main.c" between now and two commits back, here are three equivalent commands:

$ git diff HEAD^^ HEAD main.c
$ git diff HEAD^^..HEAD -- main.c
$ git diff HEAD~2 HEAD -- main.c

Get exception description and stack trace which caused an exception, all as a string

For Python 3.5+:

So, you can get the stacktrace from your exception as from any other exception. Use traceback.TracebackException for it (just replace ex with your exception):


An extended example and other features to do this:

import traceback

except Exception as ex:
    print("".join(traceback.TracebackException.from_exception(ex).format()) == traceback.format_exc() == "".join(traceback.format_exception(type(ex), ex, ex.__traceback__))) # This is True !!

The output will be something like this:

Traceback (most recent call last):
  File "", line 29, in <module>
ZeroDivisionError: division by zero

Why does the preflight OPTIONS request of an authenticated CORS request work in Chrome but not Firefox?

Why does it work in Chrome and not Firefox?

The W3 spec for CORS preflight requests clearly states that user credentials should be excluded. There is a bug in Chrome and WebKit where OPTIONS requests returning a status of 401 still send the subsequent request.

Firefox has a related bug filed that ends with a link to the W3 public webapps mailing list asking for the CORS spec to be changed to allow authentication headers to be sent on the OPTIONS request at the benefit of IIS users. Basically, they are waiting for those servers to be obsoleted.

How can I get the OPTIONS request to send and respond consistently?

Simply have the server (API in this example) respond to OPTIONS requests without requiring authentication.

Kinvey did a good job expanding on this while also linking to an issue of the Twitter API outlining the catch-22 problem of this exact scenario interestingly a couple weeks before any of the browser issues were filed.

How do I stop/start a scheduled task on a remote computer programmatically?

Here's what I found.


schtasks /end /s <machine name> /tn <task name>


schtasks /run /s <machine name> /tn <task name>

C:\>schtasks /?

SCHTASKS /parameter [arguments]

    Enables an administrator to create, delete, query, change, run and
    end scheduled tasks on a local or remote system. Replaces AT.exe.

Parameter List:
    /Create         Creates a new scheduled task.

    /Delete         Deletes the scheduled task(s).

    /Query          Displays all scheduled tasks.

    /Change         Changes the properties of scheduled task.

    /Run            Runs the scheduled task immediately.

    /End            Stops the currently running scheduled task.

    /?              Displays this help message.

    SCHTASKS /Run /?
    SCHTASKS /End /?
    SCHTASKS /Create /?
    SCHTASKS /Delete /?
    SCHTASKS /Query  /?
    SCHTASKS /Change /?

Multiple file extensions in OpenFileDialog

Based on First answer here is the complete image selection options:

Filter = @"|All Image Files|*.BMP;*.bmp;*.JPG;*.JPEG*.jpg;*.jpeg;*.PNG;*.png;*.GIF;*.gif;*.tif;*.tiff;*.ico;*.ICO

Javascript: Unicode string to hex

Here is my take: these functions convert a UTF8 string to a proper HEX without the extra zeroes padding. A real UTF8 string has characters with 1, 2, 3 and 4 bytes length.

While working on this I found a couple key things that solved my problems:

  1. str.split('') doesn't handle multi-byte characters like emojis correctly. The proper/modern way to handle this is with Array.from(str)
  2. encodeURIComponent() and decodeURIComponent() are great tools to convert between string and hex. They are pretty standard, they handle UTF8 correctly.
  3. (Most) ASCII characters (codes 0 - 127) don't get URI encoded, so they need to handled separately. But c.charCodeAt(0).toString(16) works perfectly for those
    function utf8ToHex(str) {
      return Array.from(str).map(c => 
        c.charCodeAt(0) < 128 ? c.charCodeAt(0).toString(16) : 
    function hexToUtf8: function(hex) {
      return decodeURIComponent('%' + hex.match(/.{1,2}/g).join('%'));


How to set a Fragment tag by code?

Yes. So the only way is at transaction time, e.g. using add, replace, or as part of the layout.

I determined this through an examination of the compatibility sources as I briefly looked for similar at some point in the past.

jQuery: selecting each td in a tr

Your $(magicSelector) could be $('td', this). This will grab all td that are children of this, which in your case is each tr. This is the same as doing $(this).find('td').

$('td', this).each(function() {
// Logic

Using AJAX to pass variable to PHP and retrieve those using AJAX again

$(document).ready(function() {
    $("#raaagh").click(function() {
            url: 'ajax.php', //This is the current doc
            type: "POST",
            data: ({name: 145}),
            success: function(data) {
                    data: data,
                    success:function(data1) {
                        var y1=data1;

Use like this, first make a ajax call to get data, then your php function will return u the result which u wil get in data and pass that data to the new ajax call

What is the difference between MySQL, MySQLi and PDO?

There are (more than) three popular ways to use MySQL from PHP. This outlines some features/differences PHP: Choosing an API:

  1. (DEPRECATED) The mysql functions are procedural and use manual escaping.
  2. MySQLi is a replacement for the mysql functions, with object-oriented and procedural versions. It has support for prepared statements.
  3. PDO (PHP Data Objects) is a general database abstraction layer with support for MySQL among many other databases. It provides prepared statements, and significant flexibility in how data is returned.

I would recommend using PDO with prepared statements. It is a well-designed API and will let you more easily move to another database (including any that supports ODBC) if necessary.

The absolute uri: cannot be resolved in either web.xml or the jar files deployed with this application

I solved the same problem. I've just added JSTL-1.2.jar to /apache-tomcat-x.x.x/lib and set scope to provided in maven pom.xml:


How to test enum types?

For enums, I test them only when they actually have methods in them. If it's a pure value-only enum like your example, I'd say don't bother.

But since you're keen on testing it, going with your second option is much better than the first. The problem with the first is that if you use an IDE, any renaming on the enums would also rename the ones in your test class.

How do you do a limit query in JPQL or HQL?

My observation is that even you have limit in the HQL (hibernate 3.x), it will be either causing parsing error or just ignored. (if you have order by + desc/asc before limit, it will be ignored, if you don't have desc/asc before limit, it will cause parsing error)

How to re-render flatlist?

OK.I just found out that if we want the FlatList to know the data change outside of the data prop,we need set it to extraData, so I do it like this now:

<FlatList data={...} extraData={this.state} .../>

refer to :

Printing Java Collections Nicely (toString Doesn't Return Pretty Output)

I agree with the above comments about overriding toString() on your own classes (and about automating that process as much as possible).

For classes you didn't define, you could write a ToStringHelper class with an overloaded method for each library class you want to have handled to your own tastes:

public class ToStringHelper {
    //... instance configuration here (e.g. punctuation, etc.)
    public toString(List m) {
        // presentation of List content to your liking
    public toString(Map m) {
        // presentation of Map content to your liking
    public toString(Set m) {
        // presentation of Set content to your liking
    //... etc.

EDIT: Responding to the comment by xukxpvfzflbbld, here's a possible implementation for the cases mentioned previously.


import java.util.List;
import java.util.Map;
import java.util.Set;

public class ToStringHelper {

    private String separator;
    private String arrow;

    public ToStringHelper(String separator, String arrow) {
        this.separator = separator;
        this.arrow = arrow;

   public String toString(List<?> l) {
        StringBuilder sb = new StringBuilder("(");
        String sep = "";
        for (Object object : l) {
            sep = separator;
        return sb.append(")").toString();

    public String toString(Map<?,?> m) {
        StringBuilder sb = new StringBuilder("[");
        String sep = "";
        for (Object object : m.keySet()) {
            sep = separator;
        return sb.append("]").toString();

    public String toString(Set<?> s) {
        StringBuilder sb = new StringBuilder("{");
        String sep = "";
        for (Object object : s) {
            sep = separator;
        return sb.append("}").toString();


This isn't a full-blown implementation, but just a starter.

How to link a folder with an existing Heroku app

Heroku links your projects based on the heroku git remote (and a few other options, see the update below). To add your Heroku remote as a remote in your current repository, use the following command:

git remote add heroku [email protected]:project.git

where project is the name of your Heroku project (the same as the subdomain). Once you've done so, you can use the heroku xxxx commands (assuming you have the Heroku Toolbelt installed), and can push to Heroku as usual via git push heroku master. As a shortcut, if you're using the command line tool, you can type:

heroku git:remote -a project

where, again, project is the name of your Heroku project (thanks, Colonel Panic). You can name the Git remote anything you want by passing -r remote_name.


As mentioned by Ben in the comments, the remote doesn't need to be named heroku for the gem commands to work. I checked the source, and it appears it works like this:

  1. If you specify an app name via the --app option (e.g. heroku info --app myapp), it will use that app.
  2. If you specify a Git remote name via the --remote option (e.g. heroku info --remote production), it will use the app associated with that Git remote.
  3. If you specify no option and you have heroku.remote set in your Git config file, it will use the app associated with that remote (for example, to set the default remote to "production" use git config heroku.remote production in your repository, and Heroku will run git config heroku.remote to read the value of this setting)
  4. If you specify no option, the gem finds no configuration in your .git/config file, and the gem only finds one remote in your Git remotes that has "" in the URL, it will use that remote.
  5. If none of these work, it raises an error instructing you to pass --app to your command.

Getting TypeError: __init__() missing 1 required positional argument: 'on_delete' when trying to add parent table after child table with entries

You can change the property categorie of the class Article like this:

categorie = models.ForeignKey(

and the error should disappear.

Eventually you might need another option for on_delete, check the documentation for more details:


As you stated in your comment, that you don't have any special requirements for on_delete, you could use the option DO_NOTHING:

# ...
# ...

How to select top n rows from a datatable/dataview in ASP.NET

Data view is good Feature of data table . We can filter the data table as per our requirements using data view . Below Functions is After binding data table to list box data source then filter by text box control . ( this condition you can change as per your needs .Contains(txtSearch.Text.Trim()) )

Private Sub BindClients()

   okcl = 0

    sql = "Select * from Client Order By cname"        
    Dim dacli As New SqlClient.SqlDataAdapter
    Dim cmd As New SqlClient.SqlCommand()
    cmd.CommandText = sql
    cmd.CommandType = CommandType.Text
    dacli.SelectCommand = cmd
    dacli.SelectCommand.Connection = Me.sqlcn
    Dim dtcli As New DataTable
    lstboxc.DataSource = dataTableClients
    lstboxc.DisplayMember = "cname"
    lstboxc.ValueMember = "ccode"
    okcl = 1

    If dtcli.Rows.Count > 0 Then
        ccode = dtcli.Rows(0)("ccode")
        Call ClientDispData1()
    End If
End Sub

Private Sub FilterClients()        

    Dim query As EnumerableRowCollection(Of DataRow) = From dataTableClients In 
    dataTableClients.AsEnumerable() Where dataTableClients.Field(Of String) 
    ("cname").Contains(txtSearch.Text.Trim()) Order By dataTableClients.Field(Of 
    String)("cname") Select dataTableClients

    Dim dataView As DataView = query.AsDataView()
    lstboxc.DataSource = dataView
    lstboxc.DisplayMember = "cname"
    lstboxc.ValueMember = "ccode"
    okcl = 1
    If dataTableClients.Rows.Count > 0 Then
        ccode = dataTableClients.Rows(0)("ccode")
        Call ClientDispData1()
    End If
End Sub

PHP MySQL Query Where x = $variable

You have to do this to echo it:

echo $row['note'];

(The data is coming as an array)

Spring-Security-Oauth2: Full authentication is required to access this resource

The reason is that by default the /oauth/token endpoint is protected through Basic Access Authentication.

All you need to do is add the Authorization header to your request.

You can easily test it with a tool like curl by issuing the following command:

curl.exe --user [email protected]:12345678 http://localhost:8081/dummy-project-web/oauth/token?grant_type=client_credentials

How to hide close button in WPF window?

goto window properties set

window style = none;

u wont get close buttons...

How To Get Selected Value From UIPickerView

Getting the selected title of a picker:

let component = 0
let row = picker.selectedRow(inComponent: component)
let title = picker.delegate?.pickerView?(picker, titleForRow: row, forComponent: component)

Error: [$injector:unpr] Unknown provider: $routeProvider

In angular 1.4 +, in addition to adding the dependency

angular.module('myApp', ['ngRoute'])

,we also need to reference the separate angular-route.js file

<script src="angular.js">
<script src="angular-route.js">


What is the difference between sed and awk?

Both tools are meant to work with text and there are tasks both tools can be used for.

For me the rule to separate them is: Use sed to automate tasks you would do otherwise in a text editor manually. That's why it is called stream editor. (You can use the same commands to edit text in vim). Use awk if you want to analyze text, meaning counting fields, calculate totals, extract and reorganize structures etc.

Also you should not forget about grep. Use grep if you only want to search/extract something in a text (file)

Read/write files within a Linux kernel module

You should be aware that you should avoid file I/O from within Linux kernel when possible. The main idea is to go "one level deeper" and call VFS level functions instead of the syscall handler directly:


#include <linux/fs.h>
#include <asm/segment.h>
#include <asm/uaccess.h>
#include <linux/buffer_head.h>

Opening a file (similar to open):

struct file *file_open(const char *path, int flags, int rights) 
    struct file *filp = NULL;
    mm_segment_t oldfs;
    int err = 0;

    oldfs = get_fs();
    filp = filp_open(path, flags, rights);
    if (IS_ERR(filp)) {
        err = PTR_ERR(filp);
        return NULL;
    return filp;

Close a file (similar to close):

void file_close(struct file *file) 
    filp_close(file, NULL);

Reading data from a file (similar to pread):

int file_read(struct file *file, unsigned long long offset, unsigned char *data, unsigned int size) 
    mm_segment_t oldfs;
    int ret;

    oldfs = get_fs();

    ret = vfs_read(file, data, size, &offset);

    return ret;

Writing data to a file (similar to pwrite):

int file_write(struct file *file, unsigned long long offset, unsigned char *data, unsigned int size) 
    mm_segment_t oldfs;
    int ret;

    oldfs = get_fs();

    ret = vfs_write(file, data, size, &offset);

    return ret;

Syncing changes a file (similar to fsync):

int file_sync(struct file *file) 
    vfs_fsync(file, 0);
    return 0;

[Edit] Originally, I proposed using file_fsync, which is gone in newer kernel versions. Thanks to the poor guy suggesting the change, but whose change was rejected. The edit was rejected before I could review it.

How to switch to another domain and get-aduser

get-aduser -Server "servername" -Identity %username% -Properties *

get-aduser -Server "" -Identity testuser -Properties *

These work when you have the username. Also less to type than using the -filter property.

EDIT: Formatting.

What is the use of the @ symbol in PHP?

Suppose we haven't used the "@" operator then our code would look like this:

$fileHandle = fopen($fileName, $writeAttributes);

And what if the file we are trying to open is not found? It will show an error message.

To suppress the error message we are using the "@" operator like:

$fileHandle = @fopen($fileName, $writeAttributes);

Redirect stderr and stdout in Bash

For situation, when "piping" is necessary you can use :


For example:

echo -ne "15\n100\n"|sort -c |& tee >sort_result.txt


TIMEFORMAT=%R;for i in `seq 1 20` ; do time kubectl get pods |grep node >>js.log  ; done |& sort -h

This bash-based solutions can pipe STDOUT and STDERR separately (from STDERR of "sort -c" or from STDERR to "sort -h").

How to convert an XML file to nice pandas dataframe?

Chiming in to recommend the use of the xmltodict library. It handled your xml text pretty well and I've used it for ingesting an xml file with almost a million records. xmltodict handling xml load

AngularJS : The correct way of binding to a service properties

I would rather keep my watchers a less as possible. My reason is based on my experiences and one might argue it theoretically.
The issue with using watchers is that you can use any property on scope to call any of the methods in any component or service you like.
In a real world project, pretty soon you'll end up with a non-tracable (better said hard to trace) chain of methods being called and values being changed which specially makes the on-boarding process tragic.

Get jQuery version from inspecting the jQuery object

You can use either $().jquery; or $.fn.jquery which will return a string containing the version number, e.g. 1.6.2.

Nexus 7 (2013) and Win 7 64 - cannot install USB driver despite checking many forums and online resources

I also got this problem and found quite simple solution. I have Samsung adb driver installed on my system. I tried "Update driver" -> "Let me pick" -> "Already installed drivers" -> Samsung adb driver. That worked well.

How to get file URL using Storage facade in laravel 5?

If you need absolute URL of the file, use below code:

$file_path = \Storage::url($filename);
$url = asset($file_path);
// Output:

Android Dialog: Removing title bar

I'm using next variant:

Activity of my custom Dialog:

public class AlertDialogue extends AppCompatActivity {

    Button btnOk;
    TextView textDialog;

    protected void onCreate(Bundle savedInstanceState) {

        textDialog = (TextView)findViewById( ;
        textDialog.setText("Hello, I'm the dialog text!");

        btnOk = (Button) findViewById(;
        btnOk.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {


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

        android:text="Hello, I'm the dialog text!"
        app:layout_constraintTop_toTopOf="parent" />

        app:layout_constraintTop_toBottomOf="@+id/text_dialog" />



<activity android:name=".AlertDialogue"


<style name="AlertDialogNoTitle" parent="Theme.AppCompat.Light.Dialog">
        <item name="android:windowNoTitle">true</item>

Scala vs. Groovy vs. Clojure

Groovy is a dynamically typed language, whose syntax is very close to Java, with a number of syntax improvements that allow for lighter code and less boilerplate. It can run through an interpreter as well as being compiled, which makes it good for fast prototyping, scripts, and learning dynamic languages without having to learn a new syntax (assuming you know Java). As of Groovy 2.0, it also has growing support for static compilation. Groovy supports closures and has support for programming in a somewhat functional style, although it's still fairly far from the traditional definition of functional programming.

Clojure is a dialect of Lisp with a few advanced features like Software Transactional Memory. If you like Lisp and would like to use something like it under the JVM, Clojure is for you. It's possibly the most functional language running on the JVM, and certainly the most famous one. Also, it has a stronger emphasis on immutability than other Lisp dialects, which takes it closer to the heart of functional language enthusiasts.

Scala is a fully object oriented language, more so than Java, with one of the most advanced type systems available on non-research languages, and certainly the most advanced type system on the JVM. It also combines many concepts and features of functional languages, without compromising the object orientation, but its compromise on functional language characteristics put off some enthusiasts of the latter.

Groovy has good acceptance and a popular web framework in Grails. It also powers the Gradle build system, which is becoming a popular alternative to Maven. I personally think it is a language with limited utility, particularly as Jython and JRuby start making inroads on the JVM-land, compared to the others.

Clojure, even discounting some very interesting features, has a strong appeal just by being a Lisp dialect on JVM. It might limit its popularity, granted, but I expect it will have loyal community around it for a long time.

Scala can compete directly with Java, and give it a run for its money on almost all aspects. It can't compete in popularity at the moment, of course, and the lack of a strong corporate backing may hinder its acceptance on corporate environments. It's also a much more dynamic language than Java, in the sense of how the language evolves. From the perspective of the language, that's a good thing. From the perspective of users who plan on having thousands of lines of code written in it, not so.

As a final disclosure, I'm very familiar with Scala, and only acquainted with the other two.

CSS values using HTML5 data attribute

You can create with javascript some css-rules, which you can later use in your styles:

var addRule = (function (sheet) {
    if(!sheet) return;
    return function (selector, styles) {
        if (sheet.insertRule) return sheet.insertRule(selector + " {" + styles + "}", sheet.cssRules.length);
        if (sheet.addRule) return sheet.addRule(selector, styles);
}(document.styleSheets[document.styleSheets.length - 1]));

var i = 101;
while (i--) {
    addRule("[data-width='" + i + "%']", "width:" + i + "%");

This creates 100 pseudo-selectors like this:

[data-width='1%'] { width: 1%; }
[data-width='2%'] { width: 2%; }
[data-width='3%'] { width: 3%; }
[data-width='100%'] { width: 100%; }

Note: This is a bit offtopic, and not really what you (or someone) wants, but maybe helpful.

How to change permissions for a folder and its subfolders/files in one step?

You can use -R with chmod for recursive traversal of all files and subfolders.

You might need sudo as it depends on LAMP being installed by the current user or another one:

sudo chmod -R 755 /opt/lampp/htdocs

RVM is not a function, selecting rubies with 'rvm use ...' will not work

FWIW- I just ran across this as well, it was in the context of a cancelled selenium run. Perhaps there was a sub-shell being instantiated and left in place. Closing that terminal window and opening a new one was all I needed to do. (macOS Sierra)

Finding current executable's path without /proc/self/exe

Just my two cents. You can find the current application's directory in C/C++ with cross-platform interfaces by using this code.

void getExecutablePath(char ** path, unsigned int * pathLength)
    // Early exit when invalid out-parameters are passed
    if (!checkStringOutParameter(path, pathLength))

#if defined SYSTEM_LINUX

    // Preallocate PATH_MAX (e.g., 4096) characters and hope the executable path isn't longer (including null byte)
    char exePath[PATH_MAX];

    // Return written bytes, indicating if memory was sufficient
    int len = readlink("/proc/self/exe", exePath, PATH_MAX);

    if (len <= 0 || len == PATH_MAX) // memory not sufficient or general error occured
        invalidateStringOutParameter(path, pathLength);

    // Copy contents to caller, create caller ownership
    copyToStringOutParameter(exePath, len, path, pathLength);

#elif defined SYSTEM_WINDOWS

    // Preallocate MAX_PATH (e.g., 4095) characters and hope the executable path isn't longer (including null byte)
    char exePath[MAX_PATH];

    // Return written bytes, indicating if memory was sufficient
    unsigned int len = GetModuleFileNameA(GetModuleHandleA(0x0), exePath, MAX_PATH);
    if (len == 0) // memory not sufficient or general error occured
        invalidateStringOutParameter(path, pathLength);

    // Copy contents to caller, create caller ownership
    copyToStringOutParameter(exePath, len, path, pathLength);

#elif defined SYSTEM_SOLARIS

    // Preallocate PATH_MAX (e.g., 4096) characters and hope the executable path isn't longer (including null byte)
    char exePath[PATH_MAX];

    // Convert executable path to canonical path, return null pointer on error
    if (realpath(getexecname(), exePath) == 0x0)
        invalidateStringOutParameter(path, pathLength);

    // Copy contents to caller, create caller ownership
    unsigned int len = strlen(exePath);
    copyToStringOutParameter(exePath, len, path, pathLength);

#elif defined SYSTEM_DARWIN

    // Preallocate PATH_MAX (e.g., 4096) characters and hope the executable path isn't longer (including null byte)
    char exePath[PATH_MAX];

    unsigned int len = (unsigned int)PATH_MAX;

    // Obtain executable path to canonical path, return zero on success
    if (_NSGetExecutablePath(exePath, &len) == 0)
        // Convert executable path to canonical path, return null pointer on error
        char * realPath = realpath(exePath, 0x0);

        if (realPath == 0x0)
            invalidateStringOutParameter(path, pathLength);

        // Copy contents to caller, create caller ownership
        unsigned int len = strlen(realPath);
        copyToStringOutParameter(realPath, len, path, pathLength);

    else // len is initialized with the required number of bytes (including zero byte)
        char * intermediatePath = (char *)malloc(sizeof(char) * len);

        // Convert executable path to canonical path, return null pointer on error
        if (_NSGetExecutablePath(intermediatePath, &len) != 0)
            invalidateStringOutParameter(path, pathLength);

        char * realPath = realpath(intermediatePath, 0x0);


        // Check if conversion to canonical path succeeded
        if (realPath == 0x0)
            invalidateStringOutParameter(path, pathLength);

        // Copy contents to caller, create caller ownership
        unsigned int len = strlen(realPath);
        copyToStringOutParameter(realPath, len, path, pathLength);


#elif defined SYSTEM_FREEBSD

    // Preallocate characters and hope the executable path isn't longer (including null byte)
    char exePath[2048];

    unsigned int len = 2048;

    int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1 };

    // Obtain executable path by syscall
    if (sysctl(mib, 4, exePath, &len, 0x0, 0) != 0)
        invalidateStringOutParameter(path, pathLength);

    // Copy contents to caller, create caller ownership
    copyToStringOutParameter(exePath, len, path, pathLength);


    // If no OS could be detected ... degrade gracefully
    invalidateStringOutParameter(path, pathLength);


You can take a look in detail here.

Fixed size div?

You can also hard code in the dimensions in your html code as opposed to putting the desired dimensions in a style sheet

<div id="mainDiv">
    <div id="mydiv" style="height:150px; width:150px;">

Java 8 Streams: multiple filters vs. complex condition

This test shows that your second option can perform significantly better. Findings first, then the code:

one filter with predicate of form u -> exp1 && exp2, list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=4142, min=29, average=41.420000, max=82}
two filters with predicates of form u -> exp1, list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=13315, min=117, average=133.150000, max=153}
one filter with predicate of form predOne.and(pred2), list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=10320, min=82, average=103.200000, max=127}

now the code:

enum Gender {

static class User {
    Gender gender;
    int age;

    public User(Gender gender, int age){
        this.gender = gender;
        this.age = age;

    public Gender getGender() {
        return gender;

    public void setGender(Gender gender) {
        this.gender = gender;

    public int getAge() {
        return age;

    public void setAge(int age) {
        this.age = age;

static long test1(List<User> users){
    long time1 = System.currentTimeMillis();
            .filter((u) -> u.getGender() == Gender.FEMALE && u.getAge() % 2 == 0)
            .allMatch(u -> true);                   // least overhead terminal function I can think of
    long time2 = System.currentTimeMillis();
    return time2 - time1;

static long test2(List<User> users){
    long time1 = System.currentTimeMillis();
            .filter(u -> u.getGender() == Gender.FEMALE)
            .filter(u -> u.getAge() % 2 == 0)
            .allMatch(u -> true);                   // least overhead terminal function I can think of
    long time2 = System.currentTimeMillis();
    return time2 - time1;

static long test3(List<User> users){
    long time1 = System.currentTimeMillis();
            .filter(((Predicate<User>) u -> u.getGender() == Gender.FEMALE).and(u -> u.getAge() % 2 == 0))
            .allMatch(u -> true);                   // least overhead terminal function I can think of
    long time2 = System.currentTimeMillis();
    return time2 - time1;

public static void main(String... args) {
    int size = 10000000;
    List<User> users =
            .mapToObj(i -> i % 2 == 0 ? new User(Gender.MALE, i % 100) : new User(Gender.FEMALE, i % 100))
            .collect(Collectors.toCollection(()->new ArrayList<>(size)));
    repeat("one filter with predicate of form u -> exp1 && exp2", users, Temp::test1, 100);
    repeat("two filters with predicates of form u -> exp1", users, Temp::test2, 100);
    repeat("one filter with predicate of form predOne.and(pred2)", users, Temp::test3, 100);

private static void repeat(String name, List<User> users, ToLongFunction<List<User>> test, int iterations) {
    System.out.println(name + ", list size " + users.size() + ", averaged over " + iterations + " runs: " + IntStream.range(0, iterations)
            .mapToLong(i -> test.applyAsLong(users))

Setting the height of a DIV dynamically

What should happen in the case of overflow? If you want it to just get to the bottom of the window, use absolute positioning:

div {
  position: absolute;
  top: 300px;
  bottom: 0px;
  left: 30px;
  right: 30px;

This will put the DIV 30px in from each side, 300px from the top of the screen, and flush with the bottom. Add an overflow:auto; to handle cases where the content is larger than the div.

Edit: @Whoever marked this down, an explanation would be nice... Is something wrong with the answer?

Get the data received in a Flask request

To post JSON with jQuery in JavaScript, use JSON.stringify to dump the data, and set the content type to application/json.

var value_data = [1, 2, 3, 4];

    type: 'POST',
    url: '/process',
    data: JSON.stringify(value_data),
    contentType: 'application/json',
    success: function (response_data) {

Parse it in Flask with request.get_json().

data = request.get_json()

How to detect the device orientation using CSS media queries?

I think we need to write more specific media query. Make sure if you write one media query it should be not effect to other view (Mob,Tab,Desk) otherwise it can be trouble. I would like suggest to write one basic media query for respective device which cover both view and one orientation media query that you can specific code more about orientation view its for good practice. we Don't need to write both media orientation query at same time. You can refer My below example. I am sorry if my English writing is not much good. Ex:

For Mobile

@media screen and (max-width:767px) {

..This is basic media query for respective device.In to this media query  CSS code cover the both view landscape and portrait view.


@media screen and (min-width:320px) and (max-width:767px) and (orientation:landscape) {

..This orientation media query. In to this orientation media query you can specify more about CSS code for landscape view.


For Tablet

@media screen and (max-width:1024px){
..This is basic media query for respective device.In to this media query  CSS code cover the both view landscape and portrait view.
@media screen and (min-width:768px) and (max-width:1024px) and (orientation:landscape){

..This orientation media query. In to this orientation media query you can specify more about CSS code for landscape view.



make as per your design requirement enjoy...(:

Thanks, Jitu

Open a new tab on button click in AngularJS

You should use the $location service

Angular docs:

Check if a string is null or empty in XSLT

I actually found it better just testing for string length since many times the field is not null, just empty

<xsl:when test="string-length(field-you-want-to-test)<1">

How To limit the number of characters in JTextField?

I have solved this problem by using the following code segment:

private void jTextField1KeyTyped(java.awt.event.KeyEvent evt) {
    boolean max = jTextField1.getText().length() > 4;
    if ( max ){

How do I add 24 hours to a unix timestamp in php?

Unix timestamp is in seconds, so simply add the corresponding number of seconds to the timestamp:

$timeInFuture = time() + (60 * 60 * 24);

How to scroll to an element?

I used this inside a onclick function to scroll smoothly to a div where its id is "step2Div".

let offset = 100;
    behavior: "smooth",
    document.getElementById("step2Div").getBoundingClientRect().top -
    document.body.getBoundingClientRect().top -

Google Maps API - how to get latitude and longitude from Autocomplete without showing the map?

You can get from the same api without any additional api or url call.


<input class="wd100" id="fromInput" type="text" name="grFrom" placeholder="From" required/>


var input = document.getElementById('fromInput');
var defaultBounds = new google.maps.LatLngBounds(
    new google.maps.LatLng(-33.8902, 151.1759),
    new google.maps.LatLng(-33.8474, 1512631)

var options = {
bounds: defaultBounds   

var autocomplete = new google.maps.places.Autocomplete(input, options);
var searchBox = new google.maps.places.SearchBox(input, {
         bounds: defaultBounds

google.maps.event.addListener(searchBox, 'places_changed', function() {
    var places = searchBox.getPlaces();

console.log(places[0].geometry.location.G); // Get Latitude
console.log(places[0].geometry.location.K); // Get Longitude

//Additional information
console.log(places[0].formatted_address); // Formated Address of Place
console.log(places[0].name); // Name of Place

    if (places.length == 0) {

    var bounds = new google.maps.LatLngBounds();

Get checkbox list values with jQuery

You can try this...

$(document).ready(function() {
            var checkBoxValues = [];
            $.each($("input[name='check_name']:checked"), function(){



Differences between and websockets

Im going to provide an argument against using

I think using solely because it has fallbacks isnt a good idea. Let IE8 RIP.

In the past there have been many cases where new versions of NodeJS has broken You can check these lists for examples...

If you go to develop an Android app or something that needs to work with your existing app, you would probably be okay working with WS right away, might give you some trouble there...

Plus the WS module for Node.JS is amazingly simple to use.

How to get the path of running java program

    ClassLoader cl = ClassLoader.getSystemClassLoader();

    URL[] urls = ((URLClassLoader)cl).getURLs();

    for(URL url: urls){

How to delete rows in tables that contain foreign keys to other tables

Need to set the foreign key option as on delete cascade... in tables which contains foreign key columns.... It need to set at the time of table creation or add later using ALTER table

Display all post meta keys and meta values of the same post ID in wordpress

As of Jan 2020 and WordPress v5.3.2, I confirm the following works fine.

It will include the field keys with their equivalent underscore keys as well, but I guess if you properly "enum" your keys in your code, that should be no problem:

$meta_values   = get_post_meta( get_the_ID() );
$example_field = meta_values['example_field_key'][0];

//OR if you do enum style 
//(emulation of a class with a list of *const* as enum does not exist in PHP per se)
$example_field = meta_values[PostTypeEnum::FIELD_EXAMPLE_KEY][0]; 

As the print_r(meta_values); gives:

    [_edit_lock] => Array
            [0] => 1579542560:1

    [_edit_last] => Array
            [0] => 1

    [example_field] => Array
            [0] => 13

Hope that helps someone, go make a ruckus!

Bootstrap 3 - Responsive mp4-video

using that code wil give you a responsive video player with full control

<div class="embed-responsive embed-responsive-16by9">
    <iframe class="embed-responsive-item" width="640" height="480" src="" frameborder="0" allowfullscreen></iframe>

What is your single most favorite command-line trick using Bash?

Want to get the last few lines of a log file?

tail /var/log/syslog

Want to keep an eye on a log file for when it changes?

tail -f /var/log/syslog

Want to quickly read over a file from the start?

more /var/log/syslog

Want to quickly find if a file contains some text?

grep "find this text" /var/log/syslog

Java enum - why use toString instead of name

Use name() when you want to make a comparison or use the hardcoded value for some internal use in your code.

Use toString() when you want to present information to a user (including a developper looking at a log). Never rely in your code on toString() giving a specific value. Never test it against a specific string. If your code breaks when someone correctly changes the toString() return, then it was already broken.

From the javadoc (emphasis mine) :

Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.

How do I show the schema of a table in a MySQL database?

Perhaps the question needs to be slightly more precise here about what is required because it can be read it two different ways. i.e.

  1. How do I get the structure/definition for a table in mysql?
  2. How do I get the name of the schema/database this table resides in?

Given the accepted answer, the OP clearly intended it to be interpreted the first way. For anybody reading the question the other way try

SELECT `table_schema` 
FROM `information_schema`.`tables` 
WHERE `table_name` = 'whatever';

Set opacity of background image without affecting child elements

Just to add to the can use the alpha channel with the new color attributes eg. rgba(0,0,0,0) ok so this is black but with zero opacity so as a parent it will not affect the child. This only works on Chrome, FF, Safari and....I thin O.

convert your hex colours to RGBA

Getting a count of objects in a queryset in django

Use related name to count votes for a specific contest

class Item(models.Model):
    name = models.CharField()

class Contest(models.Model);
    name = models.CharField()

class Votes(models.Model):
    user = models.ForeignKey(User)
    item = models.ForeignKey(Item)
    contest = models.ForeignKey(Contest, related_name="contest_votes")
    comment = models.TextField()

>>> comments = Contest.objects.get(id=contest_id).contest_votes.count()

Ajax using https on an http page


most JS libraries make it just as easy as other AJAX calls, but internally use an iframe to do the query.

if you're not using JSON for your payload, then you'll have to roll your own mechanism around the iframe.

personally, i'd just redirect form the http:// page to the https:// one

How can I take a screenshot/image of a website using Python?

Try this..

#!/usr/bin/env python

import gtk.gdk

import time

import random

while 1 :
    # generate a random time between 120 and 300 sec
    random_time = random.randrange(120,300)

    # wait between 120 and 300 seconds (or between 2 and 5 minutes)
    print "Next picture in: %.2f minutes" % (float(random_time) / 60)


    w = gtk.gdk.get_default_root_window()
    sz = w.get_size()

    print "The size of the window is %d x %d" % sz

    pb = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB,False,8,sz[0],sz[1])
    pb = pb.get_from_drawable(w,w.get_colormap(),0,0,0,0,sz[0],sz[1])

    ts = time.time()
    filename = "screenshot"
    filename += str(ts)
    filename += ".png"

    if (pb != None):,"png")
        print "Screenshot saved to "+filename
        print "Unable to get the screenshot."

Let JSON object accept bytes or let urlopen output strings

For anyone else trying to solve this using the requests library:

import json
import requests

r = requests.get('http://localhost/index.json')
# works for Python2 and Python3

subsetting a Python DataFrame

Creating an Empty Dataframe with known Column Name:

Names = ['Col1','ActivityID','TransactionID']
df = pd.DataFrame(columns = Names)

Creating a dataframe from csv:

df = pd.DataFrame('...../file_name.csv')

Creating a dynamic filter to subset a dtaframe:

i = 12
df[df['ActivitiID'] <= i]

Creating a dynamic filter to subset required columns of dtaframe

df[df['ActivityID'] == i][['TransactionID','ActivityID']]

Visual studio code CSS indentation and formatting

Yes, try installing vscode-css-formatter extension.
It just adds the functionality to format .css files and the shortcut stays the same Alt+Shift+F.

Trigger change event of dropdown

alternatively you can put onchange attribute on the dropdownlist itself, that onchange will call certain jquery function like this.

<input type="dropdownlist" onchange="jqueryFunc()">

<script type="text/javascript">
        //something goes here

hope this one helps you, and please note that this code is just a rough draft, not tested on any ide. thanks

Ignore outliers in ggplot2 boxplot

One idea would be to winsorize the data in a two-pass procedure:

  1. run a first pass, learn what the bounds are, e.g. cut of at given percentile, or N standard deviation above the mean, or ...

  2. in a second pass, set the values beyond the given bound to the value of that bound

I should stress that this is an old-fashioned method which ought to be dominated by more modern robust techniques but you still come across it a lot.

Where do I put my php files to have Xampp parse them?

Look into the httpd.conf and/or httpd-vhosts.conf files and search for the DocumentRoot entry. If you configure multiple virtual hosts, there may be more than one of those, separated in <VirtualHost> tags.

SyntaxError: multiple statements found while compiling a single statement

In the shell, you can't execute more than one statement at a time:

>>> x = 5
y = 6
SyntaxError: multiple statements found while compiling a single statement

You need to execute them one by one:

>>> x = 5
>>> y = 6

When you see multiple statements are being declared, that means you're seeing a script, which will be executed later. But in the interactive interpreter, you can't do more than one statement at a time.

How to utilize date add function in Google spreadsheet?

You can just add the number to the cell with the date.

so if A1: 12/3/2012 and A2: =A1+7 then A2 would display 12/10/2012

Convert dictionary to list collection in C#

If you want convert Keys:

List<string> listNumber = dicNumber.Keys.ToList();

else if you want convert Values:

List<string> listNumber = dicNumber.Values.ToList();

Simple post to Web Api

It's been quite sometime since I asked this question. Now I understand it more clearly, I'm going to put a more complete answer to help others.

In Web API, it's very simple to remember how parameter binding is happening.

  • if you POST simple types, Web API tries to bind it from the URL
  • if you POST complex type, Web API tries to bind it from the body of the request (this uses a media-type formatter).

  • If you want to bind a complex type from the URL, you'll use [FromUri] in your action parameter. The limitation of this is down to how long your data going to be and if it exceeds the url character limit.

    public IHttpActionResult Put([FromUri] ViewModel data) { ... }

  • If you want to bind a simple type from the request body, you'll use [FromBody] in your action parameter.

    public IHttpActionResult Put([FromBody] string name) { ... }

as a side note, say you are making a PUT request (just a string) to update something. If you decide not to append it to the URL and pass as a complex type with just one property in the model, then the data parameter in jQuery ajax will look something like below. The object you pass to data parameter has only one property with empty property name.

var myName = 'ABC';
$.ajax({url:.., data: {'': myName}});

and your web api action will look something like below.

public IHttpActionResult Put([FromBody] string name){ ... }

This page explains it all.

How to create friendly URL in php?

I try to explain this problem step by step in following example.

0) Question

I try to ask you like this :

i want to open page like facebook profile

it get id from url and parse it to profile.php file and return featch data from database and show user to his profile

normally when we develope any website its link look like

now we update with new style not rewrite we use or as permalink (get a profile by the ID) (get a profile by the username) (get the profile of the currently logged-in user)

1) .htaccess

Create a .htaccess file in the root folder or update the existing one :

Options +FollowSymLinks
# Turn on the RewriteEngine
RewriteEngine On
#  Rules
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php

What does that do ?

If the request is for a real directory or file (one that exists on the server), index.php isn't served, else every url is redirected to index.php.

2) index.php

Now, we want to know what action to trigger, so we need to read the URL :

In index.php :

// index.php    

// This is necessary when index.php is not in the root folder, but in some subfolder...
// We compare $requestURL and $scriptName to remove the inappropriate values
$requestURI = explode(‘/’, $_SERVER[‘REQUEST_URI’]);
$scriptName = explode(‘/’,$_SERVER[‘SCRIPT_NAME’]);

for ($i= 0; $i < sizeof($scriptName); $i++)
    if ($requestURI[$i] == $scriptName[$i])

$command = array_values($requestURI);
With the url, $command would contain :

$command = array(
    [0] => 'profile',
    [1] => 19837,
    [2] => ,
Now, we have to dispatch the URLs. We add this in the index.php :

// index.php

require_once("profile.php"); // We need this file
    case ‘profile’ :
        // We run the profile function from the profile.php file.
    case ‘myprofile’ :
        // We run the myProfile function from the profile.php file.
        // Wrong page ! You could also redirect to your custom 404 page.
        echo "404 Error : wrong page.";

2) profile.php

Now in the profile.php file, we should have something like this :

// profile.php

function profile($chars)
    // We check if $chars is an Integer (ie. an ID) or a String (ie. a potential username)

    if (is_int($chars)) {
        $id = $chars;
        // Do the SQL to get the $user from his ID
        // ........
    } else {
        $username = mysqli_real_escape_string($char);
        // Do the SQL to get the $user from his username
        // ...........

    // Render your view with the $user variable
    // .........

function myProfile()
    // Get the currently logged-in user ID from the session :
    $id = ....

    // Run the above function :

<DIV> inside link (<a href="">) tag

I would just format two different a-tags with a { display: block; height: 15px; width: 40px; } . This way you don't even need the div-tags...

Can I run javascript before the whole page is loaded?

Not only can you, but you have to make a special effort not to if you don't want to. :-)

When the browser encounters a classic script tag when parsing the HTML, it stops parsing and hands over to the JavaScript interpreter, which runs the script. The parser doesn't continue until the script execution is complete (because the script might do document.write calls to output markup that the parser should handle).

That's the default behavior, but you have a few options for delaying script execution:

  1. Use JavaScript modules. A type="module" script is deferred until the HTML has been fully parsed and the initial DOM created. This isn't the primary reason to use modules, but it's one of the reasons:

    <script type="module" src="./my-code.js"></script>
    <!-- Or -->
    <script type="module">
    // Your code here

    The code will be fetched (if it's separate) and parsed in parallel with the HTML parsing, but won't be run until the HTML parsing is done. (If your module code is inline rather than in its own file, it is also deferred until HTML parsing is complete.)

    This wasn't available when I first wrote this answer in 2010, but here in 2020, all major modern browsers support modules natively, and if you need to support older browsers, you can use bundlers like Webpack and Rollup.js.

  2. Use the defer attribute on a classic script tag:

    <script defer src="./my-code.js"></script>

    As with the module, the code in my-code.js will be fetched and parsed in parallel with the HTML parsing, but won't be run until the HTML parsing is done. But, defer doesn't work with inline script content, only with external files referenced via src.

  3. I don't think it's what you want, but you can use the async attribute to tell the browser to fetch the JavaScript code in parallel with the HTML parsing, but then run it as soon as possible, even if the HTML parsing isn't complete. You can put it on a type="module" tag, or use it instead of defer on a classic script tag.

  4. Put the script tag at the end of the document, just prior to the closing </body> tag:

    <!doctype html>
    <!-- ... -->
    <!-- The document's HTML goes here -->
    <script type="module" src="./my-code.js"></script><!-- Or inline script -->

    That way, even though the code is run as soon as its encountered, all of the elements defined by the HTML above it exist and are ready to be used.

    It used to be that this caused an additional delay on some browsers because they wouldn't start fetching the code until the script tag was encountered, but modern browsers scan ahead and start prefetching. Still, this is very much the third choice at this point, both modules and defer are better options.

The spec has a useful diagram showing a raw script tag, defer, async, type="module", and type="module" async and the timing of when the JavaScript code is fetched and run:

enter image description here

Here's an example of the default behavior, a raw script tag:

.found {_x000D_
    color: green;_x000D_
<p>Paragraph 1</p>_x000D_
    if (typeof NodeList !== "undefined" && !NodeList.prototype.forEach) {_x000D_
        NodeList.prototype.forEach = Array.prototype.forEach;_x000D_
    document.querySelectorAll("p").forEach(p => {_x000D_
<p>Paragraph 2</p>

(See my answer here for details around that NodeList code.)

When you run that, you see "Paragraph 1" in green but "Paragraph 2" is black, because the script ran synchronously with the HTML parsing, and so it only found the first paragraph, not the second.

In contrast, here's a type="module" script:

.found {_x000D_
    color: green;_x000D_
<p>Paragraph 1</p>_x000D_
<script type="module">_x000D_
    document.querySelectorAll("p").forEach(p => {_x000D_
<p>Paragraph 2</p>

Notice how they're both green now; the code didn't run until HTML parsing was complete. That would also be true with a defer script with external content (but not inline content).

(There was no need for the NodeList check there because any modern browser supporting modules already has forEach on NodeList.)

In this modern world, there's no real value to the DOMContentLoaded event of the "ready" feature that PrototypeJS, jQuery, ExtJS, Dojo, and most others provided back in the day (and still provide); just use modules or defer. Even back in the day, there wasn't much reason for using them (and they were often used incorrectly, holding up page presentation while the entire jQuery library was loaded because the script was in the head instead of after the document), something some developers at Google flagged up early on. This was also part of the reason for the YUI recommendation to put scripts at the end of the body, again back in the day.

To get total number of columns in a table in sql

The below query will display all the tables and corresponding column count in a database schema

SELECT Table_Name, count(*) as [No.of Columns]
WHERE table_schema = 'dbo' -- schema name
group by table_name

Getting a 500 Internal Server Error on Laravel 5+ Ubuntu 14.04

First allow all permissions for your project folder (let say it's called laravel), for the storage subfolder and its logs subsubfolder and for the vendor subfolder (laravel/storage, laravel/storage/logs and laravel/vendor).

Then check if your have .env file - if not you can run:

$ mv .env.example .env

to rename your build-in .env.example to the needed .env.

Otherwise turn on the debug mode - open .env and set


and open laravel/config/app.php and change

'debug' => env('APP_DEBUG', false), 


'debug' => env('APP_DEBUG', true),

so you can find out what is the reason for your error.

GitHub: invalid username or password

There is a issue on Windows using cmd-Greetings

There is a issue on Windows using cmd-Greetings who will not let you clone private repositories. Remove that cmd-greeting described in this documentation (keyword Command Processor):


I can confirm that other clients like SourceTree, GitKraken, Tower and TortoiseGit affected to this issue too.

pandas read_csv index_col=None not working with delimiters at the end of each line

Re: craigts's response, for anyone having trouble with using either False or None parameters for index_col, such as in cases where you're trying to get rid of a range index, you can instead use an integer to specify the column you want to use as the index. For example:

df = pd.read_csv('file.csv', index_col=0)

The above will set the first column as the index (and not add a range index in my "common case").


Given the popularity of this answer, I thought i'd add some context/ a demo:

# Setting up the dummy data
In [1]: df = pd.DataFrame({"A":[1, 2, 3], "B":[4, 5, 6]})

In [2]: df
   A  B
0  1  4
1  2  5
2  3  6

In [3]: df.to_csv('file.csv', index=None)
A  B
1  4
2  5
3  6

Reading without index_col or with None/False will all result in a range index:

In [4]: pd.read_csv('file.csv')
   A  B
0  1  4
1  2  5
2  3  6

# Note that this is the default behavior, so the same as In [4]
In [5]: pd.read_csv('file.csv', index_col=None)
   A  B
0  1  4
1  2  5
2  3  6

In [6]: pd.read_csv('file.csv', index_col=False)
   A  B
0  1  4
1  2  5
2  3  6

However, if we specify that "A" (the 0th column) is actually the index, we can avoid the range index:

In [7]: pd.read_csv('file.csv', index_col=0)
1  4
2  5
3  6

Where can I set path to make.exe on Windows?

The path is in the registry but usually you edit through this interface:

  1. Go to Control Panel -> System -> System settings -> Environment Variables.
  2. Scroll down in system variables until you find PATH.
  3. Click edit and change accordingly.
  4. BE SURE to include a semicolon at the end of the previous as that is the delimiter, i.e. c:\path;c:\path2
  5. Launch a new console for the settings to take effect.

How to change value of ArrayList element in java

Change it to for(int i=0;i<=9;i++)

XML parsing of a variable string in JavaScript

Updated answer for 2017

The following will parse an XML string into an XML document in all major browsers. Unless you need support for IE <= 8 or some obscure browser, you could use the following function:

function parseXml(xmlStr) {
   return new window.DOMParser().parseFromString(xmlStr, "text/xml");

If you need to support IE <= 8, the following will do the job:

var parseXml;

if (typeof window.DOMParser != "undefined") {
    parseXml = function(xmlStr) {
        return new window.DOMParser().parseFromString(xmlStr, "text/xml");
} else if (typeof window.ActiveXObject != "undefined" &&
       new window.ActiveXObject("Microsoft.XMLDOM")) {
    parseXml = function(xmlStr) {
        var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async = "false";
        return xmlDoc;
} else {
    throw new Error("No XML parser found");

Once you have a Document obtained via parseXml, you can use the usual DOM traversal methods/properties such as childNodes and getElementsByTagName() to get the nodes you want.

Example usage:

var xml = parseXml("<foo>Stuff</foo>");

If you're using jQuery, from version 1.5 you can use its built-in parseXML() method, which is functionally identical to the function above.

var xml = $.parseXML("<foo>Stuff</foo>");

Set value of hidden field in a form using jQuery's ".val()" doesn't work

Simply use syntax below get and set


var a = $("#selectIndex").val();

here a variable will hold the value of hiddenfield(selectindex)

Server side

<asp:HiddenField ID="selectIndex" runat="server" Value="0" />


var a =10;

memcpy() vs memmove()

The memory in memcpy cannot overlap or you risk undefined behaviour, while the memory in memmove can overlap.

char a[16];
char b[16];

memcpy(a,b,16);           // valid
memmove(a,b,16);          // Also valid, but slower than memcpy.
memcpy(&a[0], &a[1],10);  // Not valid since it overlaps.
memmove(&a[0], &a[1],10); // valid. 

Some implementations of memcpy might still work for overlapping inputs but you cannot count of that behaviour. While memmove must allow for overlapping.

/lib/ bad ELF interpreter: No such file or directory

As @borayeris said,

yum install glibc.i686

But if you cannot find glibc.i686 or libstdc++ package, try -

sudo yum search glibc
sudo yum search libstd

and then,

sudo yum install {package}

Align the form to the center in Bootstrap 4

All above answers perfectly gives the solution to center the form using Bootstrap 4. However, if someone wants to use out of the box Bootstrap 4 css classes without help of any additional styles and also not wanting to use flex, we can do like this.

A sample form

enter image description here


<div class="container-fluid h-100 bg-light text-dark">
  <div class="row justify-content-center align-items-center">
  <div class="row justify-content-center align-items-center h-100">
    <div class="col col-sm-6 col-md-6 col-lg-4 col-xl-3">
      <form action="">
        <div class="form-group">
          <select class="form-control">
                    <option>Option 1</option>
                    <option>Option 2</option>
        <div class="form-group">
          <input type="text" class="form-control" />
        <div class="form-group text-center">
          <div class="form-check-inline">
            <label class="form-check-label">
    <input type="radio" class="form-check-input" name="optradio">Option 1
          <div class="form-check-inline">
            <label class="form-check-label">
    <input type="radio" class="form-check-input" name="optradio">Option 2
          <div class="form-check-inline">
            <label class="form-check-label">
    <input type="radio" class="form-check-input" name="optradio" disabled>Option 3
        <div class="form-group">
          <div class="container">
            <div class="row">
              <div class="col"><button class="col-6 btn btn-secondary btn-sm float-left">Reset</button></div>
              <div class="col"><button class="col-6 btn btn-primary btn-sm float-right">Submit</button></div>


Link to CodePen

I hope this helps someone. Thank you.

Appending to an object

Now with ES6 we have a very powerful spread operator (...Object) which can make this job very easy. It can be done as follows:

let alerts = { 
   1: { app: 'helloworld', message: 'message' },
   2: { app: 'helloagain', message: 'another message' }

//now suppose you want to add another key called alertNo. with value 2 in the alerts object. 

alerts = {
   alertNo: 2

Thats it. It will add the key you want. Hope this helps!!

Convert from days to milliseconds

You can use this utility class -

public class DateUtils
    public static final long SECOND_IN_MILLIS = 1000;
    public static final long MINUTE_IN_MILLIS = SECOND_IN_MILLIS * 60;
    public static final long HOUR_IN_MILLIS = MINUTE_IN_MILLIS * 60;
    public static final long DAY_IN_MILLIS = HOUR_IN_MILLIS * 24;
    public static final long WEEK_IN_MILLIS = DAY_IN_MILLIS * 7;

If you are working on Android framework then just import it (also named DateUtils) under package android.text.format

Change header background color of modal of twitter bootstrap

Add this class to your css file to override the bootstrap class.modal-header

.modal-header {

It's important try to never edit Bootstrap CSS, in order to be able to update from the repo and not loose the changes made or break something in futures releases.

Foreach in a Foreach in MVC View

Try this:

It looks like you are looping for every product each time, now this is looping for each product that has the same category ID as the current category being looped

<div id="accordion1" style="text-align:justify">
@using (Html.BeginForm())
    foreach (var category in Model.Categories)

                @foreach (var product in Model.Product.Where(m=> m.CategoryID= category.CategoryID)
                        @if (System.Web.Security.UrlAuthorizationModule.CheckUrlAccessForPrincipal("/admin", User, "GET"))
                            @Html.Raw(" - ")  
                            @Html.ActionLink("Edit", "Edit", new { id = product.ID })

Passive Link in Angular 2 - <a href=""> equivalent

Updated for Angular2 RC4:

import {HostListener, Directive, Input} from '@angular/core';

    selector: '[href]'
export class PreventDefaultLinkDirective {

    @Input() href;
    @HostListener('click', ['$event']) onClick(event) {this.preventDefault(event);}

    private preventDefault(event) {
        if (this.href.length === 0 || this.href === '#') {


bootstrap(App, [provide(PLATFORM_DIRECTIVES, {useValue: PreventDefaultLinkDirective, multi: true})]);

Read remote file with node.js (http.get)

You can do something like this, without using any external libraries.

const fs = require("fs");
const https = require("https");

const file = fs.createWriteStream("data.txt");

https.get("", response => {
  var stream = response.pipe(file);

  stream.on("finish", function() {

Maven build Compilation error : Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project Maven

Add the following in your pom.xml and do CTRL+S, it will automatically build the project.


Now click on Run as >Maven Test.

This error will definitely get solved.

Proper indentation for Python multiline strings

I'm having a similar issue, code got really unreadable using multilines, I came out with something like

"""   """bbb

yes, at beginning could look terrible but the embedded syntax was quite complex and adding something at the end (like '\n"') was not a solution

How to recursively find and list the latest modified files in a directory with subdirectories and times

@anubhava's answer is great, but unfortunately won't work on BSD tools – i.e. it won't work with the find that comes installed by default on macOS, because BSD find doesn't have the -printf operator.

So here's a variation that works with macOS + BSD (tested on my Catalina Mac), which combines BSD find with xargs and stat:

$ find . -type f -print0 \
      | xargs -0 -n1 -I{} stat -f '%Fm %N' "{}" \
      | sort -rn 

While I'm here, here's BSD command sequence I like to use, which puts the timestamp in ISO-8601 format

$ find . -type f -print0 \
    | xargs -0 -n1 -I{} \
       stat  -f '%Sm %N' -t '%Y-%m-%d %H:%M:%S' "{}" \
    | sort -rn

(note that both my answers, unlike @anubhava's, pass the filenames from find to xargs as a single argument rather than a \0 terminated list, which changes what gets piped out at the very end)

And here's the GNU version (i.e. @anubhava's answer, but in iso-8601 format):

$ gfind . -type f -printf "%T+ %p\0" | sort -zk1nr

Related q: find lacks the option -printf, now what?

Get img src with PHP

I know people say you shouldn't use regular expressions to parse HTML, but in this case I find it perfectly fine.

$string = '<img border="0" src="/images/image.jpg" alt="Image" width="100" height="100" />';
preg_match('/<img(.*)src(.*)=(.*)"(.*)"/U', $string, $result);
$foo = array_pop($result);

How to make a div center align in HTML

<!DOCTYPE html>_x000D_
    <div style="text-align: center;">_x000D_
      <div style="width: 500px; margin: 0 auto; background: #000; color: #fff;">This DIV is centered</div>_x000D_

Tested and worked in IE, Firefox, Chrome, Safari and Opera. I did not test IE6. The outer text-align is needed for IE. Other browsers (and IE9?) will work when you give the DIV margin (left and right) value of auto. Margin "0 auto" is a shorthand for margin "0 auto 0 auto" (top right bottom left).

Note: the text is also centered inside the inner DIV, if you want it to remain on the left side just specify text-align: left; for the inner DIV.

Edit: IE 6, 7, 8 and 9 running on the Standards Mode will work with margins set to auto.

Is there a goto statement in Java?

No, thankfully, there isn't goto in Java.

The goto keyword is only reserved, but not used (the same goes for const).

How to thoroughly purge and reinstall postgresql on ubuntu?

I just ran into the same issue for Ubuntu 13.04. These commands removed Postgres 9.1:

sudo apt-get purge postgresql
sudo apt-get autoremove postgresql

It occurs to me that perhaps only the second command is necessary, but from there I was able to install Postgres 9.2 (sudo apt-get install postgresql-9.2).

Validate IPv4 address in Java

Pretty simple with Regular Expression (but note this is much less efficient and much harder to read than worpet's answer that uses an Apache Commons Utility)

private static final Pattern PATTERN = Pattern.compile(

public static boolean validate(final String ip) {
    return PATTERN.matcher(ip).matches();

Based on post Mkyong

Scala: what is the best way to append an element to an Array?

You can use :+ to append element to array and +: to prepend it:

0 +: array :+ 4

should produce:

res3: Array[Int] = Array(0, 1, 2, 3, 4)

It's the same as with any other implementation of Seq.

How to make an Android device vibrate? with different frequency?

Update 2017 vibrate(interval) method is deprecated with Android-O(API 8.0)

To support all Android versions use this method.

// Vibrate for 150 milliseconds
private void shakeItBaby() {
    if (Build.VERSION.SDK_INT >= 26) {
        ((Vibrator) getSystemService(VIBRATOR_SERVICE)).vibrate(VibrationEffect.createOneShot(150, VibrationEffect.DEFAULT_AMPLITUDE));
    } else {
        ((Vibrator) getSystemService(VIBRATOR_SERVICE)).vibrate(150);


// Vibrate for 150 milliseconds
private fun shakeItBaby(context: Context) {
    if (Build.VERSION.SDK_INT >= 26) {
        (context.getSystemService(VIBRATOR_SERVICE) as Vibrator).vibrate(VibrationEffect.createOneShot(150, VibrationEffect.DEFAULT_AMPLITUDE))
    } else {
        (context.getSystemService(VIBRATOR_SERVICE) as Vibrator).vibrate(150)

How to scroll to top of a div using jQuery?

This is my solution to scroll to the top on a button click.

$(".btn").click(function () {
if ($(this).text() == "Show options") {
    scrollTop: $(window).scrollTop(0)

How to use bootstrap datepicker

You should include bootstrap-datepicker.js after bootstrap.js and you should bind the datepicker to your control.

      format: 'mm-dd-yyyy'

Font from origin has been blocked from loading by Cross-Origin Resource Sharing policy

For those using Microsoft products with a web.config file:

Merge this with your web.config.

To allow on any domain replace value="domain" with value="*"

<?xml version="1.0" encoding="utf-8" ?>
        <add name="Access-Control-Allow-Origin" value="domain" />

If you don't have permission to edit web.config, then add this line in your server-side code.

Response.AppendHeader("Access-Control-Allow-Origin", "domain");

What's the difference between returning value or Promise.resolve from then()

In simple terms, inside a then handler function:

A) When x is a value (number, string, etc):

  1. return x is equivalent to return Promise.resolve(x)
  2. throw x is equivalent to return Promise.reject(x)

B) When x is a Promise that is already settled (not pending anymore):

  1. return x is equivalent to return Promise.resolve(x), if the Promise was already resolved.
  2. return x is equivalent to return Promise.reject(x), if the Promise was already rejected.

C) When x is a Promise that is pending:

  1. return x will return a pending Promise, and it will be evaluated on the subsequent then.

Read more on this topic on the Promise.prototype.then() docs.

Could not find main class HelloWorld

put .; at classpath value in will start happens because it searches the class file in classpath which is mentioned in path variable.

How to get child process from parent process

For the case when the process tree of interest has more than 2 levels (e.g. Chromium spawns 4-level deep process tree), pgrep isn't of much use. As others have mentioned above, procfs files contain all the information about processes and one just needs to read them. I built a CLI tool called Procpath which does exactly this. It reads all /proc/N/stat files, represents the contents as a JSON tree and expose it to JSONPath queries.

To get all descendant process' comma-separated PIDs of a non-root process (for the root it's it's:

$ procpath query -d, "..children[?( == 24243)]"

Convert xlsx to csv in Linux with command line

Using the Gnumeric spreadsheet application which comes which a commandline utility called ssconvert is indeed super simple:

find . -name '*.xlsx' -exec ssconvert -T Gnumeric_stf:stf_csv {} \;

and you're done!

How to check list A contains any value from list B?

I use this to count:

int cnt = 0;

foreach (var lA in listA)
    if (listB.Contains(lA))

How to exclude *AutoConfiguration classes in Spring Boot JUnit tests?

I think that using the @EnableAutoConfiguration annotation on a test class won't work if you are using @SpringApplicationConfiguration to load your Application class. The thing is that you already have a @EnableAutoConfiguration annotation in the Application class that does not exclude the CrshAutoConfiguration.Spring uses that annotation instead of the one on your test class to do the auto configuration of your beans.

I think that your best bet is to use a different application context for your tests and exclude the CrshAutoConfiguration in that class.

I did some tests and it seems that @EnableAutoConfiguration on the test class is completely ignore if you are using the @SpringApplicationConfiguration annotation and the SpringJUnit4ClassRunner.

How to customize the background/border colors of a grouped table view cell?

One thing I ran into with the above CustomCellBackgroundView code from Mike Akers which might be useful to others:

cell.backgroundView doesn't get automatically redrawn when cells are reused, and changes to the backgroundView's position var don't affect reused cells. That means long tables will have incorrectly drawn cell.backgroundViews given their positions.

To fix this without having to create a new backgroundView every time a row is displayed, call [cell.backgroundView setNeedsDisplay] at the end of your -[UITableViewController tableView:cellForRowAtIndexPath:]. Or for a more reusable solution, override CustomCellBackgroundView's position setter to include a [self setNeedsDisplay].

How to git-cherry-pick only changes to certain files?

I usually use the -p flag with a git checkout from the other branch which I find easier and more granular than most other methods I have come across.

In principle:

git checkout <other_branch_name> <files/to/grab in/list/separated/by/spaces> -p


git checkout mybranch config/important.yml app/models/important.rb -p

You then get a dialog asking you which changes you want in "blobs" this pretty much works out to every chunk of continuous code change which you can then signal y (Yes) n (No) etc for each chunk of code.

The -p or patch option works for a variety of commands in git including git stash save -p which allows you to choose what you want to stash from your current work

I sometimes use this technique when I have done a lot of work and would like to separate it out and commit in more topic based commits using git add -p and choosing what I want for each commit :)

"Too many values to unpack" Exception

try unpacking in one variable,

python will handle it as a list,

then unpack from the list

def returnATupleWithThreeValues():
    return (1,2,3)
a = returnATupleWithThreeValues() # a is a list (1,2,3)
print a[0] # list[0] = 1
print a[1] # list[1] = 2
print a[2] # list[2] = 3

how to get the ipaddress of a virtual box running on local machine

Login to virtual machine use below command to check ip address. (anyone will work)

  1. ifconfig
  2. ip addr show

If you used NAT for your virtual machine settings(your machine ip will be, then you have to use port forwarding to connect to machine. IP address will be

If you used bridged networking/Host only networking, then you will have separate Ip address. Use that IP address to connect virtual machine

What is difference between INNER join and OUTER join

Inner join matches tables on keys, but outer join matches keys just for one side. For example when you use left outer join the query brings the whole left side table and matches the right side to the left table primary key and where there is not matched places null.

How to save a list to a file and read it as a list type?

If you want you can use numpy's save function to save the list as file. Say you have two lists


here's the function to save the list as file, remember you need to keep the extension .npy

def saveList(myList,filename):
    # the filename should mention the extension 'npy',myList)
    print("Saved successfully!")

and here's the function to load the file into a list

def loadList(filename):
    # the filename should mention the extension 'npy'
    return tempNumpyArray.tolist()

a working example

>>> saveList(sampleList1,'sampleList1.npy')
>>> Saved successfully!
>>> saveList(sampleList2,'sampleList2.npy')
>>> Saved successfully!

# loading the list now 
>>> loadedList1=loadList('sampleList1.npy')
>>> loadedList2=loadList('sampleList2.npy')

>>> loadedList1==sampleList1
>>> True

>>> print(loadedList1,sampleList1)

>>> ['z', 'x', 'a', 'b'] ['z', 'x', 'a', 'b']

Fastest way to remove first char in a String

I'd guess that Remove and Substring would tie for first place, since they both slurp up a fixed-size portion of the string, whereas TrimStart does a scan from the left with a test on each character and then has to perform exactly the same work as the other two methods. Seriously, though, this is splitting hairs.

How to auto generate migrations with Sequelize CLI from Sequelize models?

I created a small working "migration file generator". It creates files which are working perfectly fine using sequelize db:migrate - even with foreign keys!

You can find it here:

I tested it in an application with 12 different models covering:


  • Foreign key constraints (even reciprocal (user belongsTo team, team belongsTo user as owner))

  • Indexes with name, method and unique properties

How to set a border for an HTML div tag

You can use:

border-style: solid;
border-width: thin;
border-color: #FFFFFF;

You can change these as you see fit, though.

server error:405 - HTTP verb used to access this page is not allowed

In my case, IIS was fine but.. uh.. all the files in the folder except web.config had been deleted (a manual deployment half-done on a test site).

How to get all key in JSON object (javascript)

Try this

var s = {name: "raul", age: "22", gender: "Male"}
   var keys = [];
   for(var k in s) keys.push(k);

Here keys array will return your keys ["name", "age", "gender"]

Java format yyyy-MM-dd'T'HH:mm:ss.SSSz to yyyy-mm-dd HH:mm:ss

I was trying to format the date string received from a JSON response e.g. 2016-03-09T04:50:00-0800 to yyyy-MM-dd. So here's what I tried and it worked and helped me assign the formatted date string a calendar widget.

String DATE_FORMAT_I = "yyyy-MM-dd'T'HH:mm:ss";
String DATE_FORMAT_O = "yyyy-MM-dd";

SimpleDateFormat formatInput = new SimpleDateFormat(DATE_FORMAT_I);
SimpleDateFormat formatOutput = new SimpleDateFormat(DATE_FORMAT_O);

Date date = formatInput.parse(member.getString("date"));
String dateString = formatOutput.format(date);

This worked. Thanks.

How to diff a commit with its parent?

Use git show $COMMIT. It'll show you the log message for the commit, and the diff of that particular commit.

How to completely remove Python from a Windows machine?

You will also have to look in your system path. Python puts itself there and does not remove itself:

Your problems probably started because your python path is pointing to the wrong one.

How to find the files that are created in the last hour in unix

UNIX filesystems (generally) don't store creation times. Instead, there are only access time, (data) modification time, and (inode) change time.

That being said, find has -atime -mtime -ctime predicates:

$ man 1 find
-ctime  n
        The primary shall evaluate as true if the time of last change of
        file status information subtracted from the initialization time,
        divided by 86400 (with any remainder discarded), is n.

Thus find -ctime 0 finds everything for which the inode has changed (e.g. includes file creation, but also counts link count and permissions and filesize change) less than an hour ago.

How to create a generic array?

Problem is that while runtime generic type is erased so new E[10] would be equivalent to new Object[10].

This would be dangerous because it would be possible to put in array other data than of E type. That is why you need to explicitly say that type you want by either

How to check if a string array contains one string in JavaScript?

Create this function prototype:

Array.prototype.contains = function ( needle ) {
   for (i in this) {
      if (this[i] == needle) return true;
   return false;

and then you can use following code to search in array x

if (x.contains('searchedString')) {
    // do a
      // do b

Error in Python IOError: [Errno 2] No such file or directory: 'data.csv'

open looks in the current working directory, which in your case is ~, since you are calling your script from the ~ directory.

You can fix the problem by either

  • cding to the directory containing data.csv before executing the script, or

  • by using the full path to data.csv in your script, or

  • by calling os.chdir(...) to change the current working directory from within your script. Note that all subsequent commands that use the current working directory (e.g. open and os.listdir) may be affected by this.

Clearing UIWebview cache

I actually think it may retain cached information when you close out the UIWebView. I've tried removing a UIWebView from my UIViewController, releasing it, then creating a new one. The new one remembered exactly where I was at when I went back to an address without having to reload everything (it remembered my previous UIWebView was logged in).

So a couple of suggestions:

[[NSURLCache sharedURLCache] removeCachedResponseForRequest:NSURLRequest];

This would remove a cached response for a specific request. There is also a call that will remove all cached responses for all requests ran on the UIWebView:

[[NSURLCache sharedURLCache] removeAllCachedResponses];

After that, you can try deleting any associated cookies with the UIWebView:

for(NSHTTPCookie *cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]) {

    if([[cookie domain] isEqualToString:someNSStringUrlDomain]) {

        [[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];

Swift 3:

// Remove all cache 

// Delete any associated cookies     
if let cookies = HTTPCookieStorage.shared.cookies {
    for cookie in cookies {

How to include *.so library in Android Studio?

I have solved a similar problem using external native lib dependencies that are packaged inside of jar files. Sometimes these architecture dependend libraries are packaged alltogether inside one jar, sometimes they are split up into several jar files. so i wrote some buildscript to scan the jar dependencies for native libs and sort them into the correct android lib folders. Additionally this also provides a way to download dependencies that not found in maven repos which is currently usefull to get JNA working on android because not all native jars are published in public maven repos.

android {
    compileSdkVersion 23
    buildToolsVersion '24.0.0'

    lintOptions {
        abortOnError false

    defaultConfig {
        applicationId "myappid"
        minSdkVersion 17
        targetSdkVersion 23
        versionCode 1
        versionName "1.0.0"
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), ''

    sourceSets {
        main {
            jniLibs.srcDirs = ["src/main/jniLibs", "$buildDir/native-libs"]

def urlFile = { url, name ->
    File file = new File("$buildDir/download/${name}.jar")
    if (!file.exists()) {
        new URL(url).withInputStream { downloadStream ->
            file.withOutputStream { fileOut ->
                fileOut << downloadStream
dependencies {
    testCompile 'junit:junit:4.12'
    compile ''
    compile ''
    compile ''
    compile urlFile('', 'jna-android-arm')
    compile urlFile('', 'jna-android-armv7')
    compile urlFile('', 'jna-android-aarch64')
    compile urlFile('', 'jna-android-x86')
    compile urlFile('', 'jna-android-x86_64')
    compile urlFile('', 'jna-android-mips')
    compile urlFile('', 'jna-android-mips64')
def safeCopy = { src, dst ->
    File fdst = new File(dst)
    fdst.bytes = new File(src).bytes


def archFromName = { name ->
    switch (name) {
        case ~/.*android-(x86-64|x86_64|amd64).*/:
            return "x86_64"
        case ~/.*android-(i386|i686|x86).*/:
            return "x86"
        case ~/.*android-(arm64|aarch64).*/:
            return "arm64-v8a"
        case ~/.*android-(armhf|armv7|arm-v7|armeabi-v7).*/:
            return "armeabi-v7a"
        case ~/.*android-(arm).*/:
            return "armeabi"
        case ~/.*android-(mips).*/:
            return "mips"
        case ~/.*android-(mips64).*/:
            return "mips64"
            return null

task extractNatives << {
    project.configurations.compile.each { dep ->
        println "Scanning ${} for native libs"
        if (!".jar"))
        zipTree(dep).visit { zDetail ->
            if (!".so"))
            print "\tFound ${}"
            String arch = archFromName(zDetail.toString())
            if(arch != null){
                println " -> $arch"
            } else {
                println " -> No valid arch"


How do I declare class-level properties in Objective-C?

[Try this solution it's simple] You can create a static variable in a Swift class then call it from any Objective-C class.

What is a NoReverseMatch error, and how do I fix it?

It may be that it's not loading the template you expect. I added a new class that inherited from UpdateView - I thought it would automatically pick the template from what I named my class, but it actually loaded it based on the model property on the class, which resulted in another (wrong) template being loaded. Once I explicitly set template_name for the new class, it worked fine.

Correct format specifier to print pointer or address?

You can use %x or %X or %p; all of them are correct.

  • If you use %x, the address is given as lowercase, for example: a3bfbc4
  • If you use %X, the address is given as uppercase, for example: A3BFBC4

Both of these are correct.

If you use %x or %X it's considering six positions for the address, and if you use %p it's considering eight positions for the address. For example:

Iterating Through a Dictionary in Swift

If you want to iterate over all the values:

dict.values.forEach { value in
    // print(value)

How to substring in jquery

You don't need jquery in order to do that.

var placeHolder="name";
var res=name.substr(name.indexOf(placeHolder) + placeHolder.length);

How to emulate a BEFORE INSERT trigger in T-SQL / SQL Server for super/subtype (Inheritance) entities?

While Andriy's proposal will work well for INSERTs of a small number of records, full table scans will be done on the final join as both 'enumerated' and '@new_super' are not indexed, resulting in poor performance for large inserts.

This can be resolved by specifying a primary key on the @new_super table, as follows:

DECLARE @new_super TABLE (
  super_id   int

This will result in the SQL optimizer scanning through the 'enumerated' table but doing an indexed join on @new_super to get the new key.

Error message "unreported exception; must be caught or declared to be thrown"

Exceptions bubble up the stack. If a caller calls a method that throws a checked exception, like IOException, it must also either catch the exception, or itself throw it.

In the case of the first block:

    setSize(300, 300);

        addWindowListener(new WindowAdapter()
            public void windowClosing(WindowEvent we)

You would have to include a try catch block:

    try {
    catch (IOException e) {
        // Do something here
    setSize(300, 300);

        addWindowListener(new WindowAdapter()
            public void windowClosing(WindowEvent we)

In the case of the second:

public void actionPerformed(ActionEvent ae)
    if (ae.getSource() == submit)

You cannot throw IOException from this method as its signature is determined by the interface, so you must catch the exception within:

public void actionPerformed(ActionEvent ae)
        try {
        catch (IOException e) {
            // Do something here

Remember, the showFile() method is throwing the exception; that's what the "throws" keyword indicates that the method may throw that exception. If the showFile() method is throwing, then whatever code calls that method must catch, or themselves throw the exception explicitly by including the same throws IOException addition to the method signature, if it's permitted.

If the method is overriding a method signature defined in an interface or superclass that does not also declare that the method may throw that exception, you cannot declare it to throw an exception.

Found shared references to a collection org.hibernate.HibernateException

In my case, I was copying and pasting code from my other classes, so I did not notice that the getter code was bad written:

@OneToMany(fetch = FetchType.LAZY, mappedBy = "credito")
public Set getConceptoses() {
    return this.letrases;

public void setConceptoses(Set conceptoses) {
    this.conceptoses = conceptoses;

All references conceptoses but if you look at the get says letrases

Add 2 hours to current time in MySQL?

The DATE_ADD() function will do the trick. (You can also use the ADDTIME() function if you're running at least v4.1.1.)

For your query, this would be:

FROM courses 
WHERE DATE_ADD(now(), INTERVAL 2 HOUR) > start_time


FROM courses 
WHERE ADDTIME(now(), '02:00:00') > start_time

Setting an HTML text input box's "default" value. Revert the value when clicking ESC

You might looking for the placeholder attribute which will display a grey text in the input field while empty.

From Mozilla Developer Network:

A hint to the user of what can be entered in the control . The placeholder text must not contain carriage returns or line-feeds. This attribute applies when the value of the type attribute is text, search, tel, url or email; otherwise it is ignored.

However as it's a fairly 'new' tag (from the HTML5 specification afaik) you might want to to browser testing to make sure your target audience is fine with this solution.
(If not tell tell them to upgrade browser 'cause this tag works like a charm ;o) )

And finally a mini-fiddle to see it directly in action:

Edit: Here is a plain jQuery solution which will also clear the input field if an escape keystroke is detected:

Load view from an external xib file in storyboard

My full example is here, but I will provide a summary below.


Add a .swift and .xib file each with the same name to your project. The .xib file contains your custom view layout (using auto layout constraints preferably).

Make the swift file the xib file's owner.

enter image description here Code

Add the following code to the .swift file and hook up the outlets and actions from the .xib file.

import UIKit
class ResuableCustomView: UIView {

    let nibName = "ReusableCustomView"
    var contentView: UIView?

    @IBOutlet weak var label: UILabel!
    @IBAction func buttonTap(_ sender: UIButton) {
        label.text = "Hi"

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        guard let view = loadViewFromNib() else { return }
        view.frame = self.bounds
        contentView = view

    func loadViewFromNib() -> UIView? {
        let bundle = Bundle(for: type(of: self))
        let nib = UINib(nibName: nibName, bundle: bundle)
        return nib.instantiate(withOwner: self, options: nil).first as? UIView

Use it

Use your custom view anywhere in your storyboard. Just add a UIView and set the class name to your custom class name.

enter image description here

For a while Christopher Swasey's approach was the best approach I had found. I asked a couple of the senior devs on my team about it and one of them had the perfect solution! It satisfies every one of the concerns that Christopher Swasey so eloquently addressed and it doesn't require boilerplate subclass code(my main concern with his approach). There is one gotcha, but other than that it is fairly intuitive and easy to implement.

  1. Create a custom UIView class in a .swift file to control your xib. i.e. MyCustomClass.swift
  2. Create a .xib file and style it as you want. i.e. MyCustomClass.xib
  3. Set the File's Owner of the .xib file to be your custom class (MyCustomClass)
  4. GOTCHA: leave the class value (under the identity Inspector) for your custom view in the .xib file blank. So your custom view will have no specified class, but it will have a specified File's Owner.
  5. Hook up your outlets as you normally would using the Assistant Editor.
    • NOTE: If you look at the Connections Inspector you will notice that your Referencing Outlets do not reference your custom class (i.e. MyCustomClass), but rather reference File's Owner. Since File's Owner is specified to be your custom class, the outlets will hook up and work propery.
  6. Make sure your custom class has @IBDesignable before the class statement.
  7. Make your custom class conform to the NibLoadable protocol referenced below.
    • NOTE: If your custom class .swift file name is different from your .xib file name, then set the nibName property to be the name of your .xib file.
  8. Implement required init?(coder aDecoder: NSCoder) and override init(frame: CGRect) to call setupFromNib() like the example below.
  9. Add a UIView to your desired storyboard and set the class to be your custom class name (i.e. MyCustomClass).
  10. Watch IBDesignable in action as it draws your .xib in the storyboard with all of it's awe and wonder.

Here is the protocol you will want to reference:

public protocol NibLoadable {
    static var nibName: String { get }

public extension NibLoadable where Self: UIView {

    public static var nibName: String {
        return String(describing: Self.self) // defaults to the name of the class implementing this protocol.

    public static var nib: UINib {
        let bundle = Bundle(for: Self.self)
        return UINib(nibName: Self.nibName, bundle: bundle)

    func setupFromNib() {
        guard let view = Self.nib.instantiate(withOwner: self, options: nil).first as? UIView else { fatalError("Error loading \(self) from nib") }
        view.translatesAutoresizingMaskIntoConstraints = false
        view.leadingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.leadingAnchor, constant: 0).isActive = true
        view.topAnchor.constraint(equalTo: self.safeAreaLayoutGuide.topAnchor, constant: 0).isActive = true
        view.trailingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.trailingAnchor, constant: 0).isActive = true
        view.bottomAnchor.constraint(equalTo: self.safeAreaLayoutGuide.bottomAnchor, constant: 0).isActive = true

And here is an example of MyCustomClass that implements the protocol (with the .xib file being named MyCustomClass.xib):

class MyCustomClass: UIView, NibLoadable {

    @IBOutlet weak var myLabel: UILabel!

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

    override init(frame: CGRect) {
        super.init(frame: frame)


NOTE: If you miss the Gotcha and set the class value inside your .xib file to be your custom class, then it will not draw in the storyboard and you will get a EXC_BAD_ACCESS error when you run the app because it gets stuck in an infinite loop of trying to initialize the class from the nib using the init?(coder aDecoder: NSCoder) method which then calls Self.nib.instantiate and calls the init again.

Factory Pattern. When to use factory methods?

if you want to create a different object in terms of using. It is useful.

public class factoryMethodPattern {
      static String planName = "COMMERCIALPLAN";
      static int units = 3;
      public static void main(String args[]) {
          GetPlanFactory planFactory = new GetPlanFactory();
          Plan p = planFactory.getPlan(planName);
          System.out.print("Bill amount for " + planName + " of  " + units
                        + " units is: ");

abstract class Plan {
      protected double rate;

      abstract void getRate();

      public void calculateBill(int units) {
            System.out.println(units * rate);

class DomesticPlan extends Plan {
      // @override
      public void getRate() {
            rate = 3.50;

class CommercialPlan extends Plan {
      // @override
      public void getRate() {
            rate = 7.50;

class InstitutionalPlan extends Plan {
      // @override
      public void getRate() {
            rate = 5.50;

class GetPlanFactory {

      // use getPlan method to get object of type Plan
      public Plan getPlan(String planType) {
            if (planType == null) {
                  return null;
            if (planType.equalsIgnoreCase("DOMESTICPLAN")) {
                  return new DomesticPlan();
            } else if (planType.equalsIgnoreCase("COMMERCIALPLAN")) {
                  return new CommercialPlan();
            } else if (planType.equalsIgnoreCase("INSTITUTIONALPLAN")) {
                  return new InstitutionalPlan();
            return null;

Soft hyphen in HTML (<wbr> vs. &shy;)

Unfortunately, &shy's support is so inconsistent between browsers that it can't really be used.

QuirksMode is right -- there's no good way to use soft hyphens in HTML right now. See what you can do to go without them.

2013 edit: According to QuirksMode, &shy; now works/is supported on all major browsers.

How do detect Android Tablets in general. Useragent?

While we can't say if some tablets omit "mobile", many including the Samsung Galaxy Tab do have mobile in their user-agent, making it impossible to detect between an android tablet and android phone without resorting to checking model specifics. This IMHO is a waste of time unless you plan on updating and expanding your device list on a monthly basis.

Unfortunately the best solution here is to complain to Google about this and get them to fix Chrome for Android so it adds some text to identify between a mobile device and a tablet. Hell even a single letter M OR T in a specific place in the string would be enough, but I guess that makes too much sense.

Create list of object from another using Java 8 Streams

I prefer to solve this in the classic way, creating a new array of my desired data type:

List<MyNewType> newArray = new ArrayList<>();
myOldArray.forEach(info -> newArray.add(objectMapper.convertValue(info, MyNewType.class)));

Python threading.timer - repeat function every 'n' seconds

The best way is to start the timer thread once. Inside your timer thread you'd code the following

class MyThread(Thread):
    def __init__(self, event):
        self.stopped = event

    def run(self):
        while not self.stopped.wait(0.5):
            print("my thread")
            # call a function

In the code that started the timer, you can then set the stopped event to stop the timer.

stopFlag = Event()
thread = MyThread(stopFlag)
# this will stop the timer

HTML5 required attribute seems not working

Actually speaking, when I tried this, it worked only when I set the action and method value for the form. Funny how it works though!

Create an Array of Arraylists

You can create like this ArrayList<Individual>[] group = (ArrayList<Individual>[])new ArrayList[4];

You have to create array of non generic type and then cast it into generic one.

Reload a DIV without reloading the whole page

Your html is not updated every 15 seconds. The cause could be browser caching. Add Math.random() to avoid browser caching, and it's better to wait until the DOM is fully loaded as pointed out by @shadow. But I think the main cause is the caching

<script type="text/javascript" src="" />
<script type="text/javascript">
    var auto_refresh = setInterval(
    function ()
       $('.View').load('Small.php?' + Math.random()).fadeIn("slow");
    }, 15000); // refresh every 15000 milliseconds

How to initialize an array in angular2 and typescript

I don't fully understand what you really mean by initializing an array?

Here's an example:

class Environment {

    // you can declare private, public and protected variables in constructor signature 
        private id: string,
        private name: string
    ) { 
        alert( );

let environments = new Environment('a','b');

// creating and initializing array of Environment objects
let envArr: Array<Environment> = [ 
        new Environment('c','v'), 
        new Environment('c','v'), 
        new Environment('g','g'), 
        new Environment('3','e') 

Try it here :

A child container failed during start java.util.concurrent.ExecutionException

Your webapp has servletcontainer specific libraries like servlet-api.jar file in its /WEB-INF/lib. This is not right.

Remove them all.

The /WEB-INF/lib should contain only the libraries specific to the webapp, not to the servletcontainer. The servletcontainer (like Tomcat) is the one who should already provide the servletcontainer specific libraries.

If you supply libraries from an arbitrary servletcontainer of a different make/version, you'll run into this kind of problems because your webapp wouldn't be able to run on a servletcontainer of a different make/version than where those libraries are originated from.

How to solve: In Eclipse Right click on the project in eclipse Properties -> Java Build Path -> Add library -> Server Runtime Library -> Apache Tomcat

Im Maven Project:-

add follwing line in pom.xml file


How to allow access outside localhost

If you facing same problem inside Docker, then you can use below CMD in Dockerfile.

CMD ["ng", "serve", "--host", ""]

Or complete Dockerfile

FROM node:alpine
RUN npm install -g @angular/cli
COPY . .
CMD ["ng", "serve", "--host", ""]

How to get input textfield values when enter key is pressed in react js?

Adding onKeyPress will work onChange in Text Field.

  onKeyPress={(ev) => {
    console.log(`Pressed keyCode ${ev.key}`);
    if (ev.key === 'Enter') {
      // Do code here

Link to reload current page

There is no global way of doing this unfortunately with only HTML. You can try doing <a href="">test</a> however it only works in some browsers.

fatal error LNK1104: cannot open file 'kernel32.lib'

Change the platform toolset to: "Windows7.1SDK" under project properties->configuration properties->general

Show ImageView programmatically

How to ignore the certificate check when ssl

Since there is only one global ServicePointManager, setting ServicePointManager.ServerCertificateValidationCallback will yield the result that all subsequent requests will inherit this policy. Since it is a global "setting" it would be prefered to set it in the Application_Start method in Global.asax.

Setting the callback overrides the default behaviour and you can yourself create a custom validation routine.

Simplest way to have a configuration file in a Windows Forms C# application

From a quick read of the previous answers, they look correct, but it doesn't look like anyone mentioned the new configuration facilities in Visual Studio 2008. It still uses app.config (copied at compile time to YourAppName.exe.config), but there is a UI widget to set properties and specify their types. Double-click Settings.settings in your project's "Properties" folder.

The best part is that accessing this property from code is typesafe - the compiler will catch obvious mistakes like mistyping the property name. For example, a property called MyConnectionString in app.config would be accessed like:

string s = Properties.Settings.Default.MyConnectionString;

JPA OneToMany and ManyToOne throw: Repeated column in mapping for entity column (should be mapped with insert="false" update="false")

You should never use the unidirectional @OneToMany annotation because:

  1. It generates inefficient SQL statements
  2. It creates an extra table which increases the memory footprint of your DB indexes

Now, in your first example, both sides are owning the association, and this is bad.

While the @JoinColumn would let the @OneToMany side in charge of the association, it's definitely not the best choice. Therefore, always use the mappedBy attribute on the @OneToMany side.

public class User{
    @OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="user")
    public List<APost> aPosts;

    @OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="user")
    public List<BPost> bPosts;

public class BPost extends Post {

    public User user;

public class APost extends Post {

     public User user;

Fatal error: Maximum execution time of 300 seconds exceeded

In my case, when I faced that error in Phpmyadmin, I tried MySQL-Front and import my DB successfully.

Note: You can still use the provided solutions under this question to solve your problem in Phpmyadmin.

How to find the path of the local git repository when I am possibly in a subdirectory

git rev-parse --show-toplevel

could be enough if executed within a git repo.
From git rev-parse man page:


Show the absolute path of the top-level directory.

For older versions (before 1.7.x), the other options are listed in "Is there a way to get the git root directory in one command?":

git rev-parse --git-dir

That would give the path of the .git directory.

The OP mentions:

git rev-parse --show-prefix

which returns the local path under the git repo root. (empty if you are at the git repo root)

Note: for simply checking if one is in a git repo, I find the following command quite expressive:

git rev-parse --is-inside-work-tree

And yes, if you need to check if you are in a .git git-dir folder:

git rev-parse --is-inside-git-dir

CentOS 64 bit bad ELF interpreter

In general, when you get an error like this, just do

yum provides

then you'll see something like:

glibc-2.20-5.fc21.i686 : The GNU libc libraries
Repo        : fedora
Matched from:
Provides    :

and then you just run the following like BRPocock wrote (in case you were wondering what the logic was...):

yum install glibc.i686

Find OpenCV Version Installed on Ubuntu

The other methods here didn't work for me, so here's what does work in Ubuntu 12.04 'precise'.

On Ubuntu and other Debian-derived platforms, dpkg is the typical way to get software package versions. For more recent versions than the one that @Tio refers to, use

 dpkg -l | grep libopencv

If you have the development packages installed, like libopencv-core-dev, you'll probably have .pc files and can use pkg-config:

 pkg-config --modversion opencv

Python SQLite: database is locked

I found this worked for my needs. (thread locking) YMMV

conn = sqlite3.connect(database, timeout=10)

sqlite3.connect(database[, timeout, detect_types, isolation_level, check_same_thread, factory, cached_statements, uri])

When a database is accessed by multiple connections, and one of the processes modifies the database, the SQLite database is locked until that transaction is committed. The timeout parameter specifies how long the connection should wait for the lock to go away until raising an exception. The default for the timeout parameter is 5.0 (five seconds).

How to handle onchange event on input type=file in jQuery?

It should work fine, are you wrapping the code in a $(document).ready() call? If not use that or use live i.e.

$('#fileupload1').live('change', function(){ 

Here is a jsFiddle of this working against jQuery 1.4.4

How to get First and Last record from a sql query?

    MIN(Column), MAX(Column), UserId 
    UserId DESC




    TableName AS Tablename1

Changing the Status Bar Color for specific ViewControllers using Swift in iOS8

Swift 4 For specific ViewController without navigationViewController embedded just add this to your ViewController file.

override var preferredStatusBarStyle : UIStatusBarStyle {
    return .lightContent

Make a directory and copy a file

Use the FileSystemObject object, namely, its CreateFolder and CopyFile methods. Basically, this is what your script will look like:

Dim oFSO
Set oFSO = CreateObject("Scripting.FileSystemObject")

' Create a new folder
oFSO.CreateFolder "C:\MyFolder"

' Copy a file into the new folder
' Note that the destination folder path must end with a path separator (\)
oFSO.CopyFile "\\server\folder\file.ext", "C:\MyFolder\"

You may also want to add additional logic, like checking whether the folder you want to create already exists (because CreateFolder raises an error in this case) or specifying whether or not to overwrite the file being copied. So, you can end up with this:

Const strFolder = "C:\MyFolder\", strFile = "\\server\folder\file.ext"
Const Overwrite = True
Dim oFSO

Set oFSO = CreateObject("Scripting.FileSystemObject")

If Not oFSO.FolderExists(strFolder) Then
  oFSO.CreateFolder strFolder
End If

oFSO.CopyFile strFile, strFolder, Overwrite

Sequence contains no elements?

In addition to everything else that has been said, you can call DefaultIfEmpty() before you call Single(). This will ensure that your sequence contains something and thereby averts the InvalidOperationException "Sequence contains no elements". For example:

BlogPost post = (from p in dc.BlogPosts
                 where p.BlogPostID == ID
                 select p).DefaultIfEmpty().Single();

How to get the jQuery $.ajax error response text?

This is what worked for me

    function showErrorMessage(xhr, status, error) {
        if (xhr.responseText != "") {

            var jsonResponseText = $.parseJSON(xhr.responseText);
            var jsonResponseStatus = '';
            var message = '';
            $.each(jsonResponseText, function(name, val) {
                if (name == "ResponseStatus") {
                    jsonResponseStatus = $.parseJSON(JSON.stringify(val));
                     $.each(jsonResponseStatus, function(name2, val2) {
                         if (name2 == "Message") {
                             message = val2;


How can one print a size_t variable portably using the printf family?

For C89, use %lu and cast the value to unsigned long:

size_t foo;
printf("foo = %lu\n", (unsigned long) foo);

For C99 and later, use %zu:

size_t foo;
printf("foo = %zu\n", foo);

How to align footer (div) to the bottom of the page?

I am a newbie and these methods are not working for me. However, I tried a margin-top property in css and simply added the value of content pixels +5.

Example: my content layout had a height of 1000px so I put a margin-top value of 1005px in the footer css which gave me a 5px border and a footer that sits delightfully at the bottom of my site.

Probably an amateur way of doing it, but EFFECTIVE!!!

Convert HashBytes to VarChar

With personal experience of using the following code within a Stored Procedure which Hashed a SP Variable I can confirm, although undocumented, this combination works 100% as per my example:

@var=SUBSTRING(master.dbo.fn_varbintohexstr(HashBytes('SHA2_512', @SPvar)), 3, 128)

How to open Atom editor from command line in OS X?

Upgrading Atom appears to break command line functionality on the occasion. Looks like in my case it created two versions of the application instead of overwriting them. Occurs because the new file structure doesn't match file paths created by "Atom -> Install Shell Commands". In order fix the issue you'll need to do the following.

  1. Move "Atom X" from Documents into Applications (why it ended up in here, I have no idea)
  2. Rename "Atom X" to "Atom"
  3. Might need to restart your terminal and Atom

After that everything should work just like it did before. Hopefully this saves someone 30 minutes of poking around.

Detecting superfluous #includes in C/C++?

Here is a simple brute force way of identifying superfluous header includes. It's not perfect but eliminates the "obvious" unnecessary includes. Getting rid of these goes a long way in cleaning up the code.

The scripts can be accessed directly on GitHub.

Python socket connection timeout

You just need to use the socket settimeout() method before attempting the connect(), please note that after connecting you must settimeout(None) to set the socket into blocking mode, such is required for the makefile . Here is the code I am using:

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
fileobj = sock.makefile('rb', 0)

How to connect TFS in Visual Studio code

I know I'm a little late to the party, but I did want to throw some interjections. (I would have commented but not enough reputation points yet, so, here's a full answer).

This requires the latest version of VS Code, Azure Repo Extention, and Git to be installed.

Anyone looking to use the new VS Code (or using the preview like myself), when you go to the Settings (Still File -> Preferences -> Settings or CTRL+, ) you'll be looking under User Settings -> Extensions -> Azure Repos.


Then under Tfvc: Location you can paste the location of the executable.


For 2017 it'll be

C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\TF.exe

Or for 2019 (Preview)

C:\Program Files (x86)\Microsoft Visual Studio\2019\Preview\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\TF.exe

After adding the location, I closed my VS Code (not sure if this was needed) and went my git repo to copy the git URL.


After that, went back into VS Code went to the Command Palette (View -> Command Palette or CTRL+Shift+P) typed Git: Clone pasted my repo:


Selected the location for the repo to be stored. Next was an error that popped up. I proceeded to follow this video which walked me through clicking on the Team button with the exclamation mark on the bottom of your VS Code Screen


Then chose the new method of authentication


Copy by using CTRL+C and then press enter. Your browser will launch a page where you'll enter the code you copied (CTRL+V).


Click Continue


Log in with your Microsoft Credentials and you should see a change on the bottom bar of VS Code.



How do you clone a Git repository into a specific folder?

Although all of the answers above are good, I would like to propose a new method instead of using the symbolic link method in public html directory as proposed BEST in the accepted answer. You need to have access to your server virtual host configurations.

It is about configuring virtual host of your web server directly pointing to the repository directory. In Apache you can do it like:

DocumentRoot /var/www/html/website/your-git-repo

Here is an example of a virtual host file:

<VirtualHost *:443>

    DocumentRoot /path/to/your-git-repo

Empty responseText from XMLHttpRequest

Had a similar problem to yours. What we had to do is use the document.domain solution found here:

Ways to circumvent the same-origin policy

We also needed to change thins on the web service side. Used the "Access-Control-Allow-Origin" header found here:

CodeIgniter: 404 Page Not Found on Live Server

I was able to fix similar errors by changeing


on the application/config/config.php line 26.