Programs & Examples On #Phoenix

Bootstrap 4 responsive tables won't take up 100% width

The solution compliant with the v4 of the framework is to set the proper breakpoint. Rather than using .table-responsive, you should be able to use .table-responsive-sm (to be just responsive on small devices)

You can use any of the available endpoints: table-responsive{-sm|-md|-lg|-xl}

Parse json string to find and element (key / value)

You want to convert it to an object first and then access normally making sure to cast it.

JObject obj = JObject.Parse(json);
string name = (string) obj["Name"];

ImportError: No module named dateutil.parser

If you're using a virtualenv, make sure that you are running pip from within the virtualenv.

$ which pip
$ find . -name pip -print
$ ./flask/bin/pip install python-dateutil

Unable to send email using Gmail SMTP server through PHPMailer, getting error: SMTP AUTH is required for message submission on port 587. How to fix?

$mail = new PHPMailer(); // create a new object
$mail->IsSMTP(); // enable SMTP
$mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true; // authentication enabled
$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for Gmail
$mail->Host = "";
$mail->Port = 465; // or 587
$mail->Username = "[email protected]";
$mail->Password = "password";
$mail->SetFrom("[email protected]");
$mail->Subject = "Test";
$mail->Body = "hello";
$mail->AddAddress("[email protected]");

 if(!$mail->Send()) {
    echo "Mailer Error: " . $mail->ErrorInfo;
 } else {
    echo "Message has been sent";

This code above has been tested and worked for me.

It could be that you needed $mail->SMTPSecure = 'ssl';

Also make sure you don't have two step verification switched on for that account as that can cause problems also.


You could try changing $mail->SMTP to:

$mail->SMTPSecure = 'tls';

It's worth noting that some SMTP servers block connections. Some SMTP servers don't support SSL (or TLS) connections.

Change the class from factor to numeric of many columns in a data frame

Here are some dplyr options:

# by column type:
df %>% 
  mutate_if(is.factor, ~as.numeric(as.character(.)))

# by specific columns:
df %>% 
  mutate_at(vars(x, y, z), ~as.numeric(as.character(.))) 

# all columns:
df %>% 

Generating a drop down list of timezones with PHP

I would do it with the following code which is similar to the accepted answer (I'm aware the code could be refactored :) ):

    $list = DateTimeZone::listAbbreviations();
    $idents = DateTimeZone::listIdentifiers();

    $data = $offset = $added = array();
    foreach ($list as $abbr => $info) {
        foreach ($info as $zone) {
            if ( ! empty($zone['timezone_id'])
                ! in_array($zone['timezone_id'], $added)
                  in_array($zone['timezone_id'], $idents)) {
                $z = new DateTimeZone($zone['timezone_id']);
                $c = new DateTime(null, $z);
                $zone['time'] = $c->format('H:i a');
                $offset[] = $zone['offset'] = $z->getOffset($c);
                $data[] = $zone;
                $added[] = $zone['timezone_id'];

    array_multisort($offset, SORT_ASC, $data);
    $options = array();
    foreach ($data as $key => $row) {
        $options[$row['timezone_id']] = $row['time'] . ' - '
                                        . formatOffset($row['offset']) 
                                        . ' ' . $row['timezone_id'];

    // now you can use $options;

function formatOffset($offset) {
        $hours = $offset / 3600;
        $remainder = $offset % 3600;
        $sign = $hours > 0 ? '+' : '-';
        $hour = (int) abs($hours);
        $minutes = (int) abs($remainder / 60);

        if ($hour == 0 AND $minutes == 0) {
            $sign = ' ';
        return 'GMT' . $sign . str_pad($hour, 2, '0', STR_PAD_LEFT) 
                .':'. str_pad($minutes,2, '0');


It produces something like:

<option value="America/Boise" label="02:10 am - GMT-06:00 America/Boise">02:10 am - GMT-06:00 America/Boise</option>

<option value="America/Denver" label="02:10 am - GMT-06:00 America/Denver">02:10 am - GMT-06:00 America/Denver</option>
<option value="America/Edmonton" label="02:10 am - GMT-06:00 America/Edmonton">02:10 am - GMT-06:00 America/Edmonton</option>
<option value="America/Inuvik" label="02:10 am - GMT-06:00 America/Inuvik">02:10 am - GMT-06:00 America/Inuvik</option>
<option value="America/Shiprock" label="02:10 am - GMT-06:00 America/Shiprock">02:10 am - GMT-06:00 America/Shiprock</option>

<option value="America/Belize" label="02:10 am - GMT-05:00 America/Belize">02:10 am - GMT-05:00 America/Belize</option>

Hope that helps a bit and/or inspire you to come with something better.

Java8: sum values from specific field of the objects in a list


int sum = -> o.field > 10).mapToInt(o -> o.field).sum();

Best way to run scheduled tasks

You can easily create a Windows Service that runs code on interval using the 'ThreadPool.RegisterWaitForSingleObject' method. It is really slick and quite easy to get set up. This method is a more streamlined approach then to use any of the Timers in the Framework.

Have a look at the link below for more information:

Running a Periodic Process in .NET using a Windows Service:

How do I check OS with a preprocessor directive?

#ifdef _WIN32
// do something for windows like include <windows.h>
#elif defined __unix__
// do something for unix like include <unistd.h>
#elif defined __APPLE__
// do something for mac

SyntaxError: Unexpected token function - Async Await Nodejs

Node.JS does not fully support ES6 currently, so you can either use asyncawait module or transpile it using Bable.


npm install --save asyncawait


var async = require('asyncawait/async');
var await = require('asyncawait/await');

(async (function testingAsyncAwait() {
    await (console.log("Print me!"));

python .replace() regex

You can use the re module for regexes, but regexes are probably overkill for what you want. I might try something like

z.write(article[:article.index("</html>") + 7]

This is much cleaner, and should be much faster than a regex based solution.

How to change language of app when user selects language?

Kotlin solution using context extension

fun Context.applyNewLocale(locale: Locale): Context {
    val config = this.resources.configuration
    val sysLocale = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    } else {
    if (sysLocale.language != locale.language) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        } else {
            config.locale = locale
        resources.updateConfiguration(config, resources.displayMetrics)
    return this


override fun attachBaseContext(newBase: Context?) {
    super.attachBaseContext(newBase?.applyNewLocale(Locale("es", "MX")))

how to activate a textbox if I select an other option in drop down box

Coded an example at


<select name="color" onchange='checkvalue(this.value)'> 
    <option>pick a color</option>  
    <option value="red">RED</option>
    <option value="blue">BLUE</option>
    <option value="others">others</option>
<input type="text" name="color" id="color" style='display:none'/>


function checkvalue(val)

Concatenate two NumPy arrays vertically

a = np.array([1,2,3])
b = np.array([4,5,6])

works just as well as

np.array([[1,2,3], [4,5,6]])

Regardless of whether it is a list of lists or a list of 1d arrays, np.array tries to create a 2d array.

But it's also a good idea to understand how np.concatenate and its family of stack functions work. In this context concatenate needs a list of 2d arrays (or any anything that np.array will turn into a 2d array) as inputs.

np.vstack first loops though the inputs making sure they are at least 2d, then does concatenate. Functionally it's the same as expanding the dimensions of the arrays yourself.

np.stack is a new function that joins the arrays on a new dimension. Default behaves just like np.array.

Look at the code for these functions. If written in Python you can learn quite a bit. For vstack:

return _nx.concatenate([atleast_2d(_m) for _m in tup], 0)

PHP code to remove everything but numbers

You would need to enclose the pattern in a delimiter - typically a slash (/) is used. Try this:

echo preg_replace("/[^0-9]/","",'604-619-5135');

Passing arguments to require (when loading module)

Yes. In your login module, just export a single function that takes the db as its argument. For example:

module.exports = function(db) {

Laravel 5.4 redirection to custom url after login

That's what i am currrently working, what a coincidence.

You also need to add the following lines into your LoginController

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;

use Illuminate\Foundation\Auth\AuthenticatesUsers;

use Illuminate\Http\Request;

class LoginController extends Controller
| Login Controller
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.

use AuthenticatesUsers;

protected function authenticated(Request $request, $user)
if ( $user->isAdmin() ) {// do your magic here
    return redirect()->route('dashboard');

 return redirect('/home');
 * Where to redirect users after login.
 * @var string
//protected $redirectTo = '/admin';

 * Create a new controller instance.
 * @return void
public function __construct()
    $this->middleware('guest', ['except' => 'logout']);

Inline onclick JavaScript variable

<script>var myVar = 15;</script>
<input id="EditBanner" type="button" value="Edit Image" onclick="EditBanner(myVar);"/>

Get column from a two dimensional array

This function works to arrays and objects. obs: it works like array_column php function. It means that an optional third parameter can be passed to define what column will correspond to the indices of return.

function array_column(list, column, indice){
    var result;

    if(typeof indice != "undefined"){
        result = {};

        for(key in list)
            result[list[key][indice]] = list[key][column];
        result = [];

        for(key in list)
            result.push( list[key][column] );

    return result;

This is a conditional version:

function array_column_conditional(list, column, indice){
    var result;

    if(typeof indice != "undefined"){
        result = {};

        for(key in list)
            if(typeof list[key][column] !== 'undefined' && typeof list[key][indice] !== 'undefined')
                result[list[key][indice]] = list[key][column];
        result = [];

        for(key in list)
            if(typeof list[key][column] !== 'undefined')
                result.push( list[key][column] );

    return result;


var lista = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]

var obj_list = [
  {a: 1, b: 2, c: 3},
  {a: 4, b: 5, c: 6},
  {a: 8, c: 9}

var objeto = {
  d: {a: 1, b: 3},
  e: {a: 4, b: 5, c: 6},
  f: {a: 7, b: 8, c: 9}

var list_obj = {
  d: [1, 2, 3],
  e: [4, 5],
  f: [7, 8, 9]

console.log( "column list: ", array_column(lista, 1) );
console.log( "column obj_list: ", array_column(obj_list, 'b', 'c') );
console.log( "column objeto: ", array_column(objeto, 'c') );
console.log( "column list_obj: ", array_column(list_obj, 0, 0) );

console.log( "column list conditional: ", array_column_conditional(lista, 1) );
console.log( "column obj_list conditional: ", array_column_conditional(obj_list, 'b', 'c') );
console.log( "column objeto conditional: ", array_column_conditional(objeto, 'c') );
console.log( "column list_obj conditional: ", array_column_conditional(list_obj, 0, 0) );


column list:  Array [ 2, 5, 8 ]
column obj_list:  Object { 3: 2, 6: 5, 9: undefined }
column objeto:  Array [ undefined, 6, 9 ]
column list_obj:  Object { 1: 1, 4: 4, 7: 7 }

column list conditional:  Array [ 2, 5, 8 ]
column obj_list conditional:  Object { 3: 2, 6: 5 }
column objeto conditional:  Array [ 6, 9 ]
column list_obj conditional:  Object { 1: 1, 4: 4, 7: 7 }

Can a class member function template be virtual?

While an older question that has been answered by many I believe a succinct method, not so different from the others posted, is to use a minor macro to help ease the duplication of class declarations.

// abstract.h

// Simply define the types that each concrete class will use
#define IMPL_RENDER() \
    void render(int a, char *b) override { render_internal<char>(a, b); }   \
    void render(int a, short *b) override { render_internal<short>(a, b); } \
    // ...

class Renderable
    // Then, once for each on the abstract
    virtual void render(int a, char *a) = 0;
    virtual void render(int a, short *b) = 0;
    // ...

So now, to implement our subclass:

class Box : public Renderable
    IMPL_RENDER() // Builds the functions we want

    template<typename T>
    void render_internal(int a, T *b); // One spot for our logic

The benefit here is that, when adding a newly supported type, it can all be done from the abstract header and forego possibly rectifying it in multiple source/header files.

Setting a divs background image to fit its size?

Use background-size for that purpose:

background-size: 100% 100%;

More on:

Draw radius around a point in Google map

It seems that the most common method of achieving this is to draw a GPolygon with enough points to simulate a circle. The example you referenced uses this method. This page has a good example - look for the function drawCircle in the source code.

Heatmap in matplotlib with pcolor?

The python seaborn module is based on matplotlib, and produces a very nice heatmap.

Below is an implementation with seaborn, designed for the ipython/jupyter notebook.

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
# import the data directly into a pandas dataframe
nba = pd.read_csv("", index_col='Name  ')
# remove index title = ""
# normalize data columns
nba_norm = (nba - nba.mean()) / (nba.max() - nba.min())
# relabel columns
labels = ['Games', 'Minutes', 'Points', 'Field goals made', 'Field goal attempts', 'Field goal percentage', 'Free throws made', 
          'Free throws attempts', 'Free throws percentage','Three-pointers made', 'Three-point attempt', 'Three-point percentage', 
          'Offensive rebounds', 'Defensive rebounds', 'Total rebounds', 'Assists', 'Steals', 'Blocks', 'Turnover', 'Personal foul']
nba_norm.columns = labels
# set appropriate font and dpi
sns.set_style({"savefig.dpi": 100})
# plot it out
ax = sns.heatmap(nba_norm,, linewidths=.1)
# set the x-axis labels on the top
# rotate the x-axis labels
# get figure (usually obtained via "fig,ax=plt.subplots()" with matplotlib)
fig = ax.get_figure()
# specify dimensions and save
fig.set_size_inches(15, 20)

The output looks like this: seaborn nba heatmap I used the matplotlib Blues color map, but personally find the default colors quite beautiful. I used matplotlib to rotate the x-axis labels, as I couldn't find the seaborn syntax. As noted by grexor, it was necessary to specify the dimensions (fig.set_size_inches) by trial and error, which I found a bit frustrating.

As noted by Paul H, you can easily add the values to heat maps (annot=True), but in this case I didn't think it improved the figure. Several code snippets were taken from the excellent answer by joelotz.

Selecting data frame rows based on partial string match in a column

Another option would be to simply use grepl function:

df[grepl('er', df$name), ]
CO2[grepl('non', CO2$Treatment), ]

df <- data.frame(name = c('bob','robert','peter'),
                 id = c(1,2,3)

# name id
# 2 robert  2
# 3  peter  3

Angular 4: How to include Bootstrap?

If you are using Sass/Scss, then follow this,

Do npm install

npm install bootstrap --save

and add import statement to your sass/scss file,

@import '~bootstrap/dist/css/bootstrap.css'

How to check if a variable is both null and /or undefined in JavaScript

You can wrap it in your own function:

function isNullAndUndef(variable) {

    return (variable !== null && variable !== undefined);

"Invalid JSON primitive" in Ajax processing

these answers just had me bouncing back and forth between invalid parameter and missing parameter.

this worked for me , just wrap string variables in quotes...

data: { RecordId: RecordId,
            UserId: UId,
            UserProfileId: UserProfileId,
            ItemType: '"' +  ItemType + '"',
            FileName: '"' +  XmlName + '"'

How to create a WPF Window without a border that can be resized via a grip only?

Sample here:

<Style TargetType="Window" x:Key="DialogWindow">
        <Setter Property="AllowsTransparency" Value="True"/>
        <Setter Property="WindowStyle" Value="None"/>
        <Setter Property="ResizeMode" Value="CanResizeWithGrip"/>
        <Setter Property="Template">
                <ControlTemplate TargetType="{x:Type Window}">
                    <Border BorderBrush="Black" BorderThickness="3" CornerRadius="10" Height="{TemplateBinding Height}"
                            Width="{TemplateBinding Width}" Background="Gray">
                            <Grid DockPanel.Dock="Top">
                                    <ColumnDefinition Width="50"/>
                                <Label Height="35" Grid.ColumnSpan="2"
                                <Button Width="15" Height="15" Content="x" Grid.Column="1" x:Name="PART_CloseButton"/>
                            <Border HorizontalAlignment="Stretch" VerticalAlignment="Stretch" 
                                        Background="LightBlue" CornerRadius="0,0,10,10" 
                                        <ColumnDefinition Width="20"/>
                                        <RowDefinition Height="*"/>
                                        <RowDefinition Height="20"></RowDefinition>
                                    <ResizeGrip Width="10" Height="10" Grid.Column="1" VerticalAlignment="Bottom" Grid.Row="1"/>

Oracle SQL escape character (for a '&')

Set the define character to something other than &

create table blah (x varchar(20));
insert into blah (x) values ('blah&amp');
select * from blah;


How to add shortcut keys for java code in eclipse

This is one more option: go to Windows > Preference > Java > Editor > Content Assit. Look in "Auto Activation" zone, sure that "Enable auto activation" is checked and add more charactor (like "abcd....yz, default is ".") to auto show content assist menu as your typing.

Running Composer returns: "Could not open input file: composer.phar"

To googlers who installed composer via HomeBrew: make a symbolic link for /usr/local/bin/composer

ln -s /usr/local/bin/composer /usr/local/bin/composer.phar

Accessing Redux state in an action creator?

I know I'm late to the party here, but I came here for opinions on my own desire to use state in actions, and then formed my own, when I realized what I think is the correct behavior.

This is where a selector makes the most sense to me. Your component that issues this request should be told wether it's time to issue it through selection.

export const SOME_ACTION = 'SOME_ACTION';
export function someAction(items) {
  return (dispatch) => {

It might feel like leaking abstractions, but your component clearly needs to send a message and the message payload should contain pertinent state. Unfortunately your question doesn't have a concrete example because we could work through a 'better model' of selectors and actions that way.

How to solve : SQL Error: ORA-00604: error occurred at recursive SQL level 1

One possible explanation is a database trigger that fires for each DROP TABLE statement. To find the trigger, query the _TRIGGERS dictionary views:

select * from all_triggers
where trigger_type in ('AFTER EVENT', 'BEFORE EVENT')

disable any suspicious trigger with

   alter trigger <trigger_name> disable;

and try re-running your DROP TABLE statement

How do I convert a Python program to a runnable .exe Windows program?

I've used py2exe in the past and have been very happy with it. I didn't particularly enjoy using cx-freeze as much, though

How to change the font and font size of an HTML input tag?

<input type ="text" id="txtComputer">



Renaming Columns in an SQL SELECT Statement

You can alias the column names one by one, like so

SELECT col1 as `MyNameForCol1`, col2 as `MyNameForCol2` 
FROM `foobar`

Edit You can access INFORMATION_SCHEMA.COLUMNS directly to mangle a new alias like so. However, how you fit this into a query is beyond my MySql skills :(

select CONCAT('Foobar_', COLUMN_NAME)
where TABLE_NAME = 'Foobar'

How to print pthread_t

A lookup table (pthread_t : int) could become a memory leak in programs that start a lot of short-lived threads.

Creating a hash of the bytes of the pthread_t (whether it be structure or pointer or long integer or whatever) may be a usable solution that doesn't require lookup tables. As with any hash there is a risk of collisions, but you could tune the length of the hash to suit your requirements.

How to remove "rows" with a NA value?

dat <- data.frame(x1 = c(1,2,3, NA, 5), x2 = c(100, NA, 300, 400, 500))

  x1  x2
1  1 100
3  3 300
5  5 500

Automated testing for REST Api

I have used TestNG and Apache HTTP classes to build my own REST API test framework, I developed this concept after working in Selenium for two years.

Everything is same, except you should use Apache HTTP classes instead of Selenium classes.

give a try, its really cute and good, you've all the power to customize your test framework to your fullest possibilities.

Where does Chrome store extensions?

This link "Finding All Installed Browsers in Windows XP and Vista – beware 64bit!" may be useful for Windows as suggested by "How to find all the browsers installed on a machine".

The installed web browsers are saved in this registry,



How to printf long long

First of all, %d is for a int

So %1.16lld makes no sense, because %d is an integer

That typedef you do, is also unnecessary, use the type straight ahead, makes a much more readable code.

What you want to use is the type double, for calculating pi and then using %f or %1.16f.

Best way to select random rows PostgreSQL

A variation of the materialized view "Possible alternative" outlined by Erwin Brandstetter is possible.

Say, for example, that you don't want duplicates in the randomized values that are returned. So you will need to set a boolean value on the primary table containing your (non-randomized) set of values.

Assuming this is the input table:

id_values  id  |   used
           1   |   FALSE
           2   |   FALSE
           3   |   FALSE
           4   |   FALSE
           5   |   FALSE

Populate the ID_VALUES table as needed. Then, as described by Erwin, create a materialized view that randomizes the ID_VALUES table once:

CREATE MATERIALIZED VIEW id_values_randomized AS
  FROM id_values
  ORDER BY random();

Note that the materialized view does not contain the used column, because this will quickly become out-of-date. Nor does the view need to contain other columns that may be in the id_values table.

In order to obtain (and "consume") random values, use an UPDATE-RETURNING on id_values, selecting id_values from id_values_randomized with a join, and applying the desired criteria to obtain only relevant possibilities. For example:

UPDATE id_values
SET used = TRUE
    FROM id_values_randomized r INNER JOIN id_values i ON =
    WHERE (NOT i.used)
    LIMIT 5)

Change LIMIT as necessary -- if you only need one random value at a time, change LIMIT to 1.

With the proper indexes on id_values, I believe the UPDATE-RETURNING should execute very quickly with little load. It returns randomized values with one database round-trip. The criteria for "eligible" rows can be as complex as required. New rows can be added to the id_values table at any time, and they will become accessible to the application as soon as the materialized view is refreshed (which can likely be run at an off-peak time). Creation and refresh of the materialized view will be slow, but it only needs to be executed when new id's are added to the id_values table.

What does character set and collation mean exactly?

A character encoding is a way to encode characters so that they fit in memory. That is, if the charset is ISO-8859-15, the euro symbol, €, will be encoded as 0xa4, and in UTF-8, it will be 0xe282ac.

The collation is how to compare characters, in latin9, there are letters as e é è ê f, if sorted by their binary representation, it will go e f é ê è but if the collation is set to, for example, French, you'll have them in the order you thought they would be, which is all of e é è ê are equal, and then f.

Print a list of space-separated elements in Python 3

Although the accepted answer is absolutely clear, I just wanted to check efficiency in terms of time.

The best way is to print joined string of numbers converted to strings.

print(" ".join(list(map(str,l))))

Note that I used map instead of loop. I wrote a little code of all 4 different ways to compare time:

import time as t

a, b = 10, 210000
l = list(range(a, b))
tic = t.time()
for i in l:
    print(i, end=" ")

tac = t.time()
t1 = (tac - tic) * 1000
toe = t.time()
t2 = (toe - tac) * 1000
print(" ".join([str(i) for i in l]))
joe = t.time()
t3 = (joe - toe) * 1000
print(" ".join(list(map(str, l))))
toy = t.time()
t4 = (toy - joe) * 1000


Time 74344.76 71790.83 196.99 153.99

The output was quite surprising to me. Huge difference of time in cases of 'loop method' and 'joined-string method'.

Conclusion: Do not use loops for printing list if size is too large( in order of 10**5 or more).

Javascript Cookie with no expiration date

You can do as the example on Mozilla docs:

 document.cookie = "someCookieName=true; expires=Fri, 31 Dec 9999 23:59:59 GMT";


Of course, there will be an issue if humanity still uses your code on the first minute of year 10000 :)

How to create an empty array in Swift?

Initiating an array with a predefined count:

Array(repeating: 0, count: 10)

I often use this for mapping statements where I need a specified number of mock objects. For example,

let myObjects: [MyObject] = Array(repeating: 0, count: 10).map { _ in return MyObject() }

Javascript get object key name

This might be better understood if you modified the wording up a bit:

var buttons = {
  foo: 'bar',
  fiz: 'buz'

for ( var property in buttons ) {
  console.log( property ); // Outputs: foo, fiz or fiz, foo

Note here that you're iterating over the properties of the object, using property as a reference to each during each subsequent cycle.

MSDN says of for ( variable in [object | array ] ) the following:

Before each iteration of a loop, variable is assigned the next property name of object or the next element index of array. You can then use it in any of the statements inside the loop to reference the property of object or the element of array.

Note also that the property order of an object is not constant, and can change, unlike the index order of an array. That might come in handy.

Java ArrayList of Arrays?

As already answered, you can create an ArrayList of String Arrays as @Péter Török written;

    //Declaration of an ArrayList of String Arrays
    ArrayList<String[]> listOfArrayList = new ArrayList<String[]>();

When assigning different String Arrays to this ArrayList, each String Array's length will be different.

In the following example, 4 different Array of String added, their lengths are varying.

String Array #1: len: 3
String Array #2: len: 1
String Array #3: len: 4
String Array #4: len: 2

The Demonstration code is as below;

import java.util.ArrayList;

public class TestMultiArray {

    public static void main(String[] args) {
        //Declaration of an ArrayList of String Arrays
        ArrayList<String[]> listOfArrayList = new ArrayList<String[]>();

        //Assignment of 4 different String Arrays with different lengths
        listOfArrayList.add( new String[]{"line1: test String 1","line1: test String 2","line1: test String 3"}  );
        listOfArrayList.add( new String[]{"line2: test String 1"}  );
        listOfArrayList.add( new String[]{"line3: test String 1","line3: test String 2","line3: test String 3", "line3: test String 4"}  );
        listOfArrayList.add( new String[]{"line4: test String 1","line4: test String 2"}  );

        // Printing out the ArrayList Contents of String Arrays
        // '$' is used to indicate the String elements of String Arrays
        for( int i = 0; i < listOfArrayList.size(); i++ ) {
            for( int j = 0; j < listOfArrayList.get(i).length; j++ )
                System.out.printf(" $ " + listOfArrayList.get(i)[j]);



And the output is as follows;

 $ line1: test String 1 $ line1: test String 2 $ line1: test String 3
 $ line2: test String 1
 $ line3: test String 1 $ line3: test String 2 $ line3: test String 3 $ line3: test String 4
 $ line4: test String 1 $ line4: test String 2

Also notify that you can initialize a new Array of Sting as below;

new String[]{ str1, str2, str3,... }; // Assuming str's are String objects

So this is same with;

String[] newStringArray = { str1, str2, str3 }; // Assuming str's are String objects

I've written this demonstration just to show that no theArrayList object, all the elements are references to different instantiations of String Arrays, thus the length of each String Arrays are not have to be the same, neither it is important.

One last note: It will be best practice to use the ArrayList within a List interface, instead of which that you've used in your question.

It will be better to use the List interface as below;

    //Declaration of an ArrayList of String Arrays
    List<String[]> listOfArrayList = new ArrayList<String[]>();

Post request with Wget?

Wget currently only supports x-www-form-urlencoded data. --post-file is not for transmitting files as form attachments, it expects data with the form: key=value&otherkey=example.

--post-data and --post-file work the same way: the only difference is that --post-data allows you to specify the data in the command line, while --post-file allows you to specify the path of the file that contain the data to send.

Here's the documentation:

           Use POST as the method for all HTTP requests and send the specified data
           in the request body.  --post-data sends string as data, whereas
           --post-file sends the contents of file.  Other than that, they work in
           exactly the same way. In particular, they both expect content of the
           form "key1=value1&key2=value2", with percent-encoding for special
           characters; the only difference is that one expects its content as a
           command-line parameter and the other accepts its content from a file. In
           particular, --post-file is not for transmitting files as form
           attachments: those must appear as "key=value" data (with appropriate
           percent-coding) just like everything else. Wget does not currently
           support "multipart/form-data" for transmitting POST data; only
           "application/x-www-form-urlencoded". Only one of --post-data and
           --post-file should be specified.

Regarding your authentication token, it should either be provided in the header, in the path of the url, or in the data itself. This must be indicated somewhere in the documentation of the service you use. In a POST request, as in a GET request, you must specify the data using keys and values. This way the server will be able to receive multiple information with specific names. It's similar with variables.

Hence, you can't just send a magic token to the server, you also need to specify the name of the key. If the key is "token", then it should be token=YOUR_TOKEN.

wget --post-data 'user=foo&password=bar'

Also, you should consider using curl if you can because it is easier to send files using it. There are many examples on the Internet for that.

Check orientation on Android phone

Some time has passed since most of these answers have been posted and some use now deprecated methods and constants.

I've updated Jarek's code to not use these methods and constants anymore:

protected int getScreenOrientation()
    Display getOrient = getWindowManager().getDefaultDisplay();
    Point size = new Point();


    int orientation;
    if (size.x < size.y)
        orientation = Configuration.ORIENTATION_PORTRAIT;
        orientation = Configuration.ORIENTATION_LANDSCAPE;
    return orientation;

Note that the mode Configuration.ORIENTATION_SQUARE isn't supported anymore.

I found this to be reliable on all devices I've tested it on in contrast to the method suggesting the usage of getResources().getConfiguration().orientation

Java 8 - Best way to transform a list: map or foreach?

One of the main benefits of using streams is that it gives the ability to process data in a declarative way, that is, using a functional style of programming. It also gives multi-threading capability for free meaning there is no need to write any extra multi-threaded code to make your stream concurrent.

Assuming the reason you are exploring this style of programming is that you want to exploit these benefits then your first code sample is potentially not functional since the foreach method is classed as being terminal (meaning that it can produce side-effects).

The second way is preferred from functional programming point of view since the map function can accept stateless lambda functions. More explicitly, the lambda passed to the map function should be

  1. Non-interfering, meaning that the function should not alter the source of the stream if it is non-concurrent (e.g. ArrayList).
  2. Stateless to avoid unexpected results when doing parallel processing (caused by thread scheduling differences).

Another benefit with the second approach is if the stream is parallel and the collector is concurrent and unordered then these characteristics can provide useful hints to the reduction operation to do the collecting concurrently.

Position Absolute + Scrolling

You need to wrap the text in a div element and include the absolutely positioned element inside of it.

<div class="container">
    <div class="inner">
        <div class="full-height"></div>
        [Your text here]


.inner: { position: relative; height: auto; }
.full-height: { height: 100%; }

Setting the inner div's position to relative makes the absolutely position elements inside of it base their position and height on it rather than on the .container div, which has a fixed height. Without the inner, relatively positioned div, the .full-height div will always calculate its dimensions and position based on .container.

* {_x000D_
  box-sizing: border-box;_x000D_
.container {_x000D_
  position: relative;_x000D_
  border: solid 1px red;_x000D_
  height: 256px;_x000D_
  width: 256px;_x000D_
  overflow: auto;_x000D_
  float: left;_x000D_
  margin-right: 16px;_x000D_
.inner {_x000D_
  position: relative;_x000D_
  height: auto;_x000D_
.full-height {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  right: 128px;_x000D_
  bottom: 0;_x000D_
  height: 100%;_x000D_
  background: blue;_x000D_
<div class="container">_x000D_
  <div class="full-height">_x000D_
<div class="container">_x000D_
  <div class="inner">_x000D_
    <div class="full-height">_x000D_
    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aspernatur mollitia maxime facere quae cumque perferendis cum atque quia repellendus rerum eaque quod quibusdam incidunt blanditiis possimus temporibus reiciendis deserunt sequi eveniet necessitatibus_x000D_
    maiores quas assumenda voluptate qui odio laboriosam totam repudiandae? Doloremque dignissimos voluptatibus eveniet rem quasi minus ex cumque esse culpa cupiditate cum architecto! Facilis deleniti unde suscipit minima obcaecati vero ea soluta odio_x000D_
    cupiditate placeat vitae nesciunt quis alias dolorum nemo sint facere. Deleniti itaque incidunt eligendi qui nemo corporis ducimus beatae consequatur est iusto dolorum consequuntur vero debitis saepe voluptatem impedit sint ea numquam quia voluptate_x000D_

Android Location Providers - GPS or Network Provider?

GPS is generally more accurate than network but sometimes GPS is not available, therefore you might need to switch between the two.

A good start might be to look at the android dev site. They had a section dedicated to determining user location and it has all the code samples you need.

How to include a class in PHP

  1. require('/yourpath/yourphp.php');

  2. require_once('/yourpath/yourphp.php');

  3. include '/yourpath/yourphp.php';

  4. use \Yourapp\Yourname


Avoid using require_once because it is slow: Why is require_once so bad to use?

Detect if string contains any spaces

function hasSpaces(str) {
  if (str.indexOf(' ') !== -1) {
    return true
  } else {
    return false

Cannot read property 'length' of null (javascript)

I tried this:

if(capital !== null){ 
//Capital has something 

Access denied for user 'root'@'localhost' while attempting to grant privileges. How do I grant privileges?

You may have come to this question with MySQL version 8 installed (like me) and not found a satisfactory answer. You can no longer create users like this in version 8:


The rather confusing error message that you get back is: ERROR 1410 (42000): You are not allowed to create a user with GRANT

In order to create users in version 8 you have to do it in two steps:

CREATE USER 'steves'@'[hostname].com' IDENTIFIED BY '[OBSCURED]';
GRANT ALL PRIVILEGES ON *.* TO 'steves'@'[hostname].com' WITH GRANT OPTION;

Of course, if you prefer, you can also supply a limited number of privileges (instead of GRANT ALL PRIVILEGES), e.g. GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, ALTER

Dart SDK is not configured

Downloading and Configuring the Dart SDK

If you don’t already have the Dart SDK, install it. You can get it either by itself or by downloading the Flutter SDK, which (as of Flutter 1.21) includes the full Dart SDK.

Choose one:

Here’s one way to configure Dart support:

  1. Start the IDE, and install the Dart plugin. To find the Dart plugin, from the Welcome screen choose Configure > Plugins, then click Install JetBrains plugin, and then search or scroll down until you find Dart. Once you've installed the Dart plugin, restart the IDE.

  2. Create a new Dart project:

    • From the Welcome screen, click Create New Project.
    • In the next dialog, click Dart.
  3. If you don't see a value for the Dart SDK path, enter it.

    • For example, the SDK path might be <dart installation directory>/dart/dart-sdk.

How can I read Chrome Cache files?

I've made short stupid script which extracts JPG and PNG files:

 $dir="/home/user/.cache/chromium/Default/Cache/";//Chrome or chromium cache folder. 
 $ppl="/home/user/Desktop/temporary/"; // Place for extracted files 

 foreach ($list as $filename)

 if (is_file($dir.$filename))
        if  (strstr($cont,'JFIF'))
            echo ($filename."  JPEG \n");
            $end=strpos($cont,"HTTP/1.1 200 OK",0);
            echo("Saving :".$wholename." \n" );

        elseif  (strstr($cont,"\211PNG"))
            echo ($filename."  PNG \n");
            $end=strpos($cont,"HTTP/1.1 200 OK",0);
            echo("Saving :".$wholename." \n" );

            echo ($filename."  UNKNOWN \n");

Unable to install packages in latest version of RStudio and R Version.3.1.1

Based on answers from the community, there appear to be several ways that might solve this:

  1. From the official FAQ and support forums and this answer, you may have have a firewall or proxy issue that is blocking RStudio from connecting to the internet:
  • Disable any firewalls
  • Tools -> Global Options -> Packages and unchecking the "Use Internet Explorer library/proxy for HTTP" option and restart R (#1, #2, #3)
  • Flag R with --internet2
  • On CentOS it was suggested to try the following: install.packages('package_name', dependencies=TRUE, repos='')
  1. Several answers suggest using an alternate mirror (#1, #2, #3):
  • Preferences > General > Default working directory > Browse and switch your mirror from local/global (whichever is unchecked)
  1. On Windows you can start the application with http_proxy=http://host:port/:
  • "C:\Program Files\RStudio\bin\rstudio.exe" http_proxy=http://host:port/
  1. Shut down and restart. Needed after many of the above operations, and suggested standalone.

How do I pass a variable to the layout using Laravel' Blade templating?

It appears as though I can pass variables to the entire layout using attributes on the layout object, for example to solve my problem I was able to do the following:

$this->layout->title = 'Home page';

How to vertically align elements in a div?

Here is just another (responsive) approach:

    body {
        height: 100%;
    body {
        margin: 0;

    .table {
        display: table;
        width:  auto;
        height: 100%;
        .table:nth-child(even) {
            background: #a9edc3;
        .table:nth-child(odd) {
            background: #eda9ce;

    .tr {
        display: table-row;
    .td {
        display: table-cell;
        width: 50%;
        vertical-align: middle;

changing the language of error message in required field in html5 contact form

//Dynamic custome validation on all fields
//add validate-msg attr to all inputs
//add this js code

$("form :input").each(function(){
                    var input = $(this);
                    var msg   = input.attr('validate-msg');
                    input.on('change invalid input', function(){
                        if(!(input[0].validity.tooLong || input[0].validity.tooShort)){
                            if (! input[0].validity.valid) {


How can I send an xml body using requests library?

Pass in the straight XML instead of a dictionary.

How to add external library in IntelliJ IDEA?

I've used this process to attach a 3rd party Jar to an Android project in IDEA.

  • Copy the Jar to your libs/ directory
  • Open Project Settings (Ctrl Alt Shift S)
  • Under the Project Settings panel on the left, choose Modules
  • On the larger right pane, choose the Dependencies tab
  • Press the Add... button on the far right of the screen (if you have a smaller screen like me, you may have to drag resize to the right in order to see it)
  • From the dropdown of Add options, choose "Library". A "Choose Libraries" dialog will appear.
  • Press "New Library..."
  • Choose a suitable title for the library
  • Press "Attach Classes..."
  • Choose the Jar from your libs/ directory, and press OK to dismiss

The library should now be recognised.

jquery stop child triggering parent event

The answers here took the OP's question too literally. How can these answers be expanded into a scenario where there are MANY child elements, not just a single <a> tag? Here's one way.

Let's say you have a photo gallery with a blacked out background and the photos centered in the browser. When you click the black background (but not anything inside of it) you want the overlay to close.

Here's some possible HTML:

<div class="gallery" style="background: black">
    <div class="contents"> <!-- Let's say this div is 50% wide and centered -->
        <h1>Awesome Photos</h1>
        <img src="img1.jpg"><br>
        <img src="img2.jpg"><br>
        <img src="img3.jpg"><br>
        <img src="img4.jpg"><br>
        <img src="img5.jpg">

And here's how the JavaScript would work:


$('.gallery > .contents').click(
    function(e) {

This will stop the click events from elements inside .contents from every research .gallery so the gallery will close only when you click in the faded black background area, but not when you click in the content area. This can be applied to many different scenarios.

What do I need to do to get Internet Explorer 8 to accept a self signed certificate?

As everyone else has mentioned, the first task is to add the certificate to the Trusted Root Authority.

There is a custom exe (selfssl.exe) which will create a certificate and allow you to specify the Issued to: value (the URL). This means Internet explorer will validate the issued to url with the custom intranet url.

Make sure you restart Internet Explorer to refresh changes.

Converting JavaScript object with numeric keys into array

Not sure what I am missing here but simply trying the below code does the work. Am I missing anything here?


var json = {
   "code" :"1", 
   "data" : { 
    "0" : {"id":"1","score":"44"},
    "1" : {"id":"1","score":"44"}


  function createUpdatedJson(){

    var updatedJson = json; = [];



Quick way to create a list of values in C#?

If you're looking to reduce clutter, consider

var lst = new List<string> { "foo", "bar" };

This uses two features of C# 3.0: type inference (the var keyword) and the collection initializer for lists.

Alternatively, if you can make do with an array, this is even shorter (by a small amount):

var arr = new [] { "foo", "bar" };

Change collations of all columns of all tables in SQL Server

To do this I have an easy solution that works for me.

  1. Create a new database with the new collation.
  2. Export the data of the original data base in script mode.
  3. Import the content to the new database using the script (rename the USE sentence to the new database).

However, you need to exercise caution if your database has triggers, procedures or similar - more that just data and tables.

How do I find the index of a character within a string in C?

What about:

char *string = "qwerty";
char *e = string;
int idx = 0;
while (*e++ != 'e') idx++;

copying to e to preserve the original string, I suppose if you don't care you could just operate over *string

What is the meaning of "POSIX"?

Posix is more as an OS, it is an "OS standard". You can imagine it as an imaginary OS, which actually doesn't exist, but it has a documentation. These papers are the "posix standard", defined by the IEEE, which is the big standard organization of the USA. The OSes implementing this specification are "Posix-compliant".

Government regulations prefer Posix-compliant solutions in their investments, thus being Posix-compliant has a significant financial advantage, particularly for the big IT companies of the USA.

The reward for an OS being fully posix compliant, that it is a guarantee that it will compile and run all Posix-compliant applications seamlessly.

Linux is the most well-known one. OSX, Solaris, NetBSD and Windows NT play here as well. Free- and OpenBSD are only "nearly" Posix-compliant. The posix-compliance of the WinNT is only a pseudo-solution to avoid this government regulation above.

What is a Maven artifact?

Usually, when you create a Java project you want to use functionalities made in another Java projects. For example, if your project wants to send one email you dont need to create all the necessary code for doing that. You can bring a java library that does the most part of the work. Maven is a building tool that will help you in several tasks. One of those tasks is to bring these external dependencies or artifacts to your project in an automatic way ( only with some configuration in a XML file ). Of course Maven has more details but, for your question this is enough. And, of course too, Maven can build your project as an artifact (usually a jar file ) that can be used or imported in other projects.

This website has several articles talking about Maven :

How to declare a global variable in React?

Create a file named "config.js" in ./src folder with this content:

module.exports = global.config = {
    i18n: {
        welcome: {
            en: "Welcome",
            fa: "??? ?????"
        // rest of your translation object
    // other global config variables you wish

In your main file "index.js" put this line:

import './config';

Everywhere you need your object use this:


How to get the selected item of a combo box to a string variable in c#

SelectedText = this.combobox.SelectionBoxItem.ToString();

Eclipse error: "The import XXX cannot be resolved"

If is a Maven project, also click on Maven >> Update project... (F5)

Update Maven project

How to interpolate variables in strings in JavaScript, without concatenation?

Prior to Firefox 34 / Chrome 41 / Safari 9 / Microsoft Edge, no. Although you could try sprintf for JavaScript to get halfway there:

var hello = "foo";
var my_string = sprintf("I pity the %s", hello);

Using CSS how to change only the 2nd column of a table

on this web i found that easy way

<col style="background-color: #6374AB; color: #ffffff" />
<col span="2" style="background-color: #07B133; color: #ffffff;" />

Extract data from XML Clob using SQL from Oracle Database

This should work

SELECT EXTRACTVALUE(column_name, '/DCResponse/ContextData/Decision') FROM traptabclob;

I have assumed the ** were just for highlighting?

Plot correlation matrix using pandas

Seaborn's heatmap version:

import seaborn as sns
corr = dataframe.corr()

file_put_contents: Failed to open stream, no such file or directory

There is definitly a problem with the destination folder path.

Your above error message says, it wants to put the contents to a file in the directory /files/grantapps/, which would be beyond your vhost, but somewhere in the system (see the leading absolute slash )

You should double check:

  • Is the directory /home/username/public_html/files/grantapps/ really present.
  • Contains your loop and your file_put_contents-Statement the absolute path /home/username/public_html/files/grantapps/

Unix's 'ls' sort by name

My ls sorts by name by default. What are you seeing?

man ls states:

List information about the FILEs (the current directory by default). Sort entries alpha-betically if none of -cftuvSUX nor --sort is specified.:

How to check the multiple permission at single request in Android M?

Based on vedval i have this solution.

public boolean checkForPermission(final String[] permissions, final int permRequestCode) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
        return true;
    final List<String> permissionsNeeded = new ArrayList<>();
    for (int i = 0; i < permissions.length; i++) {
        final String perm = permissions[i];
        if (ContextCompat.checkSelfPermission(this, permissions[i]) != PackageManager.PERMISSION_GRANTED) {
            if (shouldShowRequestPermissionRationale(permissions[i])) {
                Snackbar.make(phrase, R.string.permission_location, Snackbar.LENGTH_INDEFINITE)
                        .setAction(android.R.string.ok, new View.OnClickListener() {
                            public void onClick(View v) {
            } else {
                // add the request.

    if (permissionsNeeded.size() > 0) {
        // go ahead and request permissions
        requestPermissions(permissionsNeeded.toArray(new String[permissionsNeeded.size()]), permRequestCode);
        return false;
    } else {
        // no permission need to be asked so all good...we have them all.
        return true;

 * Callback received when a permissions request has been completed.
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                       @NonNull int[] grantResults) {
    if (requestCode == REQUEST_READ_LOCATION) {
        int i = 0;
        for (String permission : permissions ){
            if ( permission.equals(Manifest.permission.ACCESS_FINE_LOCATION) && grantResults.length > 0 && grantResults[i] == PackageManager.PERMISSION_GRANTED) {


grant remote access of MySQL database from any IP address

To remotely access database Mysql server 8:

CREATE USER 'root'@'%' IDENTIFIED BY 'Pswword@123';



Convert stdClass object to array in PHP

Try this:

$new_array = objectToArray($yourObject);

function objectToArray($d) 
    if (is_object($d)) {
        // Gets the properties of the given object
        // with get_object_vars function
        $d = get_object_vars($d);

    if (is_array($d)) {
        * Return array converted to object
        * Using __FUNCTION__ (Magic constant)
        * for recursive call
        return array_map(__FUNCTION__, $d);
    } else {
        // Return array
        return $d;

How to get POSTed JSON in Flask?

For all those whose issue was from the ajax call, here is a full example :

Ajax call : the key here is to use a dict and then JSON.stringify

    var dict = {username : "username" , password:"password"};

        type: "POST", 
        url: "", //localhost Flask
        data : JSON.stringify(dict),
        contentType: "application/json",

And on server side :

from flask import Flask
from flask import request
import json

app = Flask(__name__)

@app.route("/",  methods = ['POST'])
def hello():
    return json.dumps({'success':True}), 200, {'ContentType':'application/json'} 

if __name__ == "__main__":

A server with the specified hostname could not be found

First of all check your internet connection.. go to safari and check by searching something on google(dont try only.. because it can be cached). If it is working fine, then try now in your app. It must work. This is fired while not having proper internet connection.

Python: How to get stdout after running os.system?

I had to use os.system, since subprocess was giving me a memory error for larger tasks. Reference for this problem here. So, in order to get the output of the os.system command I used this workaround:

import os

batcmd = 'dir'
result_code = os.system(batcmd + ' > output.txt')
if os.path.exists('output.txt'):
    fp = open('output.txt', "r")
    output =

Set content of iframe

Using Blob:

var iframe = document.getElementById("myiframe");
var blob = new Blob([s], {type: "text/html; charset=utf-8"});
iframe.src = URL.createObjectURL(blob);

Python: how to capture image from webcam on click using OpenCV

i'm not too experienced with open cv but if you want the code in the for loop to be called when a key is pressed, you can use a while loop and an raw_input and a condition to prevent the loop from executing forever

import cv2

camera = cv2.VideoCapture(0)
i = 0
while i < 10:
    raw_input('Press Enter to capture')
    return_value, image =
    cv2.imwrite('opencv'+str(i)+'.png', image)
    i += 1

How can I read a whole file into a string variable

I think the best thing to do, if you're really concerned about the efficiency of concatenating all of these files, is to copy them all into the same bytes buffer.

buf := bytes.NewBuffer(nil)
for _, filename := range filenames {
  f, _ := os.Open(filename) // Error handling elided for brevity.
  io.Copy(buf, f)           // Error handling elided for brevity.
s := string(buf.Bytes())

This opens each file, copies its contents into buf, then closes the file. Depending on your situation you may not actually need to convert it, the last line is just to show that buf.Bytes() has the data you're looking for.

Unable to generate an explicit migration in entity framework

This isn't going to be the answer for many people, but EF will chuck this error when it can't connect to the DB. If you're working from home like I am, make sure you're still connected to your VPN!

Styling a disabled input with css only

A space in a CSS selector selects child elements.

.btn input

This is basically what you wrote and it would select <input> elements within any element that has the btn class.

I think you're looking for

input[disabled].btn:hover, input[disabled].btn:active, input[disabled].btn:focus

This would select <input> elements with the disabled attribute and the btn class in the three different states of hover, active and focus.

How do I find the PublicKeyToken for a particular dll?

You can also check by following method.

Go to Run : type the path of DLL for which you need public key. You will find 2 files : 1. __AssemblyInfo_.ini 2. DLL file

Open this __AssemblyInfo_.ini file in notepad , here you can see Public Key Token.

Convert a list to a data frame

Depending on the structure of your lists there are some tidyverse options that work nicely with unequal length lists:

l <- list(a = list(var.1 = 1, var.2 = 2, var.3 = 3)
        , b = list(var.1 = 4, var.2 = 5)
        , c = list(var.1 = 7, var.3 = 9)
        , d = list(var.1 = 10, var.2 = 11, var.3 = NA))

df <- dplyr::bind_rows(l)
df <- purrr::map_df(l, dplyr::bind_rows)
df <- purrr::map_df(l, ~.x)

# all create the same data frame:
# A tibble: 4 x 3
  var.1 var.2 var.3
  <dbl> <dbl> <dbl>
1     1     2     3
2     4     5    NA
3     7    NA     9
4    10    11    NA

You can also mix vectors and data frames:

  list(a = 1, b = 2),
  data_frame(a = 3:4, b = 5:6),
  c(a = 7)

# A tibble: 4 x 2
      a     b
  <dbl> <dbl>
1     1     2
2     3     5
3     4     6
4     7    NA

How can I get the executing assembly version?

using System.Reflection;
    string version = Assembly.GetEntryAssembly().GetName().Version.ToString();

Remarks from MSDN

The GetEntryAssembly method can return null when a managed assembly has been loaded from an unmanaged application. For example, if an unmanaged application creates an instance of a COM component written in C#, a call to the GetEntryAssembly method from the C# component returns null, because the entry point for the process was unmanaged code rather than a managed assembly.

Why is __init__() always called after __new__()?

When __new__ returns instance of the same class, __init__ is run afterwards on returned object. I.e. you can NOT use __new__ to prevent __init__ from being run. Even if you return previously created object from __new__, it will be double (triple, etc...) initialized by __init__ again and again.

Here is the generic approach to Singleton pattern which extends vartec answer above and fixes it:

def SingletonClass(cls):
    class Single(cls):
        __doc__ = cls.__doc__
        _initialized = False
        _instance = None

        def __new__(cls, *args, **kwargs):
            if not cls._instance:
                cls._instance = super(Single, cls).__new__(cls, *args, **kwargs)
            return cls._instance

        def __init__(self, *args, **kwargs):
            if self._initialized:
            super(Single, self).__init__(*args, **kwargs)
            self.__class__._initialized = True  # Its crucial to set this variable on the class!
    return Single

Full story is here.

Another approach, which in fact involves __new__ is to use classmethods:

class Singleton(object):
    __initialized = False

    def __new__(cls, *args, **kwargs):
        if not cls.__initialized:
            cls.__init__(*args, **kwargs)
            cls.__initialized = True
        return cls

class MyClass(Singleton):
    def __init__(cls, x, y):
        print "init is here"

    def do(cls):
        print "doing stuff"

Please pay attention, that with this approach you need to decorate ALL of your methods with @classmethod, because you'll never use any real instance of MyClass.

How to scroll to bottom in react?

Working Example:

You can use the DOM scrollIntoView method to make a component visible in the view.

For this, while rendering the component just give a reference ID for the DOM element using ref attribute. Then use the method scrollIntoView on componentDidMount life cycle. I am just putting a working sample code for this solution. The following is a component rendering each time a message received. You should write code/methods for rendering this component.

class ChatMessage extends Component {
    scrollToBottom = (ref) => {
        this.refs[ref].scrollIntoView({ behavior: "smooth" });

    componentDidMount() {

    render() {
            <div ref={this.props.message.MessageId}>
                <div>Message content here...</div>

Here this.props.message.MessageId is the unique ID of the particular chat message passed as props

Mapping US zip code to time zone

I've been working on this problem for my own site and feel like I've come up with a pretty good solution

1) Assign time zones to all states with only one timezone (most states)

and then either

2a) use the js solution (Javascript/PHP and timezones) for the remaining states


2b) use a database like the one linked above by @Doug.

This way, you can find tz cheaply (and highly accurately!) for the majority of your users and then use one of the other, more expensive methods to get it for the rest of the states.

Not super elegant, but seemed better to me than using js or a database for each and every user.

How to quickly and conveniently disable all console.log statements in my code?

I wrote a ES2015 solution ( use only with Webpack ).

class logger {
  static isEnabled = true;

  static enable () {
    if(this.constructor.isEnabled === true){ return; }

    this.constructor.isEnabled = true;

  static disable () {
    if(this.constructor.isEnabled === false){ return; }

    this.constructor.isEnabled = false;

  static log () {
    if(this.constructor.isEnabled === false ) { return; }

    const copy = [];

    window['console']['log'].apply(this, copy);

  static warn () {
    if(this.constructor.isEnabled === false ) { return; }

    const copy = [];

    window['console']['warn'].apply(this, copy);

  static error () {
    if(this.constructor.isEnabled === false ) { return; }

    const copy = [];

    window['console']['error'].apply(this, copy);


  1. Along with logger.enable and logger.disable you can use console.['log','warn','error'] methods as well using logger class.
  2. By using logger class for displaying, enabling or disabling messages makes the code much cleaner and maintainable.
  3. The code below shows you how to use the logger class:
    • logger.disable() - disable all console messages
    • logger.enable() - enable all console messages
    • logger.log('message1', 'message2') - works exactly like console.log.
    • logger.warn('message1', 'message2') - works exactly like console.warn.
    • logger.error('message1', 'message2') - works exactly like console.error. Happy coding..

How to set String's font size, style in Java using the Font class?

Font myFont = new Font("Serif", Font.BOLD, 12);, then use a setFont method on your components like

JButton b = new JButton("Hello World");

How to update Ruby with Homebrew?

To upgrade Ruby with rbenv: Per the rbenv README

  • Update first: brew upgrade rbenv ruby-build
  • See list of Ruby versions: versions available: rbenv install -l
  • Install: rbenv install <selected version>

Show Console in Windows Application?

What you want to do is not possible in a sane way. There was a similar question so look at the answers.

Then there's also an insane approach (site down - backup available here.) written by Jeffrey Knight:

Question: How do I create an application that can run in either GUI (windows) mode or command line / console mode?

On the surface of it, this would seem easy: you create a Console application, add a windows form to it, and you're off and running. However, there's a problem:

Problem: If you run in GUI mode, you end up with both a window and a pesky console lurking in the background, and you don't have any way to hide it.

What people seem to want is a true amphibian application that can run smoothly in either mode.

If you break it down, there are actually four use cases here:

User starts application from existing cmd window, and runs in GUI mode
User double clicks to start application, and runs in GUI mode
User starts application from existing cmd window, and runs in command mode
User double clicks to start application, and runs in command mode.

I'm posting the code to do this, but with a caveat.

I actually think this sort of approach will run you into a lot more trouble down the road than it's worth. For example, you'll have to have two different UIs' -- one for the GUI and one for the command / shell. You're going to have to build some strange central logic engine that abstracts from GUI vs. command line, and it's just going to get weird. If it were me, I'd step back and think about how this will be used in practice, and whether this sort of mode-switching is worth the work. Thus, unless some special case called for it, I wouldn't use this code myself, because as soon as I run into situations where I need API calls to get something done, I tend to stop and ask myself "am I overcomplicating things?".

Output type=Windows Application

using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Diagnostics;
using Microsoft.Win32;

namespace WindowsApplication
    static class Program
    DEMO CODE ONLY: In general, this approach calls for re-thinking 
    your architecture!
    There are 4 possible ways this can run:
    1) User starts application from existing cmd window, and runs in GUI mode
    2) User double clicks to start application, and runs in GUI mode
    3) User starts applicaiton from existing cmd window, and runs in command mode
    4) User double clicks to start application, and runs in command mode.

    To run in console mode, start a cmd shell and enter:
        c:\path\to\Debug\dir\WindowsApplication.exe console
        To run in gui mode,  EITHER just double click the exe, OR start it from the cmd prompt with:
        c:\path\to\Debug\dir\WindowsApplication.exe (or pass the "gui" argument).
        To start in command mode from a double click, change the default below to "console".
    In practice, I'm not even sure how the console vs gui mode distinction would be made from a
    double click...
        string mode = args.Length > 0 ? args[0] : "console"; //default to console

        [DllImport("kernel32.dll", SetLastError = true)]
        static extern bool AllocConsole();

        [DllImport("kernel32.dll", SetLastError = true)]
        static extern bool FreeConsole();

        [DllImport("kernel32", SetLastError = true)]
        static extern bool AttachConsole(int dwProcessId);

        static extern IntPtr GetForegroundWindow();

        [DllImport("user32.dll", SetLastError = true)]
        static extern uint GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId);

        static void Main(string[] args)
            //TODO: better handling of command args, (handle help (--help /?) etc.)
            string mode = args.Length > 0 ? args[0] : "gui"; //default to gui

            if (mode == "gui")
                MessageBox.Show("Welcome to GUI mode");



                Application.Run(new Form1());
            else if (mode == "console")

                //Get a pointer to the forground window.  The idea here is that
                //IF the user is starting our application from an existing console
                //shell, that shell will be the uppermost window.  We'll get it
                //and attach to it
                IntPtr ptr = GetForegroundWindow();

                int  u;

                GetWindowThreadProcessId(ptr, out u);

                Process process = Process.GetProcessById(u);

                if (process.ProcessName == "cmd" )    //Is the uppermost window a cmd process?

                    //we have a console to attach to ..
                    Console.WriteLine("hello. It looks like you started me from an existing console.");
                    //no console AND we're in console mode ... create a new console.


                    Console.WriteLine(@"hello. It looks like you double clicked me to start
                   AND you want console mode.  Here's a new console.");
                    Console.WriteLine("press any key to continue ...");


How to style SVG <g> element?

You cannot add style to an SVG <g> element. Its only purpose is to group children. That means, too, that style attributes you give to it are given down to its children, so a fill="green" on the <g> means an automatic fill="green" on its child <rect> (as long as it has no own fill specification).

Your only option is to add a new <rect> to the SVG and place it accordingly to match the <g> children's dimensions.

RESTful Authentication

It's certainly not about "session keys" as it is generally used to refer to sessionless authentication which is performed within all of the constraints of REST. Each request is self-describing, carrying enough information to authorize the request on its own without any server-side application state.

The easiest way to approach this is by starting with HTTP's built-in authentication mechanisms in RFC 2617.

Python strftime - date without leading 0?

>>> import datetime
>>> d =
>>> d.strftime('X%d/X%m/%Y').replace('X0','X').replace('X','')

Get JSON Data from URL Using Android?

If you get the server response as a String, without using a third party library you can do

JSONObject json = new JSONObject(response);
JSONObject jsonResponse = json.getJSONObject("response");
String team = jsonResponse.getString("Team");

Here is the documentation

Otherwise to parse json you can use Gson or Jackson

EDIT without libraries (not tested)

class retrievedata extends AsyncTask<Void, Void, String>{
    protected String doInBackground(Void... params) {

        HttpURLConnection urlConnection = null;
        BufferedReader reader = null;

        URL url;
        try {
            url = new URL("");
            urlConnection.setRequestMethod("GET"); //Your method here 

            InputStream inputStream = urlConnection.getInputStream();
            StringBuffer buffer = new StringBuffer();
            if (inputStream == null) {
                return null;
            reader = new BufferedReader(new InputStreamReader(inputStream));

            String line;
            while ((line = reader.readLine()) != null)
                buffer.append(line + "\n");

            if (buffer.length() == 0)
                return null;

            return buffer.toString();
        } catch (IOException e) {
            Log.e(TAG, "IO Exception", e);
            exception = e;
            return null;
        } finally {
            if (urlConnection != null) {
            if (reader != null) {
                try {
                } catch (final IOException e) {
                    exception = e;
                    Log.e(TAG, "Error closing stream", e);

    protected void onPostExecute(String response) {
        if(response != null) {
            JSONObject json = new JSONObject(response);
            JSONObject jsonResponse = json.getJSONObject("response");
            String team = jsonResponse.getString("Team");

map function for objects (instead of arrays)

ES6: = function(mapFunc) {
    return Object.keys(this).map((key, index) => mapFunc(key, this[key], index));

ES2015: = function (mapFunc) {
    var _this = this;

    return Object.keys(this).map(function (key, index) {
        return mapFunc(key, _this[key], index);

test in node:

> a = {foo: "bar"}
{ foo: 'bar' }
>,v,i) => v)
[ 'bar' ]

Django request.GET

Here is a good way to do it.

from django.utils.datastructures import MultiValueDictKeyError
    message = 'You submitted: %r' % request.GET['q']
except MultiValueDictKeyError:
    message = 'You submitted nothing!'

You don't need to check again if q is in GET request. The call in the QueryDict.get already does that to you.

Can I inject a service into a directive in AngularJS?

You can do injection on Directives, and it looks just like it does everywhere else.

app.directive('changeIt', ['myData', function(myData){
    return {
        restrict: 'C',
        link: function (scope, element, attrs) {

Printing 2D array in matrix format

You can do it like this (with a slightly modified array to show it works for non-square arrays):

        long[,] arr = new long[5, 4] { { 1, 2, 3, 4 }, { 1, 1, 1, 1 }, { 2, 2, 2, 2 }, { 3, 3, 3, 3 }, { 4, 4, 4, 4 } };

        int rowLength = arr.GetLength(0);
        int colLength = arr.GetLength(1);

        for (int i = 0; i < rowLength; i++)
            for (int j = 0; j < colLength; j++)
                Console.Write(string.Format("{0} ", arr[i, j]));
            Console.Write(Environment.NewLine + Environment.NewLine);

How to convert a pymongo.cursor.Cursor into a dict?

The find method returns a Cursor instance, which allows you to iterate over all matching documents.

To get the first document that matches the given criteria you need to use find_one. The result of find_one is a dictionary.

You can always use the list constructor to return a list of all the documents in the collection but bear in mind that this will load all the data in memory and may not be what you want.

You should do that if you need to reuse the cursor and have a good reason not to use rewind()

Demo using find:

>>> import pymongo
>>> conn = pymongo.MongoClient()
>>> db = conn.test #test is my database
>>> col = db.spam #Here spam is my collection
>>> cur = col.find()  
>>> cur
<pymongo.cursor.Cursor object at 0xb6d447ec>
>>> for doc in cur:
...     print(doc)  # or do something with the document
{'a': 1, '_id': ObjectId('54ff30faadd8f30feb90268f'), 'b': 2}
{'a': 1, 'c': 3, '_id': ObjectId('54ff32a2add8f30feb902690'), 'b': 2}

Demo using find_one:

>>> col.find_one()
{'a': 1, '_id': ObjectId('54ff30faadd8f30feb90268f'), 'b': 2}

Curl and PHP - how can I pass a json through curl by PUT,POST,GET

set one more property curl_setopt($ch, CURLOPT_SSL_VERIFYPEER , false);

Throwing multiple exceptions in a method of an interface in java

You need to specify it on the methods that can throw the exceptions. You just seperate them with a ',' if it can throw more than 1 type of exception. e.g.

public interface MyInterface {
  public MyObject find(int x) throws MyExceptionA,MyExceptionB;

How to fill DataTable with SQL Table

You need to modify the method GetData() and add your "experimental" code there, and return t1.

Error: class X is public should be declared in a file named

You named your file as name your file as and compile.

How to auto resize and adjust Form controls with change in resolution

float widthRatio = Screen.PrimaryScreen.Bounds.Width / 1280;
float heightRatio = Screen.PrimaryScreen.Bounds.Height / 800f;
SizeF scale = new SizeF(widthRatio, heightRatio);
foreach (Control control in this.Controls)
control.Font = new Font("Verdana", control.Font.SizeInPoints * heightRatio * widthRatio);

Best practices for catching and re-throwing .NET exceptions

When you throw ex, you're essentially throwing a new exception, and will miss out on the original stack trace information. throw is the preferred method.

Show Error on the tip of the Edit Text Android

It seems all you can't get is to show the error at the end of editText. Set your editText width to match that of the parent layout enveloping. Will work just fine.

not None test in Python

The best bet with these types of questions is to see exactly what python does. The dis module is incredibly informative:

>>> import dis
>>> dis.dis("val != None")
  1           0 LOAD_NAME                0 (val)
              2 LOAD_CONST               0 (None)
              4 COMPARE_OP               3 (!=)
              6 RETURN_VALUE
>>> dis.dis("not (val is None)")
  1           0 LOAD_NAME                0 (val)
              2 LOAD_CONST               0 (None)
              4 COMPARE_OP               9 (is not)
              6 RETURN_VALUE
>>> dis.dis("val is not None")
  1           0 LOAD_NAME                0 (val)
              2 LOAD_CONST               0 (None)
              4 COMPARE_OP               9 (is not)
              6 RETURN_VALUE

Notice that the last two cases reduce to the same sequence of operations, Python reads not (val is None) and uses the is not operator. The first uses the != operator when comparing with None.

As pointed out by other answers, using != when comparing with None is a bad idea.

How to test if string exists in file with Bash?

grep -Fxq "$FILENAME" my_list.txt

The exit status is 0 (true) if the name was found, 1 (false) if not, so:

if grep -Fxq "$FILENAME" my_list.txt
    # code if found
    # code if not found


Here are the relevant sections of the man page for grep:

grep [options] PATTERN [FILE...]

-F, --fixed-strings

        Interpret PATTERN as a list of fixed strings, separated by newlines, any of which is to be matched.

-x, --line-regexp

        Select only those matches that exactly match the whole line.

-q, --quiet, --silent

        Quiet; do not write anything to standard output. Exit immediately with zero status if any match is found, even if an error was detected. Also see the -s or --no-messages option.

Error handling

As rightfully pointed out in the comments, the above approach silently treats error cases as if the string was found. If you want to handle errors in a different way, you'll have to omit the -q option, and detect errors based on the exit status:

Normally, the exit status is 0 if selected lines are found and 1 otherwise. But the exit status is 2 if an error occurred, unless the -q or --quiet or --silent option is used and a selected line is found. Note, however, that POSIX only mandates, for programs such as grep, cmp, and diff, that the exit status in case of error be greater than 1; it is therefore advisable, for the sake of portability, to use logic that tests for this general condition instead of strict equality with 2.

To suppress the normal output from grep, you can redirect it to /dev/null. Note that standard error remains undirected, so any error messages that grep might print will end up on the console as you'd probably want.

To handle the three cases, we can use a case statement:

case `grep -Fx "$FILENAME" "$LIST" >/dev/null; echo $?` in
    # code if found
    # code if not found
    # code if an error occurred

How to create a link to another PHP page

Use like this

<a href="index.php">Index Page</a>
<a href="page2.php">Page 2</a>

How to put a component inside another component in Angular2?

If you remove directives attribute it should work.

    selector: 'parent',
    template: `
            <h1>Parent Component</h1>
    export class ParentComponent{}

    selector: 'child',    
    template: `
            <h4>Child Component</h4>
    export class ChildComponent{}

Directives are like components but they are used in attributes. They also have a declarator @Directive. You can read more about directives Structural Directives and Attribute Directives.

There are two other kinds of Angular directives, described extensively elsewhere: (1) components and (2) attribute directives.

A component manages a region of HTML in the manner of a native HTML element. Technically it's a directive with a template.

Also if you are open the glossary you can find that components are also directives.

Directives fall into one of the following categories:

  • Components combine application logic with an HTML template to render application views. Components are usually represented as HTML elements. They are the building blocks of an Angular application.

  • Attribute directives can listen to and modify the behavior of other HTML elements, attributes, properties, and components. They are usually represented as HTML attributes, hence the name.

  • Structural directives are responsible for shaping or reshaping HTML layout, typically by adding, removing, or manipulating elements and their children.

The difference that components have a template. See Angular Architecture overview.

A directive is a class with a @Directive decorator. A component is a directive-with-a-template; a @Component decorator is actually a @Directive decorator extended with template-oriented features.

The @Component metadata doesn't have directives attribute. See Component decorator.

Sending cookies with postman

You should enable your interceptor extension man manually, it locate in the top-right of your postman window. There are several buttons, find the interceptor button and enable it, then you can send cookies after set Cookie field in your request headers.

jQuery - What are differences between $(document).ready and $(window).load?

The Difference between $(document).ready() and $(window).load() functions is that the code included inside $(window).load() will run once the entire page(images, iframes, stylesheets,etc) are loaded whereas the document ready event fires before all images,iframes etc. are loaded, but after the whole DOM itself is ready.









There are not difference between the above 3 codes.

They are equivalent,but you may face conflict if any other JavaScript Frameworks uses the same dollar symbol $ as a shortcut name.

 //Code using $ as alias to jQuery

Facebook Graph API : get larger pictures in one request

JS styled variant. Just set enormous large picture width and you will get the largest variant.

  '/' + userId,
  {fields: 'picture.width(2048)'},
  function (response) {
    if (response && !response.error) {

Android, How to limit width of TextView (and add three dots at the end of text)?

The approach of @AzharShaikh works fine.


But I realize a trouble that TextView will be truncated by word (in default). Show if we have a text like:

test long_line_without_any_space_abcdefgh

the TextView will display:


And I found solution to handle this trouble, replace spaces with the unicode no-break space character, it makes TextView wrap on characters instead of words:

yourString.replace(" ", "\u00A0");

The result:

test long_line_without_any_space_abc...

How to set max and min value for Y axis

Just set the value for scaleStartValue in your options.

var options = {
   // ....
   scaleStartValue: 0,

See the documentation for this here.

REST API Token-based Authentication

In the web a stateful protocol is based on having a temporary token that is exchanged between a browser and a server (via cookie header or URI rewriting) on every request. That token is usually created on the server end, and it is a piece of opaque data that has a certain time-to-live, and it has the sole purpose of identifying a specific web user agent. That is, the token is temporary, and becomes a STATE that the web server has to maintain on behalf of a client user agent during the duration of that conversation. Therefore, the communication using a token in this way is STATEFUL. And if the conversation between client and server is STATEFUL it is not RESTful.

The username/password (sent on the Authorization header) is usually persisted on the database with the intent of identifying a user. Sometimes the user could mean another application; however, the username/password is NEVER intended to identify a specific web client user agent. The conversation between a web agent and server based on using the username/password in the Authorization header (following the HTTP Basic Authorization) is STATELESS because the web server front-end is not creating or maintaining any STATE information whatsoever on behalf of a specific web client user agent. And based on my understanding of REST, the protocol states clearly that the conversation between clients and server should be STATELESS. Therefore, if we want to have a true RESTful service we should use username/password (Refer to RFC mentioned in my previous post) in the Authorization header for every single call, NOT a sension kind of token (e.g. Session tokens created in web servers, OAuth tokens created in authorization servers, and so on).

I understand that several called REST providers are using tokens like OAuth1 or OAuth2 accept-tokens to be be passed as "Authorization: Bearer " in HTTP headers. However, it appears to me that using those tokens for RESTful services would violate the true STATELESS meaning that REST embraces; because those tokens are temporary piece of data created/maintained on the server side to identify a specific web client user agent for the valid duration of a that web client/server conversation. Therefore, any service that is using those OAuth1/2 tokens should not be called REST if we want to stick to the TRUE meaning of a STATELESS protocol.


Batch Extract path and filename from a variable

set file=C:\Users\l72rugschiri\Desktop\fs.cfg
FOR %%i IN ("%file%") DO (
ECHO filedrive=%%~di
ECHO filepath=%%~pi
ECHO filename=%%~ni
ECHO fileextension=%%~xi

Not really sure what you mean by no "function"

Obviously, change ECHO to SET to set the variables rather thon ECHOing them...

See for documentation for a full list.

ceztko's test case (for reference)

set file="C:\Users\ l72rugschiri\Desktop\fs.cfg"
FOR /F "delims=" %%i IN ("%file%") DO (
ECHO filedrive=%%~di
ECHO filepath=%%~pi
ECHO filename=%%~ni
ECHO fileextension=%%~xi

Comment : please see comments.

Cannot catch toolbar home button click event

    mActionBarDrawerToggle = mNavigationDrawerFragment.getActionBarDrawerToggle();
    mActionBarDrawerToggle.setToolbarNavigationClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            // event when click home button

in mycase this code work perfect

WCF Error - Could not find default endpoint element that references contract 'UserService.UserService'

In case if you are using WPF application using PRISM framework then configuration should exist in your start up project (i.e. in the project where your bootstrapper resides.)

In short just remove it from the class library and put into a start up project.

Countdown timer in React

The one downside with setInterval is that it can slow down the main thread. You can do a countdown timer using requestAnimationFrame instead to prevent this. For example, this is my generic countdown timer component:

class Timer extends Component {
  constructor(props) {
    // here, getTimeRemaining is a helper function that returns an 
    // object with { total, seconds, minutes, hours, days }
    this.state = { timeLeft: getTimeRemaining(props.expiresAt) }

  // Wait until the component has mounted to start the animation frame
  componentDidMount() {

  // Clean up by cancelling any animation frame previously scheduled
  componentWillUnmount() {

  start = () => {
    this.frameId = requestAnimationFrame(this.tick)

  tick = () => {
    const timeLeft = getTimeRemaining(this.props.expiresAt)
    if ( <= 0) {
      // ...any other actions to do on expiration
    } else {
        { timeLeft },
        () => this.frameId = requestAnimationFrame(this.tick)

  stop = () => {

  render() {...}

OpenCV - Apply mask to a color image

Answer given by Abid Rahman K is not completely correct. I also tried it and found very helpful but got stuck.

This is how I copy image with a given mask.

x, y = np.where(mask!=0)
pts = zip(x, y)
# Assuming dst and src are of same sizes
for pt in pts:
   dst[pt] = src[pt]

This is a bit slow but gives correct results.


Pythonic way.

idx = (mask!=0)
dst[idx] = src[idx]

How can I clone a private GitLab repository?

You have your ssh clone statement wrong: git clone username [email protected]:root/test.git

That statement would try to clone a repository named username into the location relative to your current path, [email protected]:root/test.git.

You want to leave out username:

git clone [email protected]:root/test.git

Postgresql query between date ranges

SELECT user_id 
FROM user_logs 
WHERE login_date BETWEEN '2014-02-01' AND '2014-03-01'

Between keyword works exceptionally for a date. it assumes the time is at 00:00:00 (i.e. midnight) for dates.

How does python numpy.where() work?

How do they achieve internally that you are able to pass something like x > 5 into a method?

The short answer is that they don't.

Any sort of logical operation on a numpy array returns a boolean array. (i.e. __gt__, __lt__, etc all return boolean arrays where the given condition is true).


x = np.arange(9).reshape(3,3)
print x > 5


array([[False, False, False],
       [False, False, False],
       [ True,  True,  True]], dtype=bool)

This is the same reason why something like if x > 5: raises a ValueError if x is a numpy array. It's an array of True/False values, not a single value.

Furthermore, numpy arrays can be indexed by boolean arrays. E.g. x[x>5] yields [6 7 8], in this case.

Honestly, it's fairly rare that you actually need numpy.where but it just returns the indicies where a boolean array is True. Usually you can do what you need with simple boolean indexing.

Creating a Jenkins environment variable using Groovy

You can also define a variable without the EnvInject Plugin within your Groovy System Script:

import hudson.model.*
def build = Thread.currentThread().executable
def pa = new ParametersAction([
  new StringParameterValue("FOO", "BAR")

Then you can access this variable in the next build step which (for example) is an windows batch command:

@echo off
Setlocal EnableDelayedExpansion
echo FOO=!FOO!

This echo will show you "FOO=BAR".


Decimal to Hexadecimal Converter in Java

Here's mine

public static String dec2Hex(int num)
    String hex = "";

    while (num != 0)
        if (num % 16 < 10)
            hex = Integer.toString(num % 16) + hex;
            hex = (char)((num % 16)+55) + hex;
        num = num / 16;

    return hex;

The name 'model' does not exist in current context in MVC3

Had similar problems using VS2012 and VS2013.
Adding the following line to <appSettings> in the main web.config worked:

<add key="webpages:Version" value="" />

If the line was already there but said, changing it to worked.

Google Play Services GCM 9.2.0 asks to "update" back to 9.0.0

I had the same problem, today 2016 - october - 06 I solved with this:

I changed all dependencies that began with 9.?.? to 9.6.1 I compiled with sdk version 24 and target version 17.

There is another packages in my solution because I used more things then only authentication.

After changed your build.gradle (Module:app) with the code below do it:

  1. Put your package NAME in the line with the words applicationId "com.YOUR_PACKAGE_HERE"

  2. Synchronize your project (Ctrl+alt+v) and Build Again.

This is the code of the file buid.gradle (Module:app) that worked for me:

apply plugin: ''

android {
    compileSdkVersion 24
    buildToolsVersion "24.0.3"
    defaultConfig {
        applicationId "com.YOUR_PACKAGE_HERE"
        minSdkVersion 24
        targetSdkVersion 17
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner ""
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), ''

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('', {
        exclude group: '', module: 'support-annotations'

    compile ''
    compile ''

    compile ''
    compile ''

    compile ''
    testCompile 'junit:junit:4.12'

    compile ''

    compile ''

    compile ''

    compile ''

apply plugin: ''

Section vs Article HTML5

My interpretation is: I think of YouTube it has a comment-section, and inside the comment-section there are multiple articles (in this case comments).

So a section is like a div-container that holds articles.

Strip spaces/tabs/newlines - python

The above solutions suggesting the use of regex aren't ideal because this is such a small task and regex requires more resource overhead than the simplicity of the task justifies.

Here's what I do:

myString = myString.replace(' ', '').replace('\t', '').replace('\n', '')

or if you had a bunch of things to remove such that a single line solution would be gratuitously long:

removal_list = [' ', '\t', '\n']
for s in removal_list:
  myString = myString.replace(s, '')

Why can't I push to this bare repository?

Yes, the problem is that there are no commits in "bare". This is a problem with the first commit only, if you create the repos in the order (bare,alice). Try doing:

git push --set-upstream origin master

This would only be required the first time. Afterwards it should work normally.

As Chris Johnsen pointed out, you would not have this problem if your push.default was customized. I like upstream/tracking.

How do you check if a string is not equal to an object or other string value in java?

Change your || to && so it will only exit if the answer is NEITHER "AM" nor "PM".

Populate one dropdown based on selection in another

Could you please have a look at:

Basically, the data is stored in an Array and the options are added accordingly. I think the code says more than a thousand words.

var data = [ // The data
    ['ten', [
    ['twenty', [
        'twentyone', 'twentytwo'

$a = $('#a'); // The dropdowns
$b = $('#b');

for(var i = 0; i < data.length; i++) {
    var first = data[i][0];
    $a.append($("<option>"). // Add options
       data("sel", i).

$a.change(function() {
    var index = $(this).children('option:selected').data('sel');
    var second = data[index][1]; // The second-choice data

    $b.html(''); // Clear existing options in second dropdown

    for(var j = 0; j < second.length; j++) {
        $b.append($("<option>"). // Add options
           data("sel", j).
}).change(); // Trigger once to add options at load of first choice

Get type name without full namespace

make use of (Type Properties)

 Name   Gets the name of the current member. (Inherited from MemberInfo.)
 Example : typeof(T).Name;

Implementing autocomplete

PrimeNG has a native AutoComplete component with advanced features like templating and multiple selection.

How to get label text value form a html page?

var lbltext = document.getElementById('*spaM4').innerHTML

Leave only two decimal places after the dot

Alternatively, you may also use the composite operator F then indicating how many decimal spots you wish to appear after the decimal.

string.Format("{0:F2}", 123.456789);     //123.46
string.Format("{0:F3}", 123.456789);     //123.457
string.Format("{0:F4}", 123.456789);     //123.4568

It will round up so be aware of that.

I sourced the general documentation. There are a ton of other formatting operators there as well that you may check out.


Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"

Please check context root cannot be empty.

If you're using eclipse:
right click, select properties, then web project settings. Check the context root cannot be empty

How to Resize image in Swift?

It's also possible to use AlamofireImage (

let size = CGSize(width: 30.0, height: 30.0)
let aspectScaledToFitImage = image.af_imageAspectScaled(toFit: size)

The function in the previous post gave me a blurry result.

groovy.lang.MissingPropertyException: No such property: jenkins for class: groovy.lang.Binding

As pointed out by @Jayan in another post, the solution was to do the following

import jenkins.model.*
jenkins = Jenkins.instance

Then I was able to do the rest of my scripting the way it was.

matplotlib: how to draw a rectangle on image

You can add a Rectangle patch to the matplotlib Axes.

For example (using the image from the tutorial here):

import matplotlib.pyplot as plt
import matplotlib.patches as patches
from PIL import Image

im ='stinkbug.png')

# Create figure and axes
fig, ax = plt.subplots()

# Display the image

# Create a Rectangle patch
rect = patches.Rectangle((50, 100), 40, 30, linewidth=1, edgecolor='r', facecolor='none')

# Add the patch to the Axes

enter image description here

What is the difference between atomic / volatile / synchronized?

I know that two threads can not enter in Synchronize block at the same time

Two thread cannot enter a synchronized block on the same object twice. This means that two threads can enter the same block on different objects. This confusion can lead to code like this.

private Integer i = 0;

synchronized(i) {

This will not behave as expected as it could be locking on a different object each time.

if this is true than How this atomic.incrementAndGet() works without Synchronize ?? and is thread safe ??

yes. It doesn't use locking to achieve thread safety.

If you want to know how they work in more detail, you can read the code for them.

And what is difference between internal reading and writing to Volatile Variable / Atomic Variable ??

Atomic class uses volatile fields. There is no difference in the field. The difference is the operations performed. The Atomic classes use CompareAndSwap or CAS operations.

i read in some article that thread has local copy of variables what is that ??

I can only assume that it referring to the fact that each CPU has its own cached view of memory which can be different from every other CPU. To ensure that your CPU has a consistent view of data, you need to use thread safety techniques.

This is only an issue when memory is shared at least one thread updates it.

how to call an ASP.NET c# method using javascript

There are several options. You can use the WebMethod attribute, for your purpose.

How to stretch in width a WPF user control to its window?

Is the Canvas crucial in your window? If not, try removing it and keep the Grid as the main panel. Canvas has no size unless specified, while a Grid normally takes up all available space. Inside the Canvas, the Grid will have no available space.

How to Change color of Button in Android when Clicked?

Try this......

First create an xml file named button_pressed.xml These are it's contents.

<?xml version="1.0" encoding="utf-8"?>
    <item android:state_focused="true" 
          android:drawable="@drawable/icon_1" />
    <item android:state_focused="true" 
          android:drawable="@drawable/icon_1_press" />
    <item android:state_focused="false" 
            android:drawable="@drawable/icon_1_press" />
    <item android:drawable="@drawable/icon_1" />

Noe try this on your button.

int imgID = getResources().getIdentifier("button_pressed", "drawable", getApplication().getPackageName());

button_pressed.xml should be in the drawable folder. icon_1_press and icon_1 are two images for button press and normal focus.

Converting String to Int using try/except in Python

You can do :

try : 
   string_integer = int(string)
except ValueError  :
   print("This string doesn't contain an integer")

Locate current file in IntelliJ

And make it autoscrollable from source without hitting shortcuts every time How to make Scroll From Source feature always enabled?

Why SQL Server throws Arithmetic overflow error converting int to data type numeric?

Precision and scale are often misunderstood. In numeric(3,2) you want 3 digits overall, but 2 to the right of the decimal. If you want 15 => 15.00 so the leading 1 causes the overflow (since if you want 2 digits to the right of the decimal, there is only room on the left for one more digit). With 4,2 there is no problem because all 4 digits fit.

join on multiple columns

tableB.col1 = tableA.col1 
OR tableB.col2 = tableA.col1  
OR tableB.col1 = tableA.col2  
OR tableB.col1 = tableA.col2

Why is 2 * (i * i) faster than 2 * i * i in Java?

More of an addendum. I did repro the experiment using the latest Java 8 JVM from IBM:

java version "1.8.0_191"
Java(TM) 2 Runtime Environment, Standard Edition (IBM build 1.8.0_191-b12 26_Oct_2018_18_45 Mac OS X x64(SR5 FP25))
Java HotSpot(TM) 64-Bit Server VM (build 25.191-b12, mixed mode)

And this shows very similar results:

0.374653912 s
n = 119860736
0.447778698 s
n = 119860736

(second results using 2 * i * i).

Interestingly enough, when running on the same machine, but using Oracle Java:

Java version "1.8.0_181"
Java(TM) SE Runtime Environment (build 1.8.0_181-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.181-b13, mixed mode)

results are on average a bit slower:

0.414331815 s
n = 119860736
0.491430656 s
n = 119860736

Long story short: even the minor version number of HotSpot matter here, as subtle differences within the JIT implementation can have notable effects.

Openstreetmap: embedding map in webpage (like Google Maps)

Take a look at mapstraction. This can give you more flexibility to provide maps based on google, osm, yahoo, etc however your code won't have to change.

How to compare times in Python?

Inspired by Roger Pate:

import datetime
def todayAt (hr, min=0, sec=0, micros=0):
   now =
   return now.replace(hour=hr, minute=min, second=sec, microsecond=micros)    

# Usage demo1:
print todayAt (17), todayAt (17, 15)

# Usage demo2:    
timeNow =
if timeNow < todayAt (13):
   print "Too Early"

If statement within Where clause

CASE might help you out:

SELECT t.first_name,
  FROM employeetable t
 WHERE t.status = (CASE WHEN status_flag = STATUS_ACTIVE THEN 'A'
                        WHEN status_flag = STATUS_INACTIVE THEN 'T'
                        ELSE null END)
   AND t.business_unit = (CASE WHEN source_flag = SOURCE_FUNCTION THEN 'production'
                               WHEN source_flag = SOURCE_USER THEN 'users'
                               ELSE null END)
   AND t.first_name LIKE firstname
   AND t.last_name LIKE lastname
   AND t.employid LIKE employeeid;

The CASE statement evaluates multiple conditions to produce a single value. So, in the first usage, I check the value of status_flag, returning 'A', 'T' or null depending on what it's value is, and compare that to t.status. I do the same for the business_unit column with a second CASE statement.

Generate class from database table

In case it's useful to anyone else, working on a Code-First approach using attribute mappings, I wanted something that just left me needing to bind an entity in the object model. So thanks to Carnotaurus' answer, I extended it as per their own suggestion and made a couple of tweaks.

This relies therefore on this solution comprising TWO parts, both of which are SQL Scalar-Valued functions:

  1. An 'Initial Caps' function (taken from: and slightly modified to meet my needs)
ALTER function [dbo].[ProperCase] (@cStringToProper varchar(8000))
returns varchar(8000)
   declare  @Position int
    select @cStringToProper = stuff(lower(@cStringToProper) , 1 , 1 , upper(left(@cStringToProper , 1)))
        , @Position = patindex('%[^a-zA-Z][a-z]%' , @cStringToProper collate Latin1_General_Bin)

   while @Position > 0
         select @cStringToProper = stuff(@cStringToProper , @Position , 2 , upper(substring(@cStringToProper , @Position , 2)))
              , @Position = patindex('%[^a-zA-Z][a-z]%' , @cStringToProper collate Latin1_General_Bin)

  select @cStringToProper = replace(@cStringToProper, '_','')

   return @cStringToProper
  1. The output function itself, which extends Carnotaurus' solution by:

    • Correctly outputting newline characters
    • Performing some basic tabulation
    • Writing out an appropriate a [Table] mapping (as suggested)
    • Writing out an appropriate [Column] mapping, including the type name (as suggested)
    • Allowing the Entity name to differ from the name of the table
    • Fixes the limitation of the Print @Result truncating when you have tables with a large number of columns


SET @result = @result + 'using System;' + CHAR(13) + CHAR(13) 

    SET @result = @result + 'namespace ' + @NameSpace  + CHAR(13) + '{' + CHAR(13)  END

SET @result = @result + '[Table(name: ' + CHAR(34) + @TableName + CHAR(34) + ')]' + CHAR(13) SET @result = @result + 'public class ' + @EntityName + CHAR(13) + '{' + CHAR(13) 

SET @result = @result + '#region Instance Properties' + CHAR(13)  

SELECT @result = @result + CHAR(13)     + '[Column(name: ' + CHAR(34) + OriginalColumnName + CHAR(34) + ', TypeName = ' + CHAR(34) + DataType
+ CHAR(34) + ')]' + CHAR(13)
    + 'public ' + ColumnType + ' ' + ColumnName + ' { get; set; } ' + CHAR(13)  FROM (
    SELECT dbo.ProperCase (c.COLUMN_NAME)   AS ColumnName 
        , CASE c.DATA_TYPE   
            WHEN 'bigint' THEN
                CASE C.IS_NULLABLE
                    WHEN 'YES' THEN 'Int64?' ELSE 'Int64' END
            WHEN 'binary' THEN 'Byte[]'
            WHEN 'bit' THEN 
                CASE C.IS_NULLABLE
                    WHEN 'YES' THEN 'Boolean?' ELSE 'Boolean' END            
            WHEN 'char' THEN 'String'
            WHEN 'date' THEN
                CASE C.IS_NULLABLE
                    WHEN 'YES' THEN 'DateTime?' ELSE 'DateTime' END                        
            WHEN 'datetime' THEN
                CASE C.IS_NULLABLE
                    WHEN 'YES' THEN 'DateTime?' ELSE 'DateTime' END                        
            WHEN 'datetime2' THEN  
                CASE C.IS_NULLABLE
                    WHEN 'YES' THEN 'DateTime?' ELSE 'DateTime' END                        
            WHEN 'datetimeoffset' THEN 
                CASE C.IS_NULLABLE
                    WHEN 'YES' THEN 'DateTimeOffset?' ELSE 'DateTimeOffset' END                                    
            WHEN 'decimal' THEN  
                CASE C.IS_NULLABLE
                    WHEN 'YES' THEN 'Decimal?' ELSE 'Decimal' END                                    
            WHEN 'float' THEN 
                CASE C.IS_NULLABLE
                    WHEN 'YES' THEN 'Single?' ELSE 'Single' END                                    
            WHEN 'image' THEN 'Byte[]'
            WHEN 'int' THEN  
                CASE C.IS_NULLABLE
                    WHEN 'YES' THEN 'Int32?' ELSE 'Int32' END
            WHEN 'money' THEN
                CASE C.IS_NULLABLE
                    WHEN 'YES' THEN 'Decimal?' ELSE 'Decimal' END                                                
            WHEN 'nchar' THEN 'String'
            WHEN 'ntext' THEN 'String'
            WHEN 'numeric' THEN
                CASE C.IS_NULLABLE
                    WHEN 'YES' THEN 'Decimal?' ELSE 'Decimal' END                                                            
            WHEN 'nvarchar' THEN 'String'
            WHEN 'real' THEN 
                CASE C.IS_NULLABLE
                    WHEN 'YES' THEN 'Double?' ELSE 'Double' END                                                                        
            WHEN 'smalldatetime' THEN 
                CASE C.IS_NULLABLE
                    WHEN 'YES' THEN 'DateTime?' ELSE 'DateTime' END                                    
            WHEN 'smallint' THEN 
                CASE C.IS_NULLABLE
                    WHEN 'YES' THEN 'Int16?' ELSE 'Int16'END            
            WHEN 'smallmoney' THEN  
                CASE C.IS_NULLABLE
                    WHEN 'YES' THEN 'Decimal?' ELSE 'Decimal' END                                                                        
            WHEN 'text' THEN 'String'
            WHEN 'time' THEN 
                CASE C.IS_NULLABLE
                    WHEN 'YES' THEN 'TimeSpan?' ELSE 'TimeSpan' END                                         
            WHEN 'timestamp' THEN 
                CASE C.IS_NULLABLE
                    WHEN 'YES' THEN 'DateTime?' ELSE 'DateTime' END                                    
            WHEN 'tinyint' THEN 
                CASE C.IS_NULLABLE
                    WHEN 'YES' THEN 'Byte?' ELSE 'Byte' END                                                
            WHEN 'uniqueidentifier' THEN 'Guid'
            WHEN 'varbinary' THEN 'Byte[]'
            WHEN 'varchar' THEN 'String'
            ELSE 'Object'
        END AS ColumnType
        , c.ORDINAL_POSITION        , c.COLUMN_NAME as OriginalColumnName       ,c.DATA_TYPE as DataType


SET @result = @result + CHAR(13) + '#endregion Instance Properties' + CHAR(13)  

SET @result = @result  + '}' + CHAR(13)

    SET @result = @result + CHAR(13) + '}'  END

return @result END

Usage from within MS SQL Management Studio:

SELECT dbo.GetEntityObject('MyNameSpace', 'MyTableName', 'MyEntityName')

will result in a column value you can copy and paste into Visual Studio.

If it helps anyone, then great!

How to convert any date format to yyyy-MM-dd

This is your primary problem:

The source date could be anything like dd-mm-yyyy, dd/mm/yyyy, mm-dd-yyyy, mm/dd/yyyy or even yyyy-MM-dd.

If you're given 01/02/2013, is it Jan 2 or Feb 1? You should solve this problem first and parsing the input will be much easier.

I suggest you take a step back and explore what you are trying to solve in more detail.

Counting the number of elements in array

Just use the length filter on the whole array. It works on more than just strings:

{{ notcount|length }}

Can you install and run apps built on the .NET framework on a Mac?

.NetCore is a fine release from Microsoft and Visual Studio's latest version is also available for mac but there is still some limitation. Like for creating GUI based application on .net core you have to write code manually for everything. Like in older version of VS we just drag and drop the things and magic happens. But in VS latest version for mac every code has to be written manually. However you can make web application and console application easily on VS for mac.

How to save the contents of a div as a image?

Do something like this:

A <div> with ID of #imageDIV, another one with ID #download and a hidden <div> with ID #previewImage.

Include the latest version of jquery, and jspdf.debug.js from the jspdf CDN

Then add this script:

var element = $("#imageDIV"); // global variable
var getCanvas; // global variable
  html2canvas(element, {
    onrendered: function (canvas) {
      getCanvas = canvas;
$("#download").on('click', function () {
  var imgageData = getCanvas.toDataURL("image/png");
  // Now browser starts downloading it instead of just showing it
  var newData = imageData.replace(/^data:image\/png/, "data:application/octet-stream");
  $("#download").attr("download", "image.png").attr("href", newData);

The div will be saved as a PNG on clicking the #download

How do I kill a VMware virtual machine that won't die?

Here's what I did based on

a) @Espo 's comments and
b) the fact that I only had Windows Task Manager to play with....

I logged onto the host machine, opened Task Manager and used the view menu to add the PID column to the Processes tab.

I wrote down (yes, with paper and a pen) the PID's for each and every instance of the vmware-wmx.exe process that was running on the box.

Using the VMWare console, I suspended the errant virtual machine.

When I resumed it, I could then identify the vmware-vmx process that corresponded to my machine and could kill it.

There doesn't seem to have been any ill effects so far.

Detect If Browser Tab Has Focus

While searching about this problem, I found a recommendation that Page Visibility API should be used. Most modern browsers support this API according to Can I Use:

Here's a working example (derived from this snippet):

$(document).ready(function() {
  var hidden, visibilityState, visibilityChange;

  if (typeof document.hidden !== "undefined") {
    hidden = "hidden", visibilityChange = "visibilitychange", visibilityState = "visibilityState";
  } else if (typeof document.msHidden !== "undefined") {
    hidden = "msHidden", visibilityChange = "msvisibilitychange", visibilityState = "msVisibilityState";

  var document_hidden = document[hidden];

  document.addEventListener(visibilityChange, function() {
    if(document_hidden != document[hidden]) {
      if(document[hidden]) {
        // Document hidden
      } else {
        // Document shown

      document_hidden = document[hidden];

Update: The example above used to have prefixed properties for Gecko and WebKit browsers, but I removed that implementation because these browsers have been offering Page Visibility API without a prefix for a while now. I kept Microsoft specific prefix in order to stay compatible with IE10.

SQL SELECT everything after a certain character

select SUBSTRING_INDEX(supplier_reference,'=',-1) from ps_product;

Please use for further reference.

`node-pre-gyp install --fallback-to-build` failed during MeanJS installation on OSX

i also face same problem.i found solution for that.

bcrypt required C++, python and node-pre-gyp.

sudo apt-get install g++
sudo apt-get install -y build-essential python
npm install node-pre-gyp

for more details check :

What is console.log in jQuery?

jQuery and console.log are unrelated entities, although useful when used together.

If you use a browser's built-in dev tools, console.log will log information about the object being passed to the log function.

If the console is not active, logging will not work, and may break your script. Be certain to check that the console exists before logging:

if (window.console) console.log('foo');

The shortcut form of this might be seen instead:


There are other useful debugging functions as well, such as debug, dir and error. Firebug's wiki lists the available functions in the console api.

Is there an SQLite equivalent to MySQL's DESCRIBE [table]?

Are you looking for the SQL used to generate a table? For that, you can query the sqlite_master table:

sqlite> CREATE TABLE foo (bar INT, quux TEXT);
sqlite> SELECT * FROM sqlite_master;
table|foo|foo|2|CREATE TABLE foo (bar INT, quux TEXT)
sqlite> SELECT sql FROM sqlite_master WHERE name = 'foo';
CREATE TABLE foo (bar INT, quux TEXT)

Java: Converting String to and from ByteBuffer and associated problems

Unless things have changed, you're better off with

public static ByteBuffer str_to_bb(String msg, Charset charset){
    return ByteBuffer.wrap(msg.getBytes(charset));

public static String bb_to_str(ByteBuffer buffer, Charset charset){
    byte[] bytes;
    if(buffer.hasArray()) {
        bytes = buffer.array();
    } else {
        bytes = new byte[buffer.remaining()];
    return new String(bytes, charset);

Usually buffer.hasArray() will be either always true or always false depending on your use case. In practice, unless you really want it to work under any circumstances, it's safe to optimize away the branch you don't need.

C# equivalent of the IsNull() function in SQL Server

You Write Two Function

    //When Expression is Number
    public static double? isNull(double? Expression, double? Value)
        if (Expression ==null)
            return Value;
            return Expression;

    //When Expression is string (Can not send Null value in string Expression
    public static string isEmpty(string Expression, string Value)
        if (Expression == "")
            return Value;
            return Expression;

They Work Very Well

Rebuild Docker container on file changes

Whenever changes are made in dockerfile or compose or requirements , re-Run it using docker-compose up --build . So that images get rebuild and refreshed

Difference between a theta join, equijoin and natural join

@outis's answer is good: concise and correct as regards relations.

However, the situation is slightly more complicated as regards SQL.

Consider the usual suppliers and parts database but implemented in SQL:


would return a resultset** with columns


The join is performed on the column with the same name in both tables, SNO. Note that the resultset has six columns and only contains one column for SNO.

Now consider a theta eqijoin, where the column names for the join must be explicitly specified (plus range variables S and SP are required):


The resultset will have seven columns, including two columns for SNO. The names of the resultset are what the SQL Standard refers to as "implementation dependent" but could look like this:


or perhaps this


In other words, NATURAL JOIN in SQL can be considered to remove columns with duplicated names from the resultset (but alas will not remove duplicate rows - you must remember to change SELECT to SELECT DISTINCT yourself).

** I don't quite know what the result of SELECT * FROM table_expression; is. I know it is not a relation because, among other reasons, it can have columns with duplicate names or a column with no name. I know it is not a set because, among other reasons, the column order is significant. It's not even a SQL table or SQL table expression. I call it a resultset.

Why does the 'int' object is not callable error occur when using the sum() function?

In the interpreter its easy to restart it and fix such problems. If you don't want to restart the interpreter, there is another way to fix it:

Python 2.6.6 (r266:84292, Dec 27 2010, 00:02:40)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> l = [1,2,3]
>>> sum(l)
>>> sum = 0 # oops! shadowed a builtin!
>>> sum(l)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
>>> import sys
>>> sum = sys.modules['__builtin__'].sum # -- fixing sum
>>> sum(l)

This also comes in handy if you happened to assign a value to any other builtin, like dict or list

Short IF - ELSE statement

I'm a little late to the party but for future readers.

From what i can tell, you're just wanting to toggle the visibility state right? Why not just use the ! operator?


It's not an if statement but I prefer this method for code related to your example.

More Pythonic Way to Run a Process X Times

The for loop is definitely more pythonic, as it uses Python's higher level built in functionality to convey what you're doing both more clearly and concisely. The overhead of range vs xrange, and assigning an unused i variable, stem from the absence of a statement like Verilog's repeat statement. The main reason to stick to the for range solution is that other ways are more complex. For instance:

from itertools import repeat

for unused in repeat(None, 10):
    del unused   # redundant and inefficient, the name is clear enough
    print "This is run 10 times"

Using repeat instead of range here is less clear because it's not as well known a function, and more complex because you need to import it. The main style guides if you need a reference are PEP 20 - The Zen of Python and PEP 8 - Style Guide for Python Code.

We also note that the for range version is an explicit example used in both the language reference and tutorial, although in that case the value is used. It does mean the form is bound to be more familiar than the while expansion of a C-style for loop.

Copying formula to the next row when inserting a new row

One other key thing that I found regarding copying rows within a table, is that the worksheet you are working on needs to be activated. If you have a workbook with multiple sheets, you need to save the sheet you called the macro from, and then activate the sheet with the table. Once you are done, you can re-activate the original sheet.

You can use Application.ScreenUpdating = False to make sure the user doesn't see that you are switching worksheets within your macro.

If you don't have the worksheet activated, the copy doesn't seem to work properly, i.e. some stuff seem to work, and other stuff doesn't ??

Android error: Failed to install *.apk on device *: timeout

don't use USB 3.0 ports for connection beetwen PC and Android phone!

USB 3.0 - Port with blue tongue

USB 2.0 - Port with black tongue

JavaScript: set dropdown selected item based on option text

A modern alternative:

const textToFind = 'Google';
const dd = document.getElementById ('MyDropDown');
dd.selectedIndex = [...dd.options].findIndex (option => option.text === textToFind);

What are .a and .so files?

Wikipedia is a decent source for this info.

To learn about static library files like .a read Static libarary

To learn about shared library files like .so read Library_(computing)#Shared_libraries On this page, there is also useful info in the File naming section.

Sql script to find invalid email addresses

I find this simple T-SQL query useful for returning valid e-mail addresses

SELECT email
FROM People
WHERE email LIKE '%_@__%.__%' 
    AND PATINDEX('%[^a-z,0-9,@,.,_]%', REPLACE(email, '-', 'a')) = 0

The PATINDEX bit eliminates all e-mail addresses containing characters that are not in the allowed a-z, 0-9, '@', '.', '_' & '-' set of characters.

It can be reversed to do what you want like this:

SELECT email
FROM People
WHERE NOT (email LIKE '%_@__%.__%' 
    AND PATINDEX('%[^a-z,0-9,@,.,_]%', REPLACE(email, '-', 'a')) = 0)

pointer to array c++

j[0]; dereferences a pointer to int, so its type is int.

(*j)[0] has no type. *j dereferences a pointer to an int, so it returns an int, and (*j)[0] attempts to dereference an int. It's like attempting int x = 8; x[0];.

Boto3 to download all files from a S3 Bucket

import boto3, os

s3 = boto3.client('s3')

def download_bucket(bucket):
    paginator = s3.get_paginator('list_objects_v2')
    pages = paginator.paginate(Bucket=bucket)
    for page in pages:
      if 'Contents' in page:
        for obj in page['Contents']:
            os.path.dirname(obj['Key']) and os.makedirs(os.path.dirname(obj['Key']), exist_ok=True) 
                s3.download_file(bucket, obj['Key'], obj['Key'])
            except NotADirectoryError:

# Change bucket_name to name of bucket that you want to download

This should work for all number of objects (also when there are more than 1000). Each paginator page can contain up to 1000 objects.Notice extra param in os.makedirs function - exist_ok=True which cause that it's not throwing error when path exist)

count number of rows in a data frame in R based on group

The count() function in plyr does what you want:


count(mydf, "MONTH-YEAR")

Replace negative values in an numpy array

Try numpy.clip:

>>> import numpy
>>> a = numpy.arange(-10, 10)
>>> a
array([-10,  -9,  -8,  -7,  -6,  -5,  -4,  -3,  -2,  -1,   0,   1,   2,
         3,   4,   5,   6,   7,   8,   9])
>>> a.clip(0, 10)
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

You can clip only the bottom half with clip(0).

>>> a = numpy.array([1, 2, 3, -4, 5])
>>> a.clip(0)
array([1, 2, 3, 0, 5])

You can clip only the top half with clip(max=n). (This is much better than my previous suggestion, which involved passing NaN to the first parameter and using out to coerce the type.):

>>> a.clip(max=2)
array([ 1,  2,  2, -4,  2])

Another interesting approach is to use where:

>>> numpy.where(a <= 2, a, 2)
array([ 1,  2,  2, -4,  2])

Finally, consider aix's answer. I prefer clip for simple operations because it's self-documenting, but his answer is preferable for more complex operations.

How does one get started with procedural generation?

Procedural generation is used heavily in the demoscene to create complex graphics in a small executable. Will Wright even said that he was inspired by the demoscene while making Spore. That may be your best place to start.

Clearing a string buffer/builder after loop

buf.delete(0,  buf.length());

CSS horizontal centering of a fixed div?

Edit September 2016: Although it's nice to still get an occasional up-vote for this, because the world has moved on, I'd now go with the answer that uses transform (and which has a ton of upvotes). I wouldn't do it this way any more.

Another way not to have to calculate a margin or need a sub-container:

#menu {
    position: fixed;   /* Take it out of the flow of the document */
    left: 0;           /* Left edge at left for now */
    right: 0;          /* Right edge at right for now, so full width */ 
    top: 30px;         /* Move it down from top of window */
    width: 500px;      /* Give it the desired width */ 
    margin: auto;      /* Center it */
    max-width: 100%;   /* Make it fit window if under 500px */ 
    z-index: 10000;    /* Whatever needed to force to front (1 might do) */

How to copy files across computers using SSH and MAC OS X Terminal

You can do this with the scp command, which uses the ssh protocol to copy files across machines. It extends the syntax of cp to allow references to other systems:

scp username1@hostname1:/path/to/file username2@hostname2:/path/to/other/file

Copy something from this machine to some other machine:

scp /path/to/local/file username@hostname:/path/to/remote/file

Copy something from another machine to this machine:

scp username@hostname:/path/to/remote/file /path/to/local/file

Copy with a port number specified:

scp -P 1234 username@hostname:/path/to/remote/file /path/to/local/file

Sum all values in every column of a data.frame in R

We can use dplyr to select only numeric columns and purr to get sum for all columns. (can be used to get what ever value for all columns, such as mean, min, max, etc. )


people %>%
    select_if(is.numeric) %>%

Or another easy way by only using dplyr

people %>%
    summarize_if(is.numeric, sum, na.rm=TRUE)

Convert JsonObject to String

     This should get all the values from the above JsonObject  

     JsonObject obj= jsonObj.get("data").getAsJsonObject().get("map").getAsJsonObject();

Expanding a parent <div> to the height of its children

<div id="parent">_x000D_
    <div id="childRightCol">_x000D_
          Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque vulputate sit amet neque ac consequat._x000D_

you are manage by using overflow:hidden; property in css

How to check if a textbox is empty using javascript

<pre><form name="myform"  method="post" enctype="multipart/form-data">
    <input type="text"   id="name"   name="name" /> 
<input type="submit"/>

<script language="JavaScript" type="text/javascript">
 var frmvalidator  = new Validator("myform");
    frmvalidator.addValidation("name","req","Plese Enter Name"); 


Note: before using the code above you have to add the gen_validatorv31.js file.

How to use bluetooth to connect two iPhone?

You can connect two iPhones and transfer data via Bluetooth using either the high-level GameKit framework or the lower-level (but still easy to work with) Bonjour discovery mechanisms. Bonjour also works transparently between Bluetooth and WiFi on the iPhone under 3.0, so it's a good choice if you would like to support iPhone-to-iPhone data transfers on those two types of networks.

For more information, you can also look at the responses to these questions:

How to convert JSON to a Ruby hash

Assuming you have a JSON hash hanging around somewhere, to automatically convert it into something like WarHog's version, wrap your JSON hash contents in %q{hsh} tags.

This seems to automatically add all the necessary escaped text like in WarHog's answer.