Programs & Examples On #Svn server

Detecting request type in PHP (GET, POST, PUT or DELETE)

It is valuable to additionally note, that PHP will populate all the $_GET parameters even when you send a proper request of other type.

Methods in above replies are completely correct, however if you want to additionaly check for GET parameters while handling POST, DELETE, PUT, etc. request, you need to check the size of $_GET array.

Mask output of `The following objects are masked from....:` after calling attach() function

You use attach without detach - every time you do it new call to attach masks objects attached before (they contain the same names). Either use detach or do not use attach at all. Nice discussion and tips are here.

BAT file to open CMD in current directory

A bit late to the game but if I'm understanding your needs correctly this will help people with the same issue.

Two solutions with the same first step: First navigate to the location you keep your scripts in and copy the filepath to that directory.

First Solution:

  • Click "Start"
  • Right-click "Computer" (or "My Computer)
  • Click "Properties"
  • On the left, click "Advanced System Settings"
  • Click "Environment Variables"
  • In the "System Variables" Box, scroll down and select "PATH"
  • Click "Edit"
  • In the "Variable Value" field, scroll all the way to the right
  • If there isn't a semi-colon (;) there yet, add it.
  • Paste in the filepath you copied earlier.
  • End with a semi-colon.
  • Click "OK"
  • Click "OK" again
  • Click "OK" one last time

You can now use any of your scripts as if you were already that folder.

Second Solution: (can easily be paired with the first for extra usefulness)

On your desktop create a batch file with the following content.

@echo off
cmd /k cd "C:\your\file\path"

This will open a command window like what you tried to do.

For tons of info on windows commands check here:

Converting String array to java.util.List

List<String> strings = Arrays.asList(new String[]{"one", "two", "three"});

This is a list view of the array, the list is partly unmodifiable, you can't add or delete elements. But the time complexity is O(1).

If you want a modifiable a List:

List<String> strings = 
     new ArrayList<String>(Arrays.asList(new String[]{"one", "two", "three"}));

This will copy all elements from the source array into a new list (complexity: O(n))

'setInterval' vs 'setTimeout'

setTimeout(expression, timeout); runs the code/function once after the timeout.

setInterval(expression, timeout); runs the code/function in intervals, with the length of the timeout between them.


var intervalID = setInterval(alert, 1000); // Will alert every second.
// clearInterval(intervalID); // Will clear the timer.

setTimeout(alert, 1000); // Will alert once, after a second.

convert string to number node.js

Using parseInt() is a bad idea mainly because it never fails. Also because some results can be unexpected, like in the case of INFINITY.
Below is the function for handling unexpected behaviour.

function cleanInt(x) {
    x = Number(x);
    return x >= 0 ? Math.floor(x) : Math.ceil(x);

See results of below test cases.

console.log("CleanInt: ", cleanInt('xyz'), " ParseInt: ", parseInt('xyz'));
console.log("CleanInt: ", cleanInt('123abc'), " ParseInt: ", parseInt('123abc'));
console.log("CleanInt: ", cleanInt('234'), " ParseInt: ", parseInt('234'));
console.log("CleanInt: ", cleanInt('-679'), " ParseInt: ", parseInt('-679'));
console.log("CleanInt: ", cleanInt('897.0998'), " ParseInt: ", parseInt('897.0998'));
console.log("CleanInt: ", cleanInt('Infinity'), " ParseInt: ", parseInt('Infinity'));


CleanInt:  NaN  ParseInt:  NaN
CleanInt:  NaN  ParseInt:  123
CleanInt:  234  ParseInt:  234
CleanInt:  -679  ParseInt:  -679
CleanInt:  897  ParseInt:  897
CleanInt:  Infinity  ParseInt:  NaN

How do I get the Git commit count?

You are not the first one to think about a "revision number" in Git, but 'wc' is quite dangerous, since commit can be erased or squashed, and the history revisited.

The "revision number" was especially important for Subversion since it was needed in case of merge (SVN1.5 and 1.6 have improved on that front).

You could end up with a pre-commit hook which would include a revision number in the comment, with an algorithm not involving looking up the all history of a branch to determine the correct number.

Bazaar actually came up with such an algorithm , and it may be a good starting point for what you want to do.

(As Bombe's answer points out, Git has actually an algorithm of its own, based on the latest tag, plus the number of commits, plus a bit of an SHA-1 key). You should see (and upvote) his answer if it works for you.

To illustrate Aaron's idea, you can also append the Git commit hash into an application’s "info" file you are distributing with your application.

That way, the about box would look like:

About box

The applicative number is part of the commit, but the 'application’s "info" file' is generated during the packaging process, effectively linking an applicative build number to a technical revision id.

Yes/No message box using QMessageBox

If you want to make it in python you need check this code in your workbench. also write like this. we created a popup box with python.

msgBox = QMessageBox()
msgBox.setText("The document has been modified.")
msgBox.setInformativeText("Do you want to save your changes?")
msgBox.setStandardButtons(QMessageBox.Save | QMessageBox.Discard | QMessageBox.Cancel)
ret = msgBox.exec_()

Run parallel multiple commands at once in the same terminal

This bash script is for N parallel threads. Each argument is a command.

trap will kill all subprocesses when SIGINT is catched.
wait $PID_LIST is waiting each process to complete. When all processes have completed, the program exits.


for cmd in "$@"; do {
  echo "Process \"$cmd\" started";
  $cmd & pid=$!
  PID_LIST+=" $pid";
} done

trap "kill $PID_LIST" SIGINT

echo "Parallel processes have started";

wait $PID_LIST

echo "All processes have completed";

Save this script as parallel_commands and make it executable.
This is how to use this script:

parallel_commands "cmd arg0 arg1 arg2" "other_cmd arg0 arg2 arg3"


parallel_commands "sleep 1" "sleep 2" "sleep 3" "sleep 4"

Start 4 parallel sleep and waits until "sleep 4" finishes.

How to count the number of true elements in a NumPy bool array

In terms of comparing two numpy arrays and counting the number of matches (e.g. correct class prediction in machine learning), I found the below example for two dimensions useful:

import numpy as np
result = np.random.randint(3,size=(5,2)) # 5x2 random integer array
target = np.random.randint(3,size=(5,2)) # 5x2 random integer array

res = np.equal(result,target)
print result
print target
print np.sum(res[:,0])
print np.sum(res[:,1])

which can be extended to D dimensions.

The results are:


[[1 2]
 [2 0]
 [2 0]
 [1 2]
 [1 2]]


[[0 1]
 [1 0]
 [2 0]
 [0 0]
 [2 1]]

Count of correct prediction for D=1: 1

Count of correct prediction for D=2: 2

regular expression for DOT

Use String.Replace() if you just want to replace the dots from string. Alternative would be to use Pattern-Matcher with StringBuilder, this gives you more flexibility as you can find groups that are between dots. If using the latter, i would recommend that you ignore empty entries with "\\.+".

public static int count(String str, String regex) {
    int i = 0;
    Pattern p = Pattern.compile(regex);
    Matcher m = p.matcher(str);
    while (m.find()) {;
    return i;

public static void main(String[] args) {
    int i = 0, j = 0, k = 0;
    String str = "-.-..-...-.-.--..-k....k...k..k.k-.-";

    // this will just remove dots
    System.out.println(str.replaceAll("\\.", ""));
    // this will just remove sequences of ".." dots
    System.out.println(str.replaceAll("\\.{2}", ""));
    // this will just remove sequences of dots, and gets
    // multiple of dots as 1
    System.out.println(str.replaceAll("\\.+", ""));

    /* for this to be more obvious, consider following */
    System.out.println(count(str, "\\."));
    System.out.println(count(str, "\\.{2}"));
    System.out.println(count(str, "\\.+"));

The output will be:


Why doesn't document.addEventListener('load', function) work in a greasemonkey script?

Apparently, document.addEventListener() is unreliable, and hence, my error. Use window.addEventListener() with the same parameters, instead.

Discard all and get clean copy of latest revision?

If you're looking for a method that's easy, then you might want to try this.

I for myself can hardly remember commandlines for all of my tools, so I tend to do it using the UI:

1. First, select "commit"


2. Then, display ignored files. If you have uncommitted changes, hide them.

Show ignored files

3. Now, select all of them and click "Delete Unversioned".

Delete them

Done. It's a procedure that is far easier to remember than commandline stuff.

Change drive in git bash for windows

In order to navigate to a different drive/directory you can do it in convenient way (instead of typing cd /e/Study/Codes), just type in cd[Space], and drag-and-drop your directory Codes with your mouse to git bash, hit [Enter].

Remove the last character from a string

An alternative to substr is the following, as a function:

substr_replace($string, "", -1)

Is it the fastest? I don't know, but I'm willing to bet these alternatives are all so fast that it just doesn't matter.

Bootstrap: Use .pull-right without having to hardcode a negative margin-top

Keep the h2 at the top, then pull-left on the p and pull-right on the login-box

<div class='container'>
  <div class='hero-unit'>


    <div class="pull-left">
      <p>Please log in</p>

    <div id='login-box' class='pull-right control-group'>
        <div class='clearfix'>
            <input type='text' placeholder='Username' />
        <div class='clearfix'>
            <input type='password' placeholder='Password' />
        <button type='button' class='btn btn-primary'>Log in</button>

    <div class="clearfix"></div>


the default vertical-align on floated boxes is baseline, so the "Please log in" exactly lines up with the "Username" (check by changing the pull-right to pull-left).

Number to String in a formula field

i wrote a simple function for this:

Function (stringVar param)
    Local stringVar oneChar := '0';
    Local numberVar strLen := Length(param);
    Local numberVar index := strLen;

    oneChar = param[strLen];

    while index > 0 and oneChar = '0' do
        oneChar := param[index];
        index := index - 1;

    Left(param , index + 1);

Create Directory if it doesn't exist with Ruby

Simple way:

directory_name = "name"
Dir.mkdir(directory_name) unless File.exists?(directory_name)

COLLATION 'utf8_general_ci' is not valid for CHARACTER SET 'latin1'

In my case I created a database and gave the collation 'utf8_general_ci' but the required collation was 'latin1'. After changing my collation type to latin1_bin the error was gone.

How can I keep my branch up to date with master with git?

You can use the cherry-pick to get the particular bug fix commit(s)

$ git checkout branch
$ git cherry-pick bugfix

What are major differences between C# and Java?

Comparing Java 7 and C# 3

(Some features of Java 7 aren't mentioned here, but the using statement advantage of all versions of C# over Java 1-6 has been removed.)

Not all of your summary is correct:

  • In Java methods are virtual by default but you can make them final. (In C# they're sealed by default, but you can make them virtual.)
  • There are plenty of IDEs for Java, both free (e.g. Eclipse, Netbeans) and commercial (e.g. IntelliJ IDEA)

Beyond that (and what's in your summary already):

  • Generics are completely different between the two; Java generics are just a compile-time "trick" (but a useful one at that). In C# and .NET generics are maintained at execution time too, and work for value types as well as reference types, keeping the appropriate efficiency (e.g. a List<byte> as a byte[] backing it, rather than an array of boxed bytes.)
  • C# doesn't have checked exceptions
  • Java doesn't allow the creation of user-defined value types
  • Java doesn't have operator and conversion overloading
  • Java doesn't have iterator blocks for simple implemetation of iterators
  • Java doesn't have anything like LINQ
  • Partly due to not having delegates, Java doesn't have anything quite like anonymous methods and lambda expressions. Anonymous inner classes usually fill these roles, but clunkily.
  • Java doesn't have expression trees
  • C# doesn't have anonymous inner classes
  • C# doesn't have Java's inner classes at all, in fact - all nested classes in C# are like Java's static nested classes
  • Java doesn't have static classes (which don't have any instance constructors, and can't be used for variables, parameters etc)
  • Java doesn't have any equivalent to the C# 3.0 anonymous types
  • Java doesn't have implicitly typed local variables
  • Java doesn't have extension methods
  • Java doesn't have object and collection initializer expressions
  • The access modifiers are somewhat different - in Java there's (currently) no direct equivalent of an assembly, so no idea of "internal" visibility; in C# there's no equivalent to the "default" visibility in Java which takes account of namespace (and inheritance)
  • The order of initialization in Java and C# is subtly different (C# executes variable initializers before the chained call to the base type's constructor)
  • Java doesn't have properties as part of the language; they're a convention of get/set/is methods
  • Java doesn't have the equivalent of "unsafe" code
  • Interop is easier in C# (and .NET in general) than Java's JNI
  • Java and C# have somewhat different ideas of enums. Java's are much more object-oriented.
  • Java has no preprocessor directives (#define, #if etc in C#).
  • Java has no equivalent of C#'s ref and out for passing parameters by reference
  • Java has no equivalent of partial types
  • C# interfaces cannot declare fields
  • Java has no unsigned integer types
  • Java has no language support for a decimal type. (java.math.BigDecimal provides something like System.Decimal - with differences - but there's no language support)
  • Java has no equivalent of nullable value types
  • Boxing in Java uses predefined (but "normal") reference types with particular operations on them. Boxing in C# and .NET is a more transparent affair, with a reference type being created for boxing by the CLR for any value type.

This is not exhaustive, but it covers everything I can think of off-hand.

How to run a single RSpec test?

For single example of spec file you need to add line number at the last , For Example

rspec spec/controllers/api/v1/card_list_controller_spec.rb:35

For single file you can specify your file path, For Example

rspec spec/controllers/api/v1/card_list_controller_spec.rb

For Whole Rspec Example in spec folder, you can try with this command

bundle exec rspec spec

Loop through an array php

Ok, I know there is an accepted answer but… for more special cases you also could use this one:

array_map(function($n) { echo $n['filename']; echo $n['filepath'];},$array);

Or in a more un-complex way:

function printItem($n){
    echo $n['filename'];
    echo $n['filepath'];

array_map('printItem', $array);

This will allow you to manipulate the data in an easier way.

Get root view from current activity

Get root view from current activity.

Inside our activity we can get the root view with:

ViewGroup rootView = (ViewGroup) ((ViewGroup) this


View rootView = getWindow().getDecorView().getRootView();

jQuery: How to capture the TAB keypress within a Textbox

This worked for me:

$("[id*=txtName]").on('keydown', function(e) { var keyCode = e.keyCode || e.which; if (keyCode == 9) { e.preventDefault(); alert('Tab Pressed'); } });

How can I record a Video in my Android App.?

Check out this Sample Camera Preview code, CameraPreview. This would help you in devloping video recording code for video preview, create MediaRecorder object, and set video recording parameters.

How to execute a stored procedure within C# program

using (SqlConnection sqlConnection1 = new SqlConnection("Your Connection String")) {
using (SqlCommand cmd = new SqlCommand()) {
  Int32 rowsAffected;

  cmd.CommandText = "StoredProcedureName";
  cmd.CommandType = CommandType.StoredProcedure;
  cmd.Connection = sqlConnection1;


  rowsAffected = cmd.ExecuteNonQuery();


Hibernate dialect for Oracle Database 11g?

According to supported databases, Oracle 11g is not officially supported. Although, I believe you shouldn't have any problems using org.hibernate.dialect.OracleDialect.

Incorrect syntax near ''

I got this error because I pasted alias columns into a DECLARE statement.

DECLARE @userdata TABLE(
f.TABLE_CATALOG nvarchar(100),
f.TABLE_NAME nvarchar(100),
f.COLUMN_NAME nvarchar(100),
p.COLUMN_NAME nvarchar(100)
SELECT * FROM @userdata 

ERROR: Msg 102, Level 15, State 1, Line 2 Incorrect syntax near '.'.

DECLARE @userdata TABLE(
f_TABLE_CATALOG nvarchar(100),
f_TABLE_NAME nvarchar(100),
f_COLUMN_NAME nvarchar(100),
p_COLUMN_NAME nvarchar(100)
SELECT * FROM @userdata


Can't push image to Amazon ECR - fails with "no basic auth credentials"

That error message is coming from docker and it not necessarily related to AWS as I have gotten same error when not using AWS ... its just saying docker is not getting authorization to proceed from whatever source of auth it happens to be using

In my case, in test I removed directory ~/.docker and got that error ... after I bounced my local docker registry then docker push was fine

Auto-click button element on page load using jQuery

I tried the following ways in first jQuery, then JavaScript:


 window.location.href = $(".contact").attr('href');

This is the best way in JavaScript:


MySQL Results as comma separated list

You can use GROUP_CONCAT to perform that, e.g. something like

FROM sites s
INNER JOIN publications p ON( = p.site_id)

How to remove padding around buttons in Android?

In the button's XML set android:includeFontPadding="false"

Android check null or empty string in Android

Use TextUtils.isEmpty( someString )

String myString = null;

if (TextUtils.isEmpty(myString)) {
    return; // or break, continue, throw

// myString is neither null nor empty if this point is reached
Log.i("TAG", myString);


  • The documentation states that both null and zero length are checked for. No need to reinvent the wheel here.
  • A good practice to follow is early return.

Using SHA1 and RSA with vs. MessageDigest and Cipher

To produce the same results:

MessageDigest sha1 = MessageDigest.getInstance("SHA1", BOUNCY_CASTLE_PROVIDER);
byte[] digest = sha1.digest(content);
DERObjectIdentifier sha1oid_ = new DERObjectIdentifier("");

AlgorithmIdentifier sha1aid_ = new AlgorithmIdentifier(sha1oid_, null);
DigestInfo di = new DigestInfo(sha1aid_, digest);

byte[] plainSig = di.getDEREncoded();
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", BOUNCY_CASTLE_PROVIDER);
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
byte[] signature = cipher.doFinal(plainSig);

Is there an equivalent to CTRL+C in IPython Notebook in Firefox to break cells that are running?

UPDATE: Turned my solution into a stand-alone python script.

This solution has saved me more than once. Hopefully others find it useful. This python script will find any jupyter kernel using more than cpu_threshold CPU and prompts the user to send a SIGINT to the kernel (KeyboardInterrupt). It will keep sending SIGINT until the kernel's cpu usage goes below cpu_threshold. If there are multiple misbehaving kernels it will prompt the user to interrupt each of them (ordered by highest CPU usage to lowest). A big thanks goes to gcbeltramini for writing code to find the name of a jupyter kernel using the jupyter api. This script was tested on MACOS with python3 and requires jupyter notebook, requests, json and psutil.

Put the script in your home directory and then usage looks like:

python ~/
Interrupt kernel chews cpu.ipynb; PID: 57588; CPU: 2.3%? (y/n) y

Script code below:

from os import getpid, kill
from time import sleep
import re
import signal

from notebook.notebookapp import list_running_servers
from requests import get
from requests.compat import urljoin
import ipykernel
import json
import psutil

def get_active_kernels(cpu_threshold):
    """Get a list of active jupyter kernels."""
    active_kernels = []
    pids = psutil.pids()
    my_pid = getpid()

    for pid in pids:
        if pid == my_pid:
            p = psutil.Process(pid)
            cmd = p.cmdline()
            for arg in cmd:
                if arg.count('ipykernel'):
                    cpu = p.cpu_percent(interval=0.1)
                    if cpu > cpu_threshold:
                        active_kernels.append((cpu, pid, cmd))
        except psutil.AccessDenied:
    return active_kernels

def interrupt_bad_notebooks(cpu_threshold=0.2):
    """Interrupt active jupyter kernels. Prompts the user for each kernel."""

    active_kernels = sorted(get_active_kernels(cpu_threshold), reverse=True)

    servers = list_running_servers()
    for ss in servers:
        response = get(urljoin(ss['url'].replace('localhost', ''), 'api/sessions'),
                       params={'token': ss.get('token', '')})
        for nn in json.loads(response.text):
            for kernel in active_kernels:
                for arg in kernel[-1]:
                    if arg.count(nn['kernel']['id']):
                        pid = kernel[1]
                        cpu = kernel[0]
                        interrupt = input(
                            'Interrupt kernel {}; PID: {}; CPU: {}%? (y/n) '.format(nn['notebook']['path'], pid, cpu))
                        if interrupt.lower() == 'y':
                            p = psutil.Process(pid)
                            while p.cpu_percent(interval=0.1) > cpu_threshold:
                                kill(pid, signal.SIGINT)

if __name__ == '__main__':

Permission to write to the SD card

The suggested technique above in Dave's answer is certainly a good design practice, and yes ultimately the required permission must be set in the AndroidManifest.xml file to access the external storage.

However, the Mono-esque way to add most (if not all, not sure) "manifest options" is through the attributes of the class implementing the activity (or service).

The Visual Studio Mono plugin automatically generates the manifest, so its best not to manually tamper with it (I'm sure there are cases where there is no other option).

For example:

[Activity(Label="MonoDroid App", MainLauncher=true, Permission="android.permission.WRITE_EXTERNAL_STORAGE")]
public class MonoActivity : Activity
  protected override void OnCreate(Bundle bindle)

PostgreSQL: How to change PostgreSQL user password?


On many systems, a user's account often contains a period, or some sort of punction (user: john.smith, horise.johnson). IN these cases a modification will have to be made to the accepted answer above. The change requires the username to be double-quoted.


ALTER USER "username.lastname" WITH PASSWORD 'password'; 


Postgres is quite picky on when to use a 'double quote' and when to use a 'single quote'. Typically when providing a string you would use a single quote.

How to list all methods for an object in Ruby?

What about one of these?


How can I check if a file exists in Perl?


if (-f $filePath)
  # code

-e returns true even if the file is a directory. -f will only return true if it's an actual file

How do you add a timer to a C# console application

Use the System.Threading.Timer class.

System.Windows.Forms.Timer is designed primarily for use in a single thread usually the Windows Forms UI thread.

There is also a System.Timers class added early on in the development of the .NET framework. However it is generally recommended to use the System.Threading.Timer class instead as this is just a wrapper around System.Threading.Timer anyway.

It is also recommended to always use a static (shared in VB.NET) System.Threading.Timer if you are developing a Windows Service and require a timer to run periodically. This will avoid possibly premature garbage collection of your timer object.

Here's an example of a timer in a console application:

using System; 
using System.Threading; 
public static class Program 
    public static void Main() 
       Console.WriteLine("Main thread: starting a timer"); 
       Timer t = new Timer(ComputeBoundOp, 5, 0, 2000); 
       Console.WriteLine("Main thread: Doing other work here...");
       Thread.Sleep(10000); // Simulating other work (10 seconds)
       t.Dispose(); // Cancel the timer now
    // This method's signature must match the TimerCallback delegate
    private static void ComputeBoundOp(Object state) 
       // This method is executed by a thread pool thread 
       Console.WriteLine("In ComputeBoundOp: state={0}", state); 
       Thread.Sleep(1000); // Simulates other work (1 second)
       // When this method returns, the thread goes back 
       // to the pool and waits for another task 

From the book CLR Via C# by Jeff Richter. By the way this book describes the rationale behind the 3 types of timers in Chapter 23, highly recommended.

JQuery, Spring MVC @RequestBody and JSON - making it work together

I'm pretty sure you only have to register MappingJacksonHttpMessageConverter

(the easiest way to do that is through <mvc:annotation-driven /> in XML or @EnableWebMvc in Java)


Here's a working example:

Maven POM

<project xmlns="" xmlns:xsi=""
    <version>0.0.1-SNAPSHOT</version><name>json test</name>
        <dependency><!-- spring mvc -->
        <dependency><!-- jackson -->
            <!-- javac --><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId>
            <!-- jetty --><plugin><groupId>org.mortbay.jetty</groupId><artifactId>jetty-maven-plugin</artifactId>

in folder src/main/webapp/WEB-INF


<web-app xmlns="" xmlns:xsi=""


<beans xmlns=""

    <import resource="classpath:mvc-context.xml" />


in folder src/main/resources:


<beans xmlns=""
    xmlns:mvc="" xmlns:xsi=""

    <mvc:annotation-driven />
    <context:component-scan base-package="test.json" />

In folder src/main/java/test/json

public class TestController {

    @RequestMapping(method = RequestMethod.POST, value = "math")
    public Result math(@RequestBody final Request request) {
        final Result result = new Result();
        result.setAddition(request.getLeft() + request.getRight());
        result.setSubtraction(request.getLeft() - request.getRight());
        result.setMultiplication(request.getLeft() * request.getRight());
        return result;


public class Request implements Serializable {
    private static final long serialVersionUID = 1513207428686438208L;
    private int left;
    private int right;
    public int getLeft() {return left;}
    public void setLeft(int left) {this.left = left;}
    public int getRight() {return right;}
    public void setRight(int right) {this.right = right;}

public class Result implements Serializable {
    private static final long serialVersionUID = -5054749880960511861L;
    private int addition;
    private int subtraction;
    private int multiplication;

    public int getAddition() { return addition; }
    public void setAddition(int addition) { this.addition = addition; }
    public int getSubtraction() { return subtraction; }
    public void setSubtraction(int subtraction) { this.subtraction = subtraction; }
    public int getMultiplication() { return multiplication; }
    public void setMultiplication(int multiplication) { this.multiplication = multiplication; }

You can test this setup by executing mvn jetty:run on the command line, and then sending a POST request:

URL:        http://localhost:8080/test/math
mime type:  application/json
post body:  { "left": 13 , "right" : 7 }

I used the Poster Firefox plugin to do this.

Here's what the response looks like:


How can I run PowerShell with the .NET 4 runtime?

Just as another option, the latest PoshConsole release includes binaries targeted to .NET 4 RC (which work fine against the RTM release) without any configuration.

Capitalize first letter. MySQL

If there are more than 1 word in the column, then this will not work as shown below. The UDF mentioned above may help in such case.

mysql> select * from names;
| name         |
| john abraham | 
1 row in set (0.00 sec)

mysql> SELECT CONCAT(UCASE(MID(name,1,1)),MID(name,2)) AS name FROM names;
| name         |
| John abraham | 
1 row in set (0.00 sec)

Or maybe this one will help...

PHP Warning: Unknown: failed to open stream

It is a SELinux blocking issue, Linux prevented httpd access. Here is the solution:

# restorecon '/var/www/html/wiki/index.php'
# restorecon -R '/var/www/html/wiki/index.php'
# /sbin/restorecon '/var/www/html/wiki/index.php'

Run script on mac prompt "Permission denied"

use source before file name,,

like my file which i want to run from terminal is ./jay/bin/activate

so i used command "source ./jay/bin/activate"

Update OpenSSL on OS X with Homebrew

In a terminal, run:

export PATH=/usr/local/bin:$PATH
brew link --force openssl

You may have to unlink openssl first if you get a warning: brew unlink openssl

This ensures we're linking the correct openssl for this situation. (and doesn't mess with .profile)

Hat tip to @Olaf's answer and @Felipe's comment. Some people - such as myself - may have some pretty messed up PATH vars.

How to declare local variables in postgresql?

Postgresql historically doesn't support procedural code at the command level - only within functions. However, in Postgresql 9, support has been added to execute an inline code block that effectively supports something like this, although the syntax is perhaps a bit odd, and there are many restrictions compared to what you can do with SQL Server. Notably, the inline code block can't return a result set, so can't be used for what you outline above.

In general, if you want to write some procedural code and have it return a result, you need to put it inside a function. For example:

  one int;
  two int;
  one := 1;
  two := 2;
  RETURN one + two;
SELECT somefuncname();

The PostgreSQL wire protocol doesn't, as far as I know, allow for things like a command returning multiple result sets. So you can't simply map T-SQL batches or stored procedures to PostgreSQL functions.

"replace" function examples

Be aware that the third parameter (value) in the examples given above: the value is a constant (e.g. 'Z' or c(20,30)).

Defining the third parameter using values from the data frame itself can lead to confusion.

E.g. with a simple data frame such as this (using dplyr::data_frame):

tmp <- data_frame(a=1:10, b=sample(LETTERS[24:26], 10, replace=T))

This will create somthing like this:

       a     b
   (int) (chr)
1      1     X
2      2     Y
3      3     Y
4      4     X
5      5     Z


Now suppose you want wanted to do, was to multiply the values in column 'a' by 2, but only where column 'b' is "X". My immediate thought would be something like this:

with(tmp, replace(a, b=="X", a*2))

That will not provide the desired outcome, however. The a*2 will defined as a fixed vector rather than a reference to the 'a' column. The vector 'a*2' will thus be

[1]  2  4  6  8 10 12 14 16 18 20

at the start of the 'replace' operation. Thus, the first row where 'b' equals "X", the value in 'a' will be placed by 2. The second time, it will be replaced by 4, etc ... it will not be replaced by two-times-the-value-of-a in that particular row.

How to check if any value is NaN in a Pandas DataFrame

You could not only check if any 'NaN' exist but also get the percentage of 'NaN's in each column using the following,

df = pd.DataFrame({'col1':[1,2,3,4,5],'col2':[6,np.nan,8,9,10]})  

   col1 col2  
0   1   6.0  
1   2   NaN  
2   3   8.0  
3   4   9.0  
4   5   10.0  

col1    0.0  
col2    0.2  
dtype: float64

An "and" operator for an "if" statement in Bash

Try this:

if [ $STATUS -ne 200 -a "$STRING" != "$VALUE" ]; then

Recommended way to insert elements into map

Use insert if you want to insert a new element. insert will not overwrite an existing element, and you can verify that there was no previously exising element:

if ( !myMap.insert( std::make_pair( key, value ) ).second ) {
    //  Element already present...

Use [] if you want to overwrite a possibly existing element:

myMap[ key ] = value;
assert( myMap.find( key )->second == value ); // post-condition

This form will overwrite any existing entry.

Setting DataContext in XAML in WPF

There are several issues here.

  1. You can't assign DataContext as DataContext="{Binding Employee}" because it's a complex object which can't be assigned as string. So you have to use <Window.DataContext></Window.DataContext> syntax.
  2. You assign the class that represents the data context object to the view, not an individual property so {Binding Employee} is invalid here, you just have to specify an object.
  3. Now when you assign data context using valid syntax like below

know that you are creating a new instance of the Employee class and assigning it as the data context object. You may well have nothing in default constructor so nothing will show up. But then how do you manage it in code behind file? You have typecast the DataContext.

    private void my_button_Click(object sender, RoutedEventArgs e)
        Employee e = (Employee) DataContext;
  1. A second way is to assign the data context in the code behind file itself. The advantage then is your code behind file already knows it and can work with it.

    public partial class MainWindow : Window
       Employee employee = new Employee();
       public MainWindow()
           DataContext = employee;

Cannot read property 'addEventListener' of null

I faced a similar situation. This is probably because the script is executed before the page loads. By placing the script at the bottom of the page, I circumvented the problem.

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

I just found a simple and reliable solution if you are using the system UI approach (

It works in the case when you are using View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN, e.g. if you are using CoordinatorLayout.

It won't work for WindowManager.LayoutParams.FLAG_FULLSCREEN (The one you can also set in theme with android:windowFullscreen), but you can achieve similar effect with SYSTEM_UI_FLAG_LAYOUT_STABLE (which "has the same visual effect" according to the docs) and this solution should work again.

                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION /* If you want to hide navigation */

I've tested it on my device running Marshmallow.

The key is that soft keyboards are also one of the system windows (such as status bar and navigation bar), so the WindowInsets dispatched by system contains accurate and reliable information about it.

For the use case such as in DrawerLayout where we are trying to draw behind the status bar, We can create a layout that ignores only the top inset, and applies the bottom inset which accounts for the soft keyboard.

Here is my custom FrameLayout:

 * Implements an effect similar to {@code android:fitsSystemWindows="true"} on Lollipop or higher,
 * except ignoring the top system window inset. {@code android:fitsSystemWindows="true"} does not
 * and should not be set on this layout.
public class FitsSystemWindowsExceptTopFrameLayout extends FrameLayout {

    public FitsSystemWindowsExceptTopFrameLayout(Context context) {

    public FitsSystemWindowsExceptTopFrameLayout(Context context, AttributeSet attrs) {
        super(context, attrs);

    public FitsSystemWindowsExceptTopFrameLayout(Context context, AttributeSet attrs,
                                                 int defStyleAttr) {
        super(context, attrs, defStyleAttr);

    public FitsSystemWindowsExceptTopFrameLayout(Context context, AttributeSet attrs,
                                                 int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);

    public WindowInsets onApplyWindowInsets(WindowInsets insets) {
            setPadding(insets.getSystemWindowInsetLeft(), 0, insets.getSystemWindowInsetRight(),
            return insets.replaceSystemWindowInsets(0, insets.getSystemWindowInsetTop(), 0, 0);
        } else {
            return super.onApplyWindowInsets(insets);

And to use it:


    <!-- Your original layout here -->

This should theoretically work for any device without insane modification, much better than any hack that tries to take a random 1/3 or 1/4 of screen size as reference.

(It requires API 16+, but I'm using fullscreen only on Lollipop+ for drawing behind the status bar so it's the best solution in this case.)

How can I get the URL of the current tab from a Google Chrome extension?

Use chrome.tabs.query() like this:

chrome.tabs.query({active: true, lastFocusedWindow: true}, tabs => {
    let url = tabs[0].url;
    // use `url` here inside the callback because it's asynchronous!

This requires that you request access to the chrome.tabs API in your extension manifest:

"permissions": [ ...

It's important to note that the definition of your "current tab" may differ depending on your extension's needs.

Setting lastFocusedWindow: true in the query is appropriate when you want to access the current tab in the user's focused window (typically the topmost window).

Setting currentWindow: true allows you to get the current tab in the window where your extension's code is currently executing. For example, this might be useful if your extension creates a new window / popup (changing focus), but still wants to access tab information from the window where the extension was run.

I chose to use lastFocusedWindow: true in this example, because Google calls out cases in which currentWindow may not always be present.

You are free to further refine your tab query using any of the properties defined here: chrome.tabs.query

Email and phone Number Validation in android

public boolean checkForEmail() {
        Context c;
        EditText mEtEmail=(EditText)findViewById(;
        String mStrEmail = mEtEmail.getText().toString();
        if (android.util.Patterns.EMAIL_ADDRESS.matcher(mStrEmail).matches()) {
            return true;
        Toast.makeText(this,"Email is not valid", Toast.LENGTH_LONG).show();
        return false;

    public boolean checkForMobile() {
        Context c;
        EditText mEtMobile=(EditText)findViewById(;
        String mStrMobile = mEtMobile.getText().toString();
        if (android.util.Patterns.PHONE.matcher(mStrMobile).matches()) {
            return true;
        Toast.makeText(this,"Phone No is not valid", Toast.LENGTH_LONG).show();
        return false;

How to modify a text file?

Unfortunately there is no way to insert into the middle of a file without re-writing it. As previous posters have indicated, you can append to a file or overwrite part of it using seek but if you want to add stuff at the beginning or the middle, you'll have to rewrite it.

This is an operating system thing, not a Python thing. It is the same in all languages.

What I usually do is read from the file, make the modifications and write it out to a new file called myfile.txt.tmp or something like that. This is better than reading the whole file into memory because the file may be too large for that. Once the temporary file is completed, I rename it the same as the original file.

This is a good, safe way to do it because if the file write crashes or aborts for any reason, you still have your untouched original file.

Clear form fields with jQuery

Use this Code Where you want to Call Normal Reset Function by jQuery


And Write this Function Out Site jQuery on Document Ready

function reset_form()
    var fm=document.getElementById('form1');

TypeError: $ is not a function when calling jQuery function

Try this:

<script language="JavaScript" type="text/javascript" src="jquery/jquery.js"></script>
    (function ($) {
        function readyFn() {
            // Set your code here!!



Is there anything like .NET's NotImplementedException in Java?

As mentioned, the JDK does not have a close match. However, my team occasionally has a use for such an exception as well. We could have gone with UnsupportedOperationException as suggested by other answers, but we prefer a custom exception class in our base library that has deprecated constructors:

public class NotYetImplementedException extends RuntimeException
     * @deprecated Deprecated to remind you to implement the corresponding code
     *             before releasing the software.
    public NotYetImplementedException()

     * @deprecated Deprecated to remind you to implement the corresponding code
     *             before releasing the software.
    public NotYetImplementedException(String message)

This approach has the following benefits:

  1. When readers see NotYetImplementedException, they know that an implementation was planned and was either forgotten or is still in progress, whereas UnsupportedOperationException says (in line with collection contracts) that something will never be implemented. That's why we have the word "yet" in the class name. Also, an IDE can easily list the call sites.
  2. With the deprecation warning at each call site, your IDE and static code analysis tool can remind you where you still have to implement something. (This use of deprecation may feel wrong to some, but in fact deprecation is not limited to announcing removal.)
  3. The constructors are deprecated, not the class. This way, you only get a deprecation warning inside the method that needs implementing, not at the import line (JDK 9 fixed this, though).

how to implement a pop up dialog box in iOS

Yup, a UIAlertView is probably what you're looking for. Here's an example:

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"No network connection" 
                                                message:@"You must be connected to the internet to use this app." 
[alert show];
[alert release];

If you want to do something more fancy, say display a custom UI in your UIAlertView, you can subclass UIAlertView and put in custom UI components in the init method. If you want to respond to a button press after a UIAlertView appears, you can set the delegate above and implement the - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex method.

You might also want to look at the UIActionSheet.

How to draw text using only OpenGL methods?

I think that the best solution for drawing text in OpenGL is texture fonts, I work with them for a long time. They are flexible, fast and nice looking (with some rear exceptions). I use special program for converting font files (.ttf for example) to texture, which is saved to file of some internal "font" format (I've developed format and program based on though my version went rather far from the original supporting Unicode and so on). When starting the main app, fonts are loaded from this "internal" format. Look link above for more information.

With such approach the main app doesn't use any special libraries like FreeType, which is undesirable for me also. Text is being drawn using standard OpenGL functions.

How to return a result (startActivityForResult) from a TabHost Activity?

Oh, god! After spending several hours and downloading the Android sources, I have finally come to a solution.

If you look at the Activity class, you will see, that finish() method only sends back the result if there is a mParent property set to null. Otherwise the result is lost.

public void finish() {
    if (mParent == null) {
        int resultCode;
        Intent resultData;
        synchronized (this) {
            resultCode = mResultCode;
            resultData = mResultData;
        if (Config.LOGV) Log.v(TAG, "Finishing self: token=" + mToken);
        try {
            if (ActivityManagerNative.getDefault()
                .finishActivity(mToken, resultCode, resultData)) {
                mFinished = true;
        } catch (RemoteException e) {
            // Empty
    } else {

So my solution is to set result to the parent activity if present, like that:

Intent data = new Intent();
if (getParent() == null) {
    setResult(Activity.RESULT_OK, data);
} else {
    getParent().setResult(Activity.RESULT_OK, data);

I hope that will be helpful if someone looks for this problem workaround again.

Android Left to Right slide animation

You can overwrite your default activity animation. Here is the solution that I use:

Create a "CustomActivityAnimation" and add this to your base Theme by "windowAnimationStyle".

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorPrimary</item>
    <item name="android:windowAnimationStyle">@style/CustomActivityAnimation</item>


<style name="CustomActivityAnimation" parent="@android:style/Animation.Activity">
    <item name="android:activityOpenEnterAnimation">@anim/slide_in_right</item>
    <item name="android:activityOpenExitAnimation">@anim/slide_out_left</item>
    <item name="android:activityCloseEnterAnimation">@anim/slide_in_left</item>
    <item name="android:activityCloseExitAnimation">@anim/slide_out_right</item>

Create anim folder under res folder and then create this four animation files:


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

<set xmlns:android="">
    <translate android:fromXDelta="100%p" android:toXDelta="0"


<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="">
    <translate android:fromXDelta="0" android:toXDelta="-100%p"


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

<set xmlns:android="">
    <translate android:fromXDelta="-100%p" android:toXDelta="0"


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

<set xmlns:android="">
    <translate android:fromXDelta="0" android:toXDelta="100%p"

This is my sample project in github.

That's all... Happy coding :)

cast_sender.js error: Failed to load resource: net::ERR_FAILED in Chrome

Apparently YouTube constantly polls for Google Cast scripts even if the extension isn't installed.

From one commenter:

... it appears that Chrome attempts to get cast_sender.js on pages that have YouTube content. I'm guessing when Chrome sees media that it can stream it attempts to access the Chromecast extension. When the extension isn't present, the error is thrown.

Read more

The only solution I've come across is to install the Google Cast extension, whether you need it or not. You may then hide the toolbar button.

For more information and updates, see this SO question. Here's the official issue.

Getting msbuild.exe without installing Visual Studio

The latest (as of Jan 2019) stand-alone MSBuild installers can be found here:

Scroll down to "Tools for Visual Studio 2019" and choose "Build Tools for Visual Studio 2019" (despite the name, it's for users who don't want the full IDE)

See this question for additional information.

How Do I Get the Query Builder to Output Its Raw SQL Query as a String?

I did it by listening query logs and appending to a log array:

//create query
$log=[];//array of log lines
//invoked on query execution if query log is enabled
DB::listen(function ($query)use(&$log){
    $log[]=$query;//enqueue query data to logs
//enable query log

Basic Apache commands for a local Windows machine

For frequent uses of this command I found it easy to add the location of C:\xampp\apache\bin to the PATH. Use whatever directory you have this installed in.

Then you can run from any directory in command line:

httpd -k restart

The answer above that suggests httpd -k -restart is actually a typo. You can see the commands by running httpd /?

Postgres Error: More than one row returned by a subquery used as an expression

Technically, to repair your statement, you can add LIMIT 1 to the subquery to ensure that at most 1 row is returned. That would remove the error, your code would still be nonsense.

... 'SELECT store_key FROM store LIMIT 1' ...

Practically, you want to match rows somehow instead of picking an arbitrary row from the remote table store to update every row of your local table customer.
Your rudimentary question doesn't provide enough details, so I am assuming a text column match_name in both tables (and UNIQUE in store) for the sake of this example:

... 'SELECT store_key FROM store
     WHERE match_name = ' || quote_literal(customer.match_name)  ...

But that's an extremely expensive way of doing things.

Ideally, you should completely rewrite the statement.

UPDATE customer c
SET    customer_id = s.store_key
FROM   dblink('port=5432, dbname=SERVER1 user=postgres password=309245'
             ,'SELECT match_name, store_key FROM store')
       AS s(match_name text, store_key integer)
WHERE c.match_name = s.match_name
AND   c.customer_id IS DISTINCT FROM s.store_key;

This remedies a number of problems in your original statement.

  • Obviously, the basic problem leading to your error is fixed.

  • It's almost always better to join in additional relations in the FROM clause of an UPDATE statement than to run correlated subqueries for every individual row.

  • When using dblink, the above becomes a thousand times more important. You do not want to call dblink() for every single row, that's extremely expensive. Call it once to retrieve all rows you need.

  • With correlated subqueries, if no row is found in the subquery, the column gets updated to NULL, which is almost always not what you want.
    In my updated form, the row only gets updated if a matching row is found. Else, the row is not touched.

  • Normally, you wouldn't want to update rows, when nothing actually changes. That's expensively doing nothing (but still produces dead rows). The last expression in the WHERE clause prevents such empty updates:

     AND   c.customer_id IS DISTINCT FROM sub.store_key

Creating a Zoom Effect on an image on hover using CSS?

<!DOCTYPE html>
.zoom {

  overflow: hidden;

.zoom img {
  transition: transform .5s ease;
.zoom:hover img {
  transform: scale(1.5);


<h1>Image Zoom On Hover</h1>
<div class="zoom">
  <img src="/image-path-url" alt="">


Java 8 forEach with index

It works with params if you capture an array with one element, that holds the current index.

int[] idx = { 0 };
params.forEach(e -> query.bind(idx[0]++, e));

The above code assumes, that the method forEach iterates through the elements in encounter order. The interface Iterable specifies this behaviour for all classes unless otherwise documented. Apparently it works for all implementations of Iterable from the standard library, and changing this behaviour in the future would break backward-compatibility.

If you are working with Streams instead of Collections/Iterables, you should use forEachOrdered, because forEach can be executed concurrently and the elements can occur in different order. The following code works for both sequential and parallel streams:

int[] idx = { 0 }; -> query.bind(idx[0]++, e));

How to scroll to an element?

Follow these steps:

1) Install:

npm install react-scroll-to --save

2) Import the package:

import { ScrollTo } from "react-scroll-to";

3) Usage:

class doc extends Component {
  render() {
        {({ scroll }) => (
          <a onClick={() => scroll({ x: 20, y: 500, , smooth: true })}>Scroll to Bottom</a>

What's the best way to set a single pixel in an HTML5 canvas?

Hmm, you could also just make a 1 pixel wide line with a length of 1 pixel and make it's direction move along a single axis.

            ctx.lineWidth = 1; // one pixel wide
            ctx.strokeStyle = rgba(...);
            ctx.moveTo(50,25); // positioned at 50,25
            ctx.lineTo(51,25); // one pixel long

Oracle query to fetch column names

  1. SELECT * FROM <SCHEMA_NAME.TABLE_NAME> WHERE ROWNUM = 0; --> Note that, this is Query Result, a ResultSet. This is exportable to other formats. And, you can export the Query Result to Text format. Export looks like below when I did SELECT * FROM SATURN.SPRIDEN WHERE ROWNUM = 0; :


  2. DESCRIBE <TABLE_NAME> --> Note: This is script output.

Date Comparison using Java

If for some reason you're intent on using Date objects for your solution, you'll need to do something like this:

    // Convert user input into year, month, and day integers
    Date toDate = new Date(year - 1900, month - 1, day + 1);
    Date currentDate = new Date();
    boolean runThatReport = toDate.after(currentDate);

Shifting the toDate ahead to midnight of the next day will take care of the bug I've whined about in the comments to other answers. But, note that this approach uses a deprecated constructor; any approach relying on Date will use one deprecated method or another, and depending on how you do it may lead to race conditions as well (if you base toDate off of new Date() and then fiddle around with the year, month, and day, for instance). Use Calendar, as described elsewhere.

jQuery: print_r() display equivalent?

Look at this: and find for print_r or use console.log() with firebug.

Best way to check if MySQL results returned in PHP?

Whenever we do queries to get some data, it is returned as an object. Then most of us convert it to array for looping through the rows easily. In php "empty()" function is used to check if an array is empty i.e. if it has no data in it. So we can check if returned array representation of query isn't empty by doing like this

           //DO STUFF

How do I get a file's last modified time in Perl?

Use the builtin stat function. Or more specifically:

my $modtime = (stat($fh))[9]

Vim autocomplete for Python

Try Jedi! There's a Vim plugin at

It works just much better than anything else for Python in Vim. It even has support for renaming, goto, etc. The best part is probably that it really tries to understand your code (decorators, generators, etc. Just look at the feature list).

Select all elements with a "data-xxx" attribute without using jQuery

Here is an interesting solution: it uses the browsers CSS engine to to add a dummy property to elements matching the selector and then evaluates the computed style to find matched elements:

It does dynamically create a style rule [...] It then scans the whole document (using the much decried and IE-specific but very fast document.all) and gets the computed style for each of the elements. We then look for the foo property on the resulting object and check whether it evaluates as “bar”. For each element that matches, we add to an array.

pip install returning invalid syntax


pip3 install bs4

If you have python2 installed you typically have to make sure you are using the correct version of pip.

error: Your local changes to the following files would be overwritten by checkout

You can force checkout your branch, if you do not want to commit your local changes.

git checkout -f branch_name

jQuery get text as number

Use the javascript parseInt method (

var number = parseInt($(this).find('.number').text(), 10);
var current = 600;
if (current > number){
     // do something

Don't forget to specify the radix value of 10 which tells parseInt that it's in base 10.

Purpose of returning by const value?

It makes sure that the returned object (which is an RValue at that point) can't be modified. This makes sure the user can't do thinks like this:

myFunc() = Object(...);

That would work nicely if myFunc returned by reference, but is almost certainly a bug when returned by value (and probably won't be caught by the compiler). Of course in C++11 with its rvalues this convention doesn't make as much sense as it did earlier, since a const object can't be moved from, so this can have pretty heavy effects on performance.

ng-model for `<input type="file"/>` (with directive DEMO)

Try this,this is working for me in angular JS

    let fileToUpload = `${documentLocation}/${documentType}.pdf`;
    let absoluteFilePath = path.resolve(__dirname, fileToUpload);
    console.log(`Uploading document ${absoluteFilePath}`);

Failed to open/create the internal network Vagrant on Windows10

Reboot your PC

Sadly, did not work for me in Windows 10 x64 with VirtualBox 5.2.6

The box was already checked and a simple reboot fixed it.

After years of telling people to just reboot, I failed to follow my own golden advice; face, meet palm.

Can the Android drawable directory contain subdirectories?

It is possible to have multiple drawable folders by having an extra folder parallel to 'res' with a subdirectory 'drawable' and then add following to gradle:

sourceSets {
    main {
        res.srcDirs 'src/main/<extra_res>'

Tested with gradle 6.5.1

Android: Bitmaps loaded from gallery are rotated in ImageView

Solved it in my case with this code using help of this post:

            Bitmap myBitmap = getBitmap(imgFile.getAbsolutePath());

            try {
                ExifInterface exif = new ExifInterface(imgFile.getAbsolutePath());
                int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
                Log.d("EXIF", "Exif: " + orientation);
                Matrix matrix = new Matrix();
                if (orientation == 6) {
                else if (orientation == 3) {
                else if (orientation == 8) {
                myBitmap = Bitmap.createBitmap(myBitmap, 0, 0, myBitmap.getWidth(), myBitmap.getHeight(), matrix, true); // rotating bitmap
            catch (Exception e) {

            ImageView img = (ImageView) findViewById(;

Hope it saves someone's time!

How to make a function wait until a callback has been called using node.js

If you don't want to use call back then you can Use "Q" module.

For example:

function getdb() {
    var deferred = Q.defer();
    MongoClient.connect(databaseUrl, function(err, db) {
        if (err) {
            console.log("Problem connecting database");
            deferred.reject(new Error(err));
        } else {
            var collection = db.collection("url");
    return deferred.promise;

getdb().then(function(collection) {
   // This function will be called afte getdb() will be executed. 

    // If Error accrued. 


For more information refer this:

How to check the exit status using an if statement

Note that exit codes != 0 are used to report error. So, it's better to do:

if [ $retVal -ne 0 ]; then
    echo "Error"
exit $retVal

instead of

# will fail for error codes > 1
if [ $retVal -eq 1 ]; then
    echo "Error"
exit $retVal

How do you set, clear, and toggle a single bit?

If you're doing a lot of bit twiddling you might want to use masks which will make the whole thing quicker. The following functions are very fast and are still flexible (they allow bit twiddling in bit maps of any size).

const unsigned char TQuickByteMask[8] =
   0x01, 0x02, 0x04, 0x08,
   0x10, 0x20, 0x40, 0x80,

/** Set bit in any sized bit mask.
 * @return    none
 * @param     bit    - Bit number.
 * @param     bitmap - Pointer to bitmap.
void TSetBit( short bit, unsigned char *bitmap)
    short n, x;

    x = bit / 8;        // Index to byte.
    n = bit % 8;        // Specific bit in byte.

    bitmap[x] |= TQuickByteMask[n];        // Set bit.

/** Reset bit in any sized mask.
 * @return  None
 * @param   bit    - Bit number.
 * @param   bitmap - Pointer to bitmap.
void TResetBit( short bit, unsigned char *bitmap)
    short n, x;

    x = bit / 8;        // Index to byte.
    n = bit % 8;        // Specific bit in byte.

    bitmap[x] &= (~TQuickByteMask[n]);    // Reset bit.

/** Toggle bit in any sized bit mask.
 * @return   none
 * @param   bit    - Bit number.
 * @param   bitmap - Pointer to bitmap.
void TToggleBit( short bit, unsigned char *bitmap)
    short n, x;

    x = bit / 8;        // Index to byte.
    n = bit % 8;        // Specific bit in byte.

    bitmap[x] ^= TQuickByteMask[n];        // Toggle bit.

/** Checks specified bit.
 * @return  1 if bit set else 0.
 * @param   bit    - Bit number.
 * @param   bitmap - Pointer to bitmap.
short TIsBitSet( short bit, const unsigned char *bitmap)
    short n, x;

    x = bit / 8;    // Index to byte.
    n = bit % 8;    // Specific bit in byte.

    // Test bit (logigal AND).
    if (bitmap[x] & TQuickByteMask[n])
        return 1;

    return 0;

/** Checks specified bit.
 * @return  1 if bit reset else 0.
 * @param   bit    - Bit number.
 * @param   bitmap - Pointer to bitmap.
short TIsBitReset( short bit, const unsigned char *bitmap)
    return TIsBitSet(bit, bitmap) ^ 1;

/** Count number of bits set in a bitmap.
 * @return   Number of bits set.
 * @param    bitmap - Pointer to bitmap.
 * @param    size   - Bitmap size (in bits).
 * @note    Not very efficient in terms of execution speed. If you are doing
 *        some computationally intense stuff you may need a more complex
 *        implementation which would be faster (especially for big bitmaps).
 *        See (
int TCountBits( const unsigned char *bitmap, int size)
    int i, count = 0;

    for (i=0; i<size; i++)
        if (TIsBitSet(i, bitmap))

    return count;

Note, to set bit 'n' in a 16 bit integer you do the following:

TSetBit( n, &my_int);

It's up to you to ensure that the bit number is within the range of the bit map that you pass. Note that for little endian processors that bytes, words, dwords, qwords, etc., map correctly to each other in memory (main reason that little endian processors are 'better' than big-endian processors, ah, I feel a flame war coming on...).

How to convert text to binary code in JavaScript?

This might be the simplest you can get:

function text2Binary(string) {
    return string.split('').map(function (char) {
        return char.charCodeAt(0).toString(2);
    }).join(' ');

Automatic exit from Bash shell script on error

One idiom is:

cd some_dir && ./configure --some-flags && make && make install

I realize that can get long, but for larger scripts you could break it into logical functions.

Can't use Swift classes inside Objective-C

The file is created automatically (talking about Xcode 6.3.2 here). But you won't see it, since it's in your Derived Data folder. After marking your swift class with @objc, compile, then search for Swift.h in your Derived Data folder. You should find the Swift header there.

I had the problem, that Xcode renamed my my-Project-Swift.h to my_Project-Swift.h Xcode doesn't like "." "-" etc. symbols. With the method above you can find the filename and import it to a Objective-C class.

Difference between PACKETS and FRAMES

Consider TCP over ATM. ATM uses 48 byte frames, but clearly TCP packets can be bigger than that. A frame is the chunk of data sent as a unit over the data link (Ethernet, ATM). A packet is the chunk of data sent as a unit over the layer above it (IP). If the data link is made specifically for IP, as Ethernet and WiFi are, these will be the same size and packets will correspond to frames.

Bizarre Error in Chrome Developer Console - Failed to load resource: net::ERR_CACHE_MISS

I had issues getting through a form because of this error.

I used Ctrl+Click to click the submit button and navigate through the form as usual.

How many characters can you store with 1 byte?

1 byte may hold 1 character. For Example: Refer Ascii values for each character & convert into binary. This is how it works.

enter image description here value 255 is stored as (11111111) base 2. Visit this link for knowing more about binary conversion.

Size of Tiny Int = 1 Byte ( -128 to 127)

Int = 4 Bytes (-2147483648 to 2147483647)

Rounded Corners Image in Flutter

You can use CircleAvatar Widget with radius:

             radius: 50.0,
             backgroundImage: AssetImage("assets/img1.jpeg"),

How do you completely remove Ionic and Cordova installation from mac?

I found that I had to use:

npm uninstall @ionic/cli

to stop ionic from still being active.

Webdriver Screenshot

driver.save_screenshot("path to save \\screen.jpeg")

How much overhead does SSL impose?

Order of magnitude: zero.

In other words, you won't see your throughput cut in half, or anything like it, when you add TLS. Answers to the "duplicate" question focus heavily on application performance, and how that compares to SSL overhead. This question specifically excludes application processing, and seeks to compare non-SSL to SSL only. While it makes sense to take a global view of performance when optimizing, that is not what this question is asking.

The main overhead of SSL is the handshake. That's where the expensive asymmetric cryptography happens. After negotiation, relatively efficient symmetric ciphers are used. That's why it can be very helpful to enable SSL sessions for your HTTPS service, where many connections are made. For a long-lived connection, this "end-effect" isn't as significant, and sessions aren't as useful.

Here's an interesting anecdote. When Google switched Gmail to use HTTPS, no additional resources were required; no network hardware, no new hosts. It only increased CPU load by about 1%.

How to receive serial data using android bluetooth

Take a look at incredible Bluetooth Serial class that has onResume() ability that helped me so much. I hope this helps ;)

What is a blob URL and why it is used?

What is blob url? Why it is used?

BLOB is just byte sequence. Browser recognize it as byte stream. It is used to get byte stream from source.

A Blob object represents a file-like object of immutable, raw data. Blobs represent data that isn't necessarily in a JavaScript-native format. The File interface is based on Blob, inheriting blob functionality and expanding it to support files on the user's system.

Can i make my own blob url on a server?

Yes you can there are serveral ways to do so for example try


Finding the index of elements based on a condition using python list comprehension

Even if it's a late answer: I think this is still a very good question and IMHO Python (without additional libraries or toolkits like numpy) is still lacking a convenient method to access the indices of list elements according to a manually defined filter.

You could manually define a function, which provides that functionality:

def indices(list, filtr=lambda x: bool(x)):
    return [i for i,x in enumerate(list) if filtr(x)]

print(indices([1,0,3,5,1], lambda x: x==1))

Yields: [0, 4]

In my imagination the perfect way would be making a child class of list and adding the indices function as class method. In this way only the filter method would be needed:

class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
    def indices(self, filtr=lambda x: bool(x)):
        return [i for i,x in enumerate(self) if filtr(x)]

my_list = MyList([1,0,3,5,1])
my_list.indices(lambda x: x==1)

I elaborated a bit more on that topic here:

Changing Underline color

I think the easiest way to do this is in your css, use:

text-decoration-color: red;

This will change the color of the underline without changing the color of your text. Good luck!

Get date from input form within PHP

if (isset($_POST['birthdate'])) {
    $timestamp = strtotime($_POST['birthdate']); 

Fastest Way to Find Distance Between Two Lat/Long Points

Using mysql

SET @orig_lon = 1.027125;
SET @dest_lon = 1.027125;

SET @orig_lat = 2.398441;
SET @dest_lat = 2.398441;

SET @kmormiles = 6371;-- for distance in miles set to : 3956

SELECT @kmormiles * ACOS(LEAST(COS(RADIANS(@orig_lat)) * 
 COS(RADIANS(@dest_lat)) * COS(RADIANS(@orig_lon - @dest_lon)) + 
 SIN(RADIANS(@orig_lat)) * SIN(RADIANS(@dest_lat)),1.0)) as distance;




NOTE: LEAST is used to avoid null values as a comment suggested on

(.text+0x20): undefined reference to `main' and undefined reference to function

This rule

main: producer.o consumer.o AddRemove.o
   $(COMPILER) -pthread $(CCFLAGS) -o producer.o consumer.o AddRemove.o

is wrong. It says to create a file named producer.o (with -o producer.o), but you want to create a file named main. Please excuse the shouting, but ALWAYS USE $@ TO REFERENCE THE TARGET:

main: producer.o consumer.o AddRemove.o
   $(COMPILER) -pthread $(CCFLAGS) -o $@ producer.o consumer.o AddRemove.o

As Shahbaz rightly points out, the gmake professionals would also use $^ which expands to all the prerequisites in the rule. In general, if you find yourself repeating a string or name, you're doing it wrong and should use a variable, whether one of the built-ins or one you create.

main: producer.o consumer.o AddRemove.o
   $(COMPILER) -pthread $(CCFLAGS) -o $@ $^

MySQL: Delete all rows older than 10 minutes

The answer is right in the MYSQL manual itself.

"DELETE FROM `table_name` WHERE `time_col` < ADDDATE(NOW(), INTERVAL -1 HOUR)"

Printing with "\t" (tabs) does not result in aligned columns

Building on this question, I use the following code to indent my messages:

String prefix1 = "short text:";
String prefix2 = "looooooooooooooong text:";
String msg = "indented";
* The second string begins after 40 characters. The dash means that the
* first string is left-justified.
String format = "%-40s%s%n";
System.out.printf(format, prefix1, msg);
System.out.printf(format, prefix2, msg);

This is the output:

short text:                             indented
looooooooooooooong text:                indented

This is documented in section "Flag characters" in man 3 printf.

How can javascript upload a blob?

2019 Update

This updates the answers with the latest Fetch API and doesn't need jQuery.

Disclaimer: doesn't work on IE, Opera Mini and older browsers. See caniuse.

Basic Fetch

It could be as simple as:

  fetch(``, {method:"POST", body:blobData})
                .then(response => console.log(response.text()))

Fetch with Error Handling

After adding error handling, it could look like:

fetch(``, {method:"POST", body:blobData})
            .then(response => {
                if (response.ok) return response;
                else throw Error(`Server returned ${response.status}: ${response.statusText}`)
            .then(response => console.log(response.text()))
            .catch(err => {

PHP Code

This is the server-side code in upload.php.

    // gets entire POST body
    $data = file_get_contents('php://input');
    // write the data out to the file
    $fp = fopen("path/to/file", "wb");

    fwrite($fp, $data);

How to read file using NPOI

private DataTable GetDataTableFromExcel(String Path)
        XSSFWorkbook wb;
        XSSFSheet sh;
        String Sheet_name;

        using (var fs = new FileStream(Path, FileMode.Open, FileAccess.Read))
            wb = new XSSFWorkbook(fs);

               Sheet_name= wb.GetSheetAt(0).SheetName;  //get first sheet name
        DataTable DT = new DataTable();

        // get sheet
        sh = (XSSFSheet)wb.GetSheet(Sheet_name);

        int i = 0;
        while (sh.GetRow(i) != null)
            // add neccessary columns
            if (DT.Columns.Count < sh.GetRow(i).Cells.Count)
                for (int j = 0; j < sh.GetRow(i).Cells.Count; j++)
                    DT.Columns.Add("", typeof(string));

            // add row

            // write row value
            for (int j = 0; j < sh.GetRow(i).Cells.Count; j++)
                var cell = sh.GetRow(i).GetCell(j);

                if (cell != null)
                    // TODO: you can add more cell types capatibility, e. g. formula
                    switch (cell.CellType)
                        case NPOI.SS.UserModel.CellType.Numeric:
                            DT.Rows[i][j] = sh.GetRow(i).GetCell(j).NumericCellValue;
                            //dataGridView1[j, i].Value = sh.GetRow(i).GetCell(j).NumericCellValue;

                        case NPOI.SS.UserModel.CellType.String:
                            DT.Rows[i][j] = sh.GetRow(i).GetCell(j).StringCellValue;



        return DT;

MVC If statement in View

You only need to prefix an if statement with @ if you're not already inside a razor code block.

Edit: You have a couple of things wrong with your code right now.

You're declaring nmb, but never actually doing anything with the value. So you need figure out what that's supposed to actually be doing. In order to fix your code, you need to make a couple of tiny changes:

@if (ViewBag.Articles != null)
    int nmb = 0;
    foreach (var item in ViewBag.Articles)
        if (nmb % 3 == 0)
            @:<div class="row"> 

        <a href="@Url.Action("Article", "Programming", new { id = })">
            <div class="tasks">
                <div class="col-md-4">
                    <div class="task important">
                        <div class="tmeta">
                            <i class="icon-calendar"></i>
                                @item.DateAdded - Pregleda:@item.Click
                            <i class="icon-pushpin"></i> Authorrr
        if (nmb % 3 == 0)

The important part here is the @:. It's a short-hand of <text></text>, which is used to force the razor engine to render text.

One other thing, the HTML standard specifies that a tags can only contain inline elements, and right now, you're putting a div, which is a block-level element, inside an a.

Add User to Role ASP.NET Identity

I had the same challenge. This is the solution I found to add users to roles.

internal class Security
    ApplicationDbContext context = new ApplicationDbContext();

    internal void AddUserToRole(string userName, string roleName)
        var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));

            var user = UserManager.FindByName(userName);
            UserManager.AddToRole(user.Id, roleName);

How to send Basic Auth with axios

For some reasons, this simple problem is blocking many developers. I struggled for many hours with this simple thing. This problem as many dimensions:

  1. CORS (if you are using a frontend and backend on different domains et ports.
  2. Backend CORS Configuration
  3. Basic Authentication configuration of Axios


My setup for development is with a vuejs webpack application running on localhost:8081 and a spring boot application running on localhost:8080. So when trying to call rest API from the frontend, there's no way that the browser will let me receive a response from the spring backend without proper CORS settings. CORS can be used to relax the Cross Domain Script (XSS) protection that modern browsers have. As I understand this, browsers are protecting your SPA from being an attack by an XSS. Of course, some answers on StackOverflow suggested to add a chrome plugin to disable XSS protection but this really does work AND if it was, would only push the inevitable problem for later.

Backend CORS configuration

Here's how you should setup CORS in your spring boot app:

Add a CorsFilter class to add proper headers in the response to a client request. Access-Control-Allow-Origin and Access-Control-Allow-Headers are the most important thing to have for basic authentication.

    public class CorsFilter implements Filter {

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpServletRequest request = (HttpServletRequest) servletRequest;

        response.setHeader("Access-Control-Allow-Origin", "http://localhost:8081");
        response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH");
        **response.setHeader("Access-Control-Allow-Headers", "authorization, Content-Type");**
        response.setHeader("Access-Control-Max-Age", "3600");

        filterChain.doFilter(servletRequest, servletResponse);


Add a configuration class which extends Spring WebSecurityConfigurationAdapter. In this class you will inject your CORS filter:

public class SecurityConfig extends WebSecurityConfigurerAdapter {
    CorsFilter corsFilter() {
        CorsFilter filter = new CorsFilter();
        return filter;

    protected void configure(HttpSecurity http) throws Exception {

        http.addFilterBefore(corsFilter(), SessionManagementFilter.class) //adds your custom CorsFilter

You don't have to put anything related to CORS in your controller.


Now, in the frontend you need to create your axios query with the Authorization header:

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <script src=""></script>
    <script src=""></script>
<div id="app">
    <p>{{ status }}</p>
    var vm = new Vue({
        el: "#app",
        data: {
            status: ''
        created: function () {
        methods: {
            getBackendResource: function () {
                this.status = 'Loading...';
                var vm = this;
                var user = "aUserName";
                var pass = "aPassword";
                var url = 'http://localhost:8080/api/resource';

                var authorizationBasic = window.btoa(user + ':' + pass);
                var config = {
                    "headers": {
                        "Authorization": "Basic " + authorizationBasic
                axios.get(url, config)
                    .then(function (response) {
                        vm.status =[0];
                    .catch(function (error) {
                        vm.status = 'An error occured.' + error;

Hope this helps.

best way to preserve numpy arrays on disk

There is now a HDF5 based clone of pickle called hickle!

import hickle as hkl 

data = { 'name' : 'test', 'data_arr' : [1, 2, 3, 4] }

# Dump data to file
hkl.dump( data, 'new_data_file.hkl' )

# Load data from file
data2 = hkl.load( 'new_data_file.hkl' )

print( data == data2 )


There also is the possibility to "pickle" directly into a compressed archive by doing:

import pickle, gzip, lzma, bz2

pickle.dump( data, 'data.pkl.gz',   'wb' ) )
pickle.dump( data, 'data.pkl.lzma', 'wb' ) )
pickle.dump( data, 'data.pkl.bz2',  'wb' ) )



import numpy as np
import matplotlib.pyplot as plt
import pickle, os, time
import gzip, lzma, bz2, h5py

compressions = [ 'pickle', 'h5py', 'gzip', 'lzma', 'bz2' ]
labels = [ 'pickle', 'h5py', 'pickle+gzip', 'pickle+lzma', 'pickle+bz2' ]
size = 1000

data = {}

# Random data
data['random'] = np.random.random((size, size))

# Not that random data
data['semi-random'] = np.zeros((size, size))
for i in range(size):
    for j in range(size):
        data['semi-random'][i,j] = np.sum(data['random'][i,:]) + np.sum(data['random'][:,j])

# Not random data
data['not-random'] = np.arange( size*size, dtype=np.float64 ).reshape( (size, size) )

sizes = {}

for key in data:

    sizes[key] = {}

    for compression in compressions:

        if compression == 'pickle':
            time_start = time.time()
            pickle.dump( data[key], open( 'data.pkl', 'wb' ) )
            time_tot = time.time() - time_start
            sizes[key]['pickle'] = ( os.path.getsize( 'data.pkl' ) * 10**(-6), time_tot )
            os.remove( 'data.pkl' )

        elif compression == 'h5py':
            time_start = time.time()
            with h5py.File( 'data.pkl.{}'.format(compression), 'w' ) as h5f:
                h5f.create_dataset('data', data=data[key])
            time_tot = time.time() - time_start
            sizes[key][compression] = ( os.path.getsize( 'data.pkl.{}'.format(compression) ) * 10**(-6), time_tot)
            os.remove( 'data.pkl.{}'.format(compression) )

            time_start = time.time()
            pickle.dump( data[key], eval(compression).open( 'data.pkl.{}'.format(compression), 'wb' ) )
            time_tot = time.time() - time_start
            sizes[key][ labels[ compressions.index(compression) ] ] = ( os.path.getsize( 'data.pkl.{}'.format(compression) ) * 10**(-6), time_tot )
            os.remove( 'data.pkl.{}'.format(compression) )

f, ax_size = plt.subplots()
ax_time = ax_size.twinx()

x_ticks = labels
x = np.arange( len(x_ticks) )

y_size = {}
y_time = {}
for key in data:
    y_size[key] = [ sizes[key][ x_ticks[i] ][0] for i in x ]
    y_time[key] = [ sizes[key][ x_ticks[i] ][1] for i in x ]

width = .2
viridis =

p1 = x-width, y_size['random']       , width, color = viridis(0)  )
p2 = x      , y_size['semi-random']  , width, color = viridis(.45))
p3 = x+width, y_size['not-random']   , width, color = viridis(.9) )

p4 = x-width, y_time['random']  , .02, color = 'red') x      , y_time['semi-random']  , .02, color = 'red') x+width, y_time['not-random']   , .02, color = 'red')

ax_size.legend( (p1, p2, p3, p4), ('random', 'semi-random', 'not-random', 'saving time'), loc='upper center',bbox_to_anchor=(.5, -.1), ncol=4 )
ax_size.set_xticks( x )
ax_size.set_xticklabels( x_ticks )

f.suptitle( 'Pickle Compression Comparison' )
ax_size.set_ylabel( 'Size [MB]' )
ax_time.set_ylabel( 'Time [s]' )

f.savefig( 'sizes.pdf', bbox_inches='tight' )

Create hive table using "as select" or "like" and also specify delimiter

Create Table as select (CTAS) is possible in Hive.

You can try out below command:

CREATE TABLE new_test 
    row format delimited 
    fields terminated by '|' 
AS select * from source where col=1
  1. Target cannot be partitioned table.
  2. Target cannot be external table.
  3. It copies the structure as well as the data

Create table like is also possible in Hive.

  1. It just copies the source table definition.

jQuery Validate Required Select

use min rule

set first option value to 0


How to prevent SIGPIPEs (or handle them properly)

What's the best practice to prevent the crash here?

Either disable sigpipes as per everybody, or catch and ignore the error.

Is there a way to check if the other side of the line is still reading?

Yes, use select().

select() doesn't seem to work here as it always says the socket is writable.

You need to select on the read bits. You can probably ignore the write bits.

When the far end closes its file handle, select will tell you that there is data ready to read. When you go and read that, you will get back 0 bytes, which is how the OS tells you that the file handle has been closed.

The only time you can't ignore the write bits is if you are sending large volumes, and there is a risk of the other end getting backlogged, which can cause your buffers to fill. If that happens, then trying to write to the file handle can cause your program/thread to block or fail. Testing select before writing will protect you from that, but it doesn't guarantee that the other end is healthy or that your data is going to arrive.

Note that you can get a sigpipe from close(), as well as when you write.

Close flushes any buffered data. If the other end has already been closed, then close will fail, and you will receive a sigpipe.

If you are using buffered TCPIP, then a successful write just means your data has been queued to send, it doesn't mean it has been sent. Until you successfully call close, you don't know that your data has been sent.

Sigpipe tells you something has gone wrong, it doesn't tell you what, or what you should do about it.

Could not find the main class, program will exit

I tried to start SQUirrel 3.1 but I received a message stating "Could not find the main class Files\Rational\ClearQuest\cqjni.jar" I noticed that C:\Program Files\Rational\ClearQuest\cqjni.jar is in my existing classpath as defined by the Windows environment variable, CLASSPATH.

SQUirrel doesn't need my existing classpath, so I updated the SQUirrel bat file, squirrel-sql.bat.



It no longer appends my existing classpath to its classpath and runs fine.

How to uninstall a package installed with pip install --user

As @thomas-lotze has mentioned, currently pip tooling does not do that as there is no corresponding --user option. But what I find is that I can check in ~/.local/bin and look for the specific pip#.# which looks to me like it corresponds to the --user option.

In my case:

antho@noctil: ~/.l/bin$ pwd
antho@noctil: ~/.l/bin$ ls pip*
pip  pip2  pip2.7  pip3  pip3.5

And then just uninstall with the specific pip version.

ImageView - have height match width?

In Android 26.0.0 PercentRelativeLayout has been deprecated.

The best way to solve it is now with ConstraintLayout like this:


    <ImageView android:layout_width="match_parent"


Here is a tutorial on how to add ConstraintLayout to your project.

How to assign name for a screen?

I am a beginner to screen but I find it immensely useful while restoring lost connections. Your question has already been answered but this information might serve as an add on - I use putty with putty connection manager and name my screens - "tab1", "tab2", etc. - as for me the overall picture of the 8-10 tabs is more important than each individual tab name. I use the 8th tab for connecting to db, the 7th for viewing logs, etc. So when I want to reattach my screens I have written a simple wrapper which says:

screen -d -r tab$1

where first argument is the tab number.

How do I reverse an int array in Java?

To reverse an int array, you swap items up until you reach the midpoint, like this:

for(int i = 0; i < validData.length / 2; i++)
    int temp = validData[i];
    validData[i] = validData[validData.length - i - 1];
    validData[validData.length - i - 1] = temp;

The way you are doing it, you swap each element twice, so the result is the same as the initial list.

How to add more than one machine to the trusted hosts list using winrm

Same as @Altered-Ego but with txt.file:

Get-Content "C:\ServerList.txt"

$ServerList = Get-Content "C:\ServerList.txt"
    $currentTrustHost=(get-item WSMan:\localhost\Client\TrustedHosts).value
    if ( ($currentTrustHost).Length -gt "0" ) {
        $currentTrustHost+= ,$ServerList
        set-item WSMan:\localhost\Client\TrustedHosts –value $currentTrustHost -Force -ErrorAction SilentlyContinue
    else {
        $currentTrustHost+= $ServerList
        set-item WSMan:\localhost\Client\TrustedHosts –value $currentTrustHost -Force -ErrorAction SilentlyContinue

The "-ErrorAction SilentlyContinue" is required in old PS version to avoid fake error message:

PS C:\Windows\system32> get-item WSMan:\localhost\Client\TrustedHosts

   WSManConfig: Microsoft.WSMan.Management\WSMan::localhost\Client

Type            Name                           SourceOfValue   Value
----            ----                           -------------   -----
System.String   TrustedHosts                                   machineA,machineB,machineC,machineD

Python pip install module is not found. How to link python to pip location?

Make sure to check the python version you are working on if it is 2 then only pip install works If it is 3. something then make sure to use pip3 install

Skip the headers when editing a csv file using Python

Inspired by Martijn Pieters' response.

In case you only need to delete the header from the csv file, you can work more efficiently if you write using the standard Python file I/O library, avoiding writing with the CSV Python library:

with open("tmob_notcleaned.csv", "rb") as infile, open("tmob_cleaned.csv", "wb") as outfile:
   next(infile)  # skip the headers

Vue.js toggle class on click

If you need more than 1 class

You can do this:

<i id="icon" 
  v-bind:class="{ 'fa fa-star': showStar }"
  v-on:click="showStar = !showStar"

data: {
  showStar: true

Notice the single quotes ' around the classes!

Thanks to everyone else's solutions.

Error:Unknown host You may need to adjust the proxy settings in Gradle

Android Plugin for Gradle HTTP proxy settings

For application-specific HTTP proxy settings, set the proxy settings in the build.gradle file as required for each application module.

apply plugin: ''

android {

    defaultConfig {

For project-wide HTTP proxy settings, set the proxy settings in the gradle/ file.

# Project-wide Gradle settings.


Please read Official Document Configuration

Changing default shell in Linux

You can change the passwd file directly for the particular user or use the below command

chsh -s /usr/local/bin/bash username

Then log out and log in

Jenkins returned status code 128 with github

In my case I had to add the public key to my repo (at Bitbucket) AND use git clone once via ssh to answer yes to the "known host" question the first time.

While, Do While, For loops in Assembly Language (emu8086)


For-loop in C:

for(int x = 0; x<=3; x++)
    //Do something!

The same loop in 8086 assembler:

        xor cx,cx   ; cx-register is the counter, set to 0
loop1   nop         ; Whatever you wanna do goes here, should not change cx
        inc cx      ; Increment
        cmp cx,3    ; Compare cx to the limit
        jle loop1   ; Loop while less or equal

That is the loop if you need to access your index (cx). If you just wanna to something 0-3=4 times but you do not need the index, this would be easier:

        mov cx,4    ; 4 iterations
loop1   nop         ; Whatever you wanna do goes here, should not change cx
        loop loop1  ; loop instruction decrements cx and jumps to label if not 0

If you just want to perform a very simple instruction a constant amount of times, you could also use an assembler-directive which will just hardcore that instruction

times 4 nop


Do-while-loop in C:

int x=1;
    //Do something!

The same loop in assembler:

        mov ax,1
loop1   nop         ; Whatever you wanna do goes here
        cmp ax,1    ; Check wether cx is 1
        je loop1    ; And loop if equal


While-loop in C:

    //Do something

The same loop in assembler:

        jmp loop1   ; Jump to condition first
cloop1  nop         ; Execute the content of the loop
loop1   cmp ax,1    ; Check the condition
        je cloop1   ; Jump to content of the loop if met

For the for-loops you should take the cx-register because it is pretty much standard. For the other loop conditions you can take a register of your liking. Of course replace the no-operation instruction with all the instructions you wanna perform in the loop.

Get current date in Swift 3?

You can do it in this way with Swift 3.0:

let date = Date()
let calendar = Calendar.current
let components = calendar.dateComponents([.year, .month, .day], from: date)

let year =  components.year
let month = components.month
let day =


How to call servlet through a JSP page

You can either post HTML form to URL, which is mapped to servlet or insert your data in HttpServletRequest object you pass to jsp page.

Amazon AWS Filezilla transfer permission denied

To allow user ec2-user (Amazon AWS) write access to the public web directory (/var/www/html),
enter this command via Putty or Terminal, as the root user sudo:

chown -R ec2-user /var/www/html

Make sure permissions on that entire folder were correct:

chmod -R 755 /var/www/html


Setting up amazon ec2-instances

Connect to Amazon EC2 file directory using Filezilla and SFTP (Video)

Understanding and Using File Permissions

Given URL is not allowed by the Application configuration Facebook application error

Sometimes this error occurs for old javascript sdk. If you save locally javascript file. Update it. I prefer to load it form the facebook server all the time.

Releasing memory in Python

eryksun has answered question #1, and I've answered question #3 (the original #4), but now let's answer question #2:

Why does it release 50.5mb in particular - what is the amount that is released based on?

What it's based on is, ultimately, a whole series of coincidences inside Python and malloc that are very hard to predict.

First, depending on how you're measuring memory, you may only be measuring pages actually mapped into memory. In that case, any time a page gets swapped out by the pager, memory will show up as "freed", even though it hasn't been freed.

Or you may be measuring in-use pages, which may or may not count allocated-but-never-touched pages (on systems that optimistically over-allocate, like linux), pages that are allocated but tagged MADV_FREE, etc.

If you really are measuring allocated pages (which is actually not a very useful thing to do, but it seems to be what you're asking about), and pages have really been deallocated, two circumstances in which this can happen: Either you've used brk or equivalent to shrink the data segment (very rare nowadays), or you've used munmap or similar to release a mapped segment. (There's also theoretically a minor variant to the latter, in that there are ways to release part of a mapped segment—e.g., steal it with MAP_FIXED for a MADV_FREE segment that you immediately unmap.)

But most programs don't directly allocate things out of memory pages; they use a malloc-style allocator. When you call free, the allocator can only release pages to the OS if you just happen to be freeing the last live object in a mapping (or in the last N pages of the data segment). There's no way your application can reasonably predict this, or even detect that it happened in advance.

CPython makes this even more complicated—it has a custom 2-level object allocator on top of a custom memory allocator on top of malloc. (See the source comments for a more detailed explanation.) And on top of that, even at the C API level, much less Python, you don't even directly control when the top-level objects are deallocated.

So, when you release an object, how do you know whether it's going to release memory to the OS? Well, first you have to know that you've released the last reference (including any internal references you didn't know about), allowing the GC to deallocate it. (Unlike other implementations, at least CPython will deallocate an object as soon as it's allowed to.) This usually deallocates at least two things at the next level down (e.g., for a string, you're releasing the PyString object, and the string buffer).

If you do deallocate an object, to know whether this causes the next level down to deallocate a block of object storage, you have to know the internal state of the object allocator, as well as how it's implemented. (It obviously can't happen unless you're deallocating the last thing in the block, and even then, it may not happen.)

If you do deallocate a block of object storage, to know whether this causes a free call, you have to know the internal state of the PyMem allocator, as well as how it's implemented. (Again, you have to be deallocating the last in-use block within a malloced region, and even then, it may not happen.)

If you do free a malloced region, to know whether this causes an munmap or equivalent (or brk), you have to know the internal state of the malloc, as well as how it's implemented. And this one, unlike the others, is highly platform-specific. (And again, you generally have to be deallocating the last in-use malloc within an mmap segment, and even then, it may not happen.)

So, if you want to understand why it happened to release exactly 50.5mb, you're going to have to trace it from the bottom up. Why did malloc unmap 50.5mb worth of pages when you did those one or more free calls (for probably a bit more than 50.5mb)? You'd have to read your platform's malloc, and then walk the various tables and lists to see its current state. (On some platforms, it may even make use of system-level information, which is pretty much impossible to capture without making a snapshot of the system to inspect offline, but luckily this isn't usually a problem.) And then you have to do the same thing at the 3 levels above that.

So, the only useful answer to the question is "Because."

Unless you're doing resource-limited (e.g., embedded) development, you have no reason to care about these details.

And if you are doing resource-limited development, knowing these details is useless; you pretty much have to do an end-run around all those levels and specifically mmap the memory you need at the application level (possibly with one simple, well-understood, application-specific zone allocator in between).

what is .subscribe in angular?

subscribe() -Invokes an execution of an Observable and registers Observer handlers for notifications it will emit. -Observable- representation of any set of values over any amount of time.

Regular expression to remove HTML tags from a string

A trivial approach would be to replace


with nothing. But depending on how ill-structured your input is that may well fail.

AngularJS. How to call controller function from outside of controller component

I would rather include the factory as dependencies on the controllers than inject them with their own line of code:

myModule.factory('mySharedService', function($rootScope) {
    return sharedService = {thing:"value"};

function ControllerZero($scope, mySharedService) {
    $scope.thing = mySharedService.thing;

ControllerZero.$inject = ['$scope', 'mySharedService'];

What does -save-dev mean in npm install grunt --save-dev

When you use the parameter "--save" your dependency will go inside the #1 below in package.json. When you use the parameter "--save-dev" your dependency will go inside the #2 below in package.json.

#1. "dependencies": these packages are required by your application in production.

#2. "devDependencies": these packages are only needed for development and testing

Difference between IISRESET and IIS Stop-Start command

Take IISReset as a suite of commands that helps you manage IIS start / stop etc.

Which means you need to specify option (/switch) what you want to do to carry any operation.

Default behavior OR default switch is /restart with iisreset so you do not need to run command twice with /start and /stop.

Hope this clarifies your question. For reference the output of iisreset /? is:

IISRESET.EXE (c) Microsoft Corp. 1998-2005

iisreset [computername]

    /RESTART            Stop and then restart all Internet services.
    /START              Start all Internet services.
    /STOP               Stop all Internet services.
    /REBOOT             Reboot the computer.
    /REBOOTONERROR      Reboot the computer if an error occurs when starting,
                        stopping, or restarting Internet services.
    /NOFORCE            Do not forcefully terminate Internet services if
                        attempting to stop them gracefully fails.
    /TIMEOUT:val        Specify the timeout value ( in seconds ) to wait for
                        a successful stop of Internet services. On expiration
                        of this timeout the computer can be rebooted if
                        the /REBOOTONERROR parameter is specified.
                        The default value is 20s for restart, 60s for stop,
                        and 0s for reboot.
    /STATUS             Display the status of all Internet services.
    /ENABLE             Enable restarting of Internet Services
                        on the local system.
    /DISABLE            Disable restarting of Internet Services
                        on the local system.

Formatting doubles for output in C#

The problem is that .NET will always round a double to 15 significant decimal digits before applying your formatting, regardless of the precision requested by your format and regardless of the exact decimal value of the binary number.

I'd guess that the Visual Studio debugger has its own format/display routines that directly access the internal binary number, hence the discrepancies between your C# code, your C code and the debugger.

There's nothing built-in that will allow you to access the exact decimal value of a double, or to enable you to format a double to a specific number of decimal places, but you could do this yourself by picking apart the internal binary number and rebuilding it as a string representation of the decimal value.

Alternatively, you could use Jon Skeet's DoubleConverter class (linked to from his "Binary floating point and .NET" article). This has a ToExactString method which returns the exact decimal value of a double. You could easily modify this to enable rounding of the output to a specific precision.

double i = 10 * 0.69;
Console.WriteLine(DoubleConverter.ToExactString(6.9 - i));

// 6.89999999999999946709294817992486059665679931640625
// 0.00000000000000088817841970012523233890533447265625
// 6.9000000000000003552713678800500929355621337890625

Simplest way to restart service on a remote computer

As of Windows XP, you can use sc.exe to interact with local and remote services. Schedule a task to run a batch file similar to this:

sc \\server stop service
sc \\server start service

Make sure the task runs under a user account privileged on the target server.

psservice.exe from the Sysinternals PSTools would also be doing the job:

psservice \\server restart service

Accessing Google Spreadsheets with C# using Google Data API

I'm pretty sure there'll be some C# SDKs / toolkits on Google Code for this. I found this one, but there may be others so it's worth having a browse around.

How To: Execute command line in C#, get STD OUT results

You will need to use ProcessStartInfo with RedirectStandardOutput enabled - then you can read the output stream. You might find it easier to use ">" to redirect the output to a file (via the OS), and then simply read the file.

[edit: like what Ray did: +1]

How can I append a string to an existing field in MySQL?

You need to use the CONCAT() function in MySQL for string concatenation:

UPDATE categories SET code = CONCAT(code, '_standard') WHERE id = 1;

In PHP, what is a closure and why does it use the "use" identifier?

This is how PHP expresses a closure. This is not evil at all and in fact it is quite powerful and useful.

Basically what this means is that you are allowing the anonymous function to "capture" local variables (in this case, $tax and a reference to $total) outside of it scope and preserve their values (or in the case of $total the reference to $total itself) as state within the anonymous function itself.

How to use ng-repeat for dictionaries in AngularJs?

JavaScript developers tend to refer to the above data-structure as either an object or hash instead of a Dictionary.

Your syntax above is wrong as you are initializing the users object as null. I presume this is a typo, as the code should read:

// Initialize users as a new hash.
var users = {};
users["182982"] = "...";

To retrieve all the values from a hash, you need to iterate over it using a for loop:

function getValues (hash) {
    var values = [];
    for (var key in hash) {

        // Ensure that the `key` is actually a member of the hash and not
        // a member of the `prototype`.
        // see:
        if (hash.hasOwnProperty(key)) {
    return values;

If you plan on doing a lot of work with data-structures in JavaScript then the underscore.js library is definitely worth a look. Underscore comes with a values method which will perform the above task for you:

var values = _.values(users);

I don't use Angular myself, but I'm pretty sure there will be a convenience method build in for iterating over a hash's values (ah, there we go, Artem Andreev provides the answer above :))

Java FileReader encoding issue

FileInputStream with InputStreamReader is better than directly using FileReader, because the latter doesn't allow you to specify encoding charset.

Here is an example using BufferedReader, FileInputStream and InputStreamReader together, so that you could read lines from a file.

List<String> words = new ArrayList<>();
List<String> meanings = new ArrayList<>();
public void readAll( ) throws IOException{
    String fileName = "College_Grade4.txt";
    String charset = "UTF-8";
    BufferedReader reader = new BufferedReader(
        new InputStreamReader(
            new FileInputStream(fileName), charset)); 

    String line; 
    while ((line = reader.readLine()) != null) { 
        line = line.trim();
        if( line.length() == 0 ) continue;
        int idx = line.indexOf("\t");
        words.add( line.substring(0, idx ));
        meanings.add( line.substring(idx+1));

Django: multiple models in one template using forms

The MultiModelForm from django-betterforms is a convenient wrapper to do what is described in Gnudiff's answer. It wraps regular ModelForms in a single class which is transparently (at least for basic usage) used as a single form. I've copied an example from their docs below.

from django import forms
from django.contrib.auth import get_user_model
from betterforms.multiform import MultiModelForm
from .models import UserProfile

User = get_user_model()

class UserEditForm(forms.ModelForm):
    class Meta:
        fields = ('email',)

class UserProfileForm(forms.ModelForm):
    class Meta:
        fields = ('favorite_color',)

class UserEditMultiForm(MultiModelForm):
    form_classes = {
        'user': UserEditForm,
        'profile': UserProfileForm,

from django.views.generic import UpdateView
from django.core.urlresolvers import reverse_lazy
from django.shortcuts import redirect
from django.contrib.auth import get_user_model
from .forms import UserEditMultiForm

User = get_user_model()

class UserSignupView(UpdateView):
    model = User
    form_class = UserEditMultiForm
    success_url = reverse_lazy('home')

    def get_form_kwargs(self):
        kwargs = super(UserSignupView, self).get_form_kwargs()
            'user': self.object,
            'profile': self.object.profile,
        return kwargs

Using CSS :before and :after pseudo-elements with inline CSS?

Yes it's possible, just add inline styles for the element which you adding after or before, Example

     .horizontalProgress:after { width: 45%; }
 </style><!-- Change Value from Here -->

 <div class="horizontalProgress"></div>

Set value of hidden input with jquery

You don't need to set name , just giving an id is enough.

<input type="hidden" id="testId" />

and than with jquery you can use 'val()' method like below:


AssertContains on strings in jUnit

Use hamcrest Matcher containsString()

// Hamcrest assertion
assertThat(person.getName(), containsString("myName"));

// Error Message
Expected: a string containing "myName"
     got: "some other name"

You can optional add an even more detail error message.

// Hamcrest assertion with custom error message
assertThat("my error message", person.getName(), containsString("myName"));

// Error Message
java.lang.AssertionError: my error message
Expected: a string containing "myName"
     got: "some other name"

Posted my answer to a duplicate question here

how to show progress bar(circle) in an activity having a listview before loading the listview with data

Create an xml file any name (say progressBar.xml) in drawable and add <color name="silverGrey">#C0C0C0</color> in color.xml.

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

        android:useLevel="false" >
            android:width="300dip" />

            android:useLevel="false" />


Now in your xml file where you have your listView add this code:



In AsyncTask in the method:

protected void onPreExecute()

    // your code

And in onPostExecute:

protected void onPostExecute(String s)

    //your code

Android camera intent

private static final int TAKE_PICTURE = 1;    
private Uri imageUri;

public void takePhoto(View view) {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    File photo = new File(Environment.getExternalStorageDirectory(),  "Pic.jpg");
    imageUri = Uri.fromFile(photo);
    startActivityForResult(intent, TAKE_PICTURE);

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
    case TAKE_PICTURE:
        if (resultCode == Activity.RESULT_OK) {
            Uri selectedImage = imageUri;
            getContentResolver().notifyChange(selectedImage, null);
            ImageView imageView = (ImageView) findViewById(;
            ContentResolver cr = getContentResolver();
            Bitmap bitmap;
            try {
                 bitmap = android.provider.MediaStore.Images.Media
                 .getBitmap(cr, selectedImage);

                Toast.makeText(this, selectedImage.toString(),
            } catch (Exception e) {
                Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT)
                Log.e("Camera", e.toString());

Php $_POST method to get textarea value

Remove some of your textarea class like

<textarea name="Address" rows="3" class="input-text full-width" placeholder="Your Address" ></textarea>


<textarea name="Address" rows="3" class="full-width" placeholder="Your Address" ></textarea>

It's dependent on your template (Purchased Template). The developer has included some JavaScript to get the value from correct object on UI, but class like input-text just finds only $('input[type=text]'), that's why.

HTTP Request in Kotlin

If you are using Kotlin, you might as well keep your code as succinct as possible. The run method turns the receiver into this and returns the value of the block. this as HttpURLConnection creates a smart cast. bufferedReader().readText() avoids a bunch of boilerplate code.

return URL(url).run {
        openConnection().run {
            this as HttpURLConnection

You can also wrap this into an extension function.

fun URL.getText(): String {
    return openConnection().run {
                this as HttpURLConnection

And call it like this

return URL(url).getText()

Finally, if you are super lazy, you can extend the String class instead.

fun String.getUrlText(): String {
    return URL(this).run {
            openConnection().run {
                this as HttpURLConnection

And call it like this

return "".getUrlText()

How to make a DIV not wrap?

Try to use width: 3000px; for the case of IE.

How do you remove a specific revision in the git history?

Per this comment (and I checked that this is true), rado's answer is very close but leaves git in a detached head state. Instead, remove HEAD and use this to remove <commit-id> from the branch you're on:

git rebase --onto <commit-id>^ <commit-id>

How to keep :active css style after click a button


:active denotes the interaction state (so for a button will be applied during press), :focus may be a better choice here. However, the styling will be lost once another element gains focus.

The final potential alternative using CSS would be to use :target, assuming the items being clicked are setting routes (e.g. anchors) within the page- however this can be interrupted if you are using routing (e.g. Angular), however this doesnt seem the case here.

.active:active {_x000D_
  color: red;_x000D_
.focus:focus {_x000D_
  color: red;_x000D_
:target {_x000D_
  color: red;_x000D_
<button class='active'>Active</button>_x000D_
<button class='focus'>Focus</button>_x000D_
<a href='#target1' id='target1' class='target'>Target 1</a>_x000D_
<a href='#target2' id='target2' class='target'>Target 2</a>_x000D_
<a href='#target3' id='target3' class='target'>Target 3</a>

Javascript / jQuery

As such, there is no way in CSS to absolutely toggle a styled state- if none of the above work for you, you will either need to combine with a change in your HTML (e.g. based on a checkbox) or programatically apply/remove a class using e.g. jQuery

$('button').on('click', function(){_x000D_
<script src=""></script>_x000D_

How to display a pdf in a modal window?

You can have a look at this library: it renders PDF document in a Web/HTML page

Also you can use Flash to embed the document into any HTML page like that:

<object data="your_file.pdf#view=Fit" type="application/pdf" width="100%" height="850">
        It appears your Web browser is not configured to display PDF files. No worries, just <a href="your_file.pdf">click here to download the PDF file.</a>

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

Most of the time @cer solution works but if in case its not working then try installing it in base R (NOT in R studio). As R studio runs base R executable in background so new package will be available in R studio as well. [my experience in macOS]

#ifdef replacement in the Swift language

In many situations, you don't really need conditional compilation; you just need conditional behavior that you can switch on and off. For that, you can use an environment variable. This has the huge advantage that you don't actually have to recompile.

You can set the environment variable, and easily switch it on or off, in the scheme editor:

enter image description here

You can retrieve the environment variable with NSProcessInfo:

    let dic = NSProcessInfo.processInfo().environment
    if dic["TRIPLE"] != nil {
        // ... do secret stuff here ...

Here's a real-life example. My app runs only on the device, because it uses the music library, which doesn't exist on the Simulator. How, then, to take screen shots on the Simulator for devices I don't own? Without those screen shots, I can't submit to the AppStore.

I need fake data and a different way of processing it. I have two environment variables: one which, when switched on, tells the app to generate the fake data from the real data while running on my device; the other which, when switched on, uses the fake data (not the missing music library) while running on the Simulator. Switching each of those special modes on / off is easy thanks to environment variable checkboxes in the Scheme editor. And the bonus is that I can't accidentally use them in my App Store build, because archiving has no environment variables.

Giving multiple conditions in for loop in Java

If you want to do that why not go with a while, for ease of mind? :P No, but seriously I didn't know that and seems kinda nice so thanks, nice to know!

c# razor url parameter from view

If you're doing the check inside the View, put the value in the ViewBag.

In your controller:

ViewBag["parameterName"] = Request["parameterName"];

It's worth noting that the Request and Response properties are exposed by the Controller class. They have the same semantics as HttpRequest and HttpResponse.

How to create id with AUTO_INCREMENT on Oracle?

There is no such thing as "auto_increment" or "identity" columns in Oracle as of Oracle 11g. However, you can model it easily with a sequence and a trigger:

Table definition:

CREATE TABLE departments (
  ID           NUMBER(10)    NOT NULL,

ALTER TABLE departments ADD (


Trigger definition:

BEFORE INSERT ON departments 

  FROM   dual;


IDENTITY column is now available on Oracle 12c:

create table t1 (
    c1 NUMBER GENERATED by default on null as IDENTITY,
    c2 VARCHAR2(10)

or specify starting and increment values, also preventing any insert into the identity column (GENERATED ALWAYS) (again, Oracle 12c+ only)

create table t1 (
    c2 VARCHAR2(10)

Alternatively, Oracle 12 also allows to use a sequence as a default value:


CREATE TABLE departments (
  ID           NUMBER(10)    DEFAULT dept_seq.nextval NOT NULL,

ALTER TABLE departments ADD (

cursor.fetchall() vs list(cursor) in Python

You could use list comprehensions to bring the item in your tuple into a list:

conn = mysql.connector.connect()
cursor = conn.cursor()
sql = "SELECT column_name FROM db.table_name;"

results = cursor.fetchall()
# bring the first item of the tuple in your results here
item_0_in_result = [_[0] for _ in results]

How can I get the list of files in a directory using C or C++?

One function is enough, you don't need to use any 3rd-party library (for Windows).

#include <Windows.h>

vector<string> get_all_files_names_within_folder(string folder)
    vector<string> names;
    string search_path = folder + "/*.*";
    WIN32_FIND_DATA fd; 
    HANDLE hFind = ::FindFirstFile(search_path.c_str(), &fd); 
    if(hFind != INVALID_HANDLE_VALUE) { 
        do { 
            // read all (real) files in current folder
            // , delete '!' read other 2 default folder . and ..
            if(! (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ) {
        }while(::FindNextFile(hFind, &fd)); 
    return names;

PS: as mentioned by @Sebastian, you could change *.* to *.ext in order to get only the EXT-files (i.e. of a specific type) in that directory.

LogisticRegression: Unknown label type: 'continuous' using sklearn in python

LogisticRegression is not for regression but classification !

The Y variable must be the classification class,

(for example 0 or 1)

And not a continuous variable,

that would be a regression problem.

Integrating the ZXing library directly into my Android application


compile ''

unfortunately didn't work for me.

This is what worked for me:

dependencies {
   compile 'com.journeyapps:zxing-android-embedded:3.0.1@aar'
   compile ''

Please find the link here:

XSLT string replace

replace isn't available for XSLT 1.0.

Codesling has a template for string-replace you can use as a substitute for the function:

<xsl:template name="string-replace-all">
    <xsl:param name="text" />
    <xsl:param name="replace" />
    <xsl:param name="by" />
        <xsl:when test="$text = '' or $replace = ''or not($replace)" >
            <!-- Prevent this routine from hanging -->
            <xsl:value-of select="$text" />
        <xsl:when test="contains($text, $replace)">
            <xsl:value-of select="substring-before($text,$replace)" />
            <xsl:value-of select="$by" />
            <xsl:call-template name="string-replace-all">
                <xsl:with-param name="text" select="substring-after($text,$replace)" />
                <xsl:with-param name="replace" select="$replace" />
                <xsl:with-param name="by" select="$by" />
            <xsl:value-of select="$text" />

invoked as:

<xsl:variable name="newtext">
    <xsl:call-template name="string-replace-all">
        <xsl:with-param name="text" select="$text" />
        <xsl:with-param name="replace" select="a" />
        <xsl:with-param name="by" select="b" />

On the other hand, if you literally only need to replace one character with another, you can call translate which has a similar signature. Something like this should work fine:

<xsl:variable name="newtext" select="translate($text,'a','b')"/>

Also, note, in this example, I changed the variable name to "newtext", in XSLT variables are immutable, so you can't do the equivalent of $foo = $foo like you had in your original code.

Browse for a directory in C#

string folderPath = "";
FolderBrowserDialog folderBrowserDialog1 = new FolderBrowserDialog();
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK) {
    folderPath = folderBrowserDialog1.SelectedPath ;

Select and display only duplicate records in MySQL

SELECT * FROM `table` t1 join `table` t2 WHERE ( && (!

mysql extract year from date format

try this code:


NSRange from Swift Range?

let text:String = "Hello Friend"

let searchRange:NSRange = NSRange(location:0,length: text.characters.count)

let range:Range`<Int`> = Range`<Int`>.init(start: searchRange.location, end: searchRange.length)

Centering FontAwesome icons vertically and horizontally

I just managed how to center icons and and making them a container instead of putting them into one.

.fas {
    position: relative;
    color: #EEE;
    font-size: 16px;
.fas:before {
    position: absolute;
    left: calc(50% - .5em);
    top: calc(50% - .5em);
.fas.fa-icon {
    width: 60px;
    height: 60px;
    color: white;
    background-color: black;

Setting state on componentDidMount()

According to the React Documentation it's perfectly OK to call setState() from within the componentDidMount() function.

It will cause render() to be called twice, which is less efficient than only calling it once, but other than that it's perfectly fine.

You can find the documentation here:

Here is the excerpt from the documentation:

You may call setState() immediately in componentDidMount(). It will trigger an extra rendering, but it will happen before the browser updates the screen. This guarantees that even though the render() will be called twice in this case, the user won’t see the intermediate state. Use this pattern with caution because it often causes performance issues...

How to distinguish between left and right mouse click with jQuery

Edit: I changed it to work for dynamically added elements using .on() in jQuery 1.7 or above:

$(document).on("contextmenu", ".element", function(e){
   alert('Context Menu event has fired!');
   return false;


[Start of original post] This is what worked for me:

   alert('Context Menu event has fired!');
   return false;

In case you are into multiple solutions ^^

Edit: Tim Down brings up a good point that it's not always going to be a right-click that fires the contextmenu event, but also when the context menu key is pressed (which is arguably a replacement for a right-click)

Sum columns with null values in oracle

The other answers regarding the use of nvl() are correct however none seem to address a more salient point:

Should you even have NULLs in this column?

Do they have a meaning other than 0?

This seems like a case where you should have a NOT NULL DEFAULT 0 on th ecolumn

How do I make flex box work in safari?

Demo ->

Safari still requires the -webkit- prefix to use flexbox.

    box-sizing: border-box;_x000D_
    display: -webkit-box;_x000D_
    display: -webkit-flex;_x000D_
    display: -ms-flexbox;_x000D_
    display: flex;_x000D_
    -webkit-flex: 0 1 auto;_x000D_
    -ms-flex: 0 1 auto;_x000D_
    flex: 0 1 auto;_x000D_
    -webkit-box-orient: horizontal;_x000D_
    -webkit-box-direction: normal;_x000D_
    -webkit-flex-direction: row;_x000D_
    -ms-flex-direction: row;_x000D_
    flex-direction: row;_x000D_
    -webkit-flex-wrap: wrap;_x000D_
    -ms-flex-wrap: wrap;_x000D_
    flex-wrap: wrap;_x000D_
.col {_x000D_
    border:1px solid black;_x000D_
    -webkit-flex: 1 ;-ms-flex: 1 ;flex: 1 ;_x000D_
<div class="wrapper">_x000D_
    <div class="content">_x000D_
        <div class="row">_x000D_
            <div class="col medium">_x000D_
                <div class="box">_x000D_
                    work on safari browser _x000D_
            <div class="col medium">_x000D_
                <div class="box">_x000D_
                    work on safari browser _x000D_
                    work on safari browser _x000D_
                    work on safari browser _x000D_
                    work on safari browser _x000D_
                    work on safari browser _x000D_
            <div class="col medium">_x000D_
                <div class="box">_x000D_
                    work on safari browser _x000D_
                    work on safari browser _x000D_
                    work on safari browser _x000D_
                    work on safari browser _x000D_
                    work on safari browser _x000D_
                    work on safari browser  work on safari browser _x000D_
                    work on safari browser _x000D_
        </div>   _x000D_

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

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

git remote get-url origin

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

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

remote: add get-url subcommand

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

X close button only using css

-- Simple HTML Solution --

Final result of easy to resize icon:

two close X buttons with different thickness.

JSfiddle demo:

The simple HTML:

<a href="#" class="close" tabindex="0" role="button">close</a>


  • tabindex attribute is there to help accessibility focus of iOS touch devices.
  • role attribute is to let screen readers users know this is a button.
  • The word close is also intended for screen readers to mention.

The CSS code:

.close {
    position: absolute;
    top: 0;
    right: 0;
    display: block;
    width: 50px;
    height: 50px;
    font-size: 0;
.close:after {
    position: absolute;
    top: 50%;
    left: 50%;
    width: 5px;
    height: 20px;
    background-color: #F0F0F0;
    transform: rotate(45deg) translate(-50%, -50%);
    transform-origin: top left;
    content: '';
.close:after {
    transform: rotate(-45deg) translate(-50%, -50%);

To adjust thickness of close X icon, change the width property. Example for thinner icon:

.close:after {
    width: 2px;

To adjust length of close X icon, change the height property. Example:

.close:after {
    height: 33px;

checking memory_limit in PHP

Checking on command line:

php -i | grep "memory_limit"

How to Import Excel file into mysql Database from PHP

You are probably having a problem with the sort of CSV file that you have.

Open the CSV file with a text editor, check that all the separations are done with the comma, and not semicolon and try the script again. It should work fine.

Why is "using namespace std;" considered bad practice?

I think using locally or globally should depend on the application.

Because, when we use the library locally, sometimes the code is going to be a real mess. Readability is going to low.

So, we should use libraries locally only when there is a possibility for conflicts.

I am not a more experienced person. So, let me know if I am wrong.

Java: Why is the Date constructor deprecated, and what do I use instead?

As the Date constructor is deprecated, you can try this code.

import java.util.Calendar;

  Calendar calendar = Calendar.getInstance();
     calendar.set(Calendar.HOUR_OF_DAY, 6);// for 6 hour
     calendar.set(Calendar.MINUTE, 0);// for 0 min
     calendar.set(Calendar.SECOND, 0);// for 0 sec
     calendar.set(1996,0,26);// for Date [year,month(0 to 11), date]

    Date date = new Date(calendar.getTimeInMillis());// calendar gives long value

    String mConvertedDate = date.toString();// Fri Jan 26 06:00:00 GMT+05:30 1996

Executing JavaScript after X seconds

I believe you are looking for the setTimeout function.

To make your code a little neater, define a separate function for onclick in a <script> block:

function myClick() {
    function() {
    }, 5000);

then call your function from onclick


Rails 3.1 and Image Assets

In rails 4 you can now use a css and sass helper image-url:

div.logo {background-image: image-url("logo.png");}

If your background images aren't showing up consider looking at how you're referencing them in your stylesheets.

Get: TypeError: 'dict_values' object does not support indexing when using python 3.2.3

In Python 3 the dict.values() method returns a dictionary view object, not a list like it does in Python 2. Dictionary views have a length, can be iterated, and support membership testing, but don't support indexing.

To make your code work in both versions, you could use either of these:

{names[i]:value for i,value in enumerate(d.values())}


values = list(d.values())
{name:values[i] for i,name in enumerate(names)}

By far the simplest, fastest way to do the same thing in either version would be:

dict(zip(names, d.values()))

Note however, that all of these methods will give you results that will vary depending on the actual contents of d. To overcome that, you may be able use an OrderedDict instead, which remembers the order that keys were first inserted into it, so you can count on the order of what is returned by the values() method.

getting a checkbox array value from POST

I just used the following code:

<form method="post">
    <input id="user1" value="user1"  name="invite[]" type="checkbox">
    <input id="user2" value="user2"  name="invite[]" type="checkbox">
    <input type="submit">

        $invite = $_POST['invite'];

When I checked both boxes, the output was:

Array ( [0] => user1 [1] => user2 )

I know this doesn't directly answer your question, but it gives you a working example to reference and hopefully helps you solve the problem.

I can't install intel HAXM

Note: this is not an answer because I could not find a solution. But I think the information may be useful for others (and it wouldn't be practical as a comment). I have tried all of the steps detailed in the various docs but I could not get Android Emulator to work on my AMD Ryzen 7 :(

Most answers work only for Intel CPUs. If you have an AMD CPU (like me, an AMD Ryzen 7) you need to know about some restrictions and you have to use WHPX instead of HAXM.

I found this on MS's site: Because the Android emulator currently supports AMD hardware acceleration only on Linux, hardware acceleration is not available for AMD-based computers running Windows.

Fortunatelly there is a way to make it work but configuring hardware acceleration for an AMD CPU is a bit more complex:

Requirements and recommendations: - AMD CPU recommendation: AMD Ryzen CPU - Android Studio 3.2 Beta 1 or higher - Android Emulator version 27.3.8 or higher - Windows 10 with April 2018 Update or higher

To use WHPX acceleration on Windows, you must enable the Windows Hypervisor Platform option in the Turn Windows features on or off dialog box. For changes to this option to take effect, restart your computer.

Additionally, the following changes must be made in the BIOS settings: - AMD CPU: Virtualization or SVM must be enabled.

Note that there are further restrictions as well:

  • You can't run a VM-accelerated emulator inside another VM, such as a VM hosted by VirtualBox, VMWare, or Docker. You must run the emulator directly on your system hardware.
  • You can't run software that uses another virtualization technology at the same time that you run the accelerated emulator. For example, VirtualBox, VMWare, and Docker currently use a different virtualization technology, so you can't run them at the same time as the accelerated emulator.

Some more info: Android Emulator - AMD Processor & Hyper-V Support

This recommendation did not help either:

Please note: More recent versions of the emulator (27.2.8, 27.3.0, or later), require an emulator flag while the feature is in the preview. To do this, create or edit the file C:\Users\.android\advancedFeatures.ini and add the line “WindowsHypervisorPlatform = on”, or start the emulator from the command line with “-feature WindowsHypervisorPlatform”.

Alter user defined type in SQL Server

1.Rename the old UDT,
2.Execute query , 3.Drop the old UDT.

Refresh or force redraw the fragment

I am using remove and replace both for refreshing content of Fragment like

final FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();

ASP.NET Identity reset password


This was the original answer. It does work, but has a problem. What if AddPassword fails? The user is left without a password.

The original answer: we can use three lines of code:

UserManager<IdentityUser> userManager = 
    new UserManager<IdentityUser>(new UserStore<IdentityUser>());


userManager.AddPassword(userId, newPassword);

See also:

Now Recommended

It's probably better to use the answer that EdwardBrey proposed and then DanielWright later elaborated with a code sample.

Where's the IE7/8/9/10-emulator in IE11 dev tools?

I posted an answer to this already when someone else asked the same question (see How to bring back "Browser mode" in IE11?).

Read my answer there for a fuller explaination, but in short:

  • They removed it deliberately, because compat mode is not actually really very good for testing compatibility.

  • If you really want to test for compatibility with any given version of IE, you need to test in a real copy of that IE version. MS provide free VMs on for you to use for this purpose.

  • The only way to get compat mode in IE11 is to set the X-UA-Compatible header. When you have this and the site defaults to compat mode, you will be able to set the mode in dev tools, but only between edge or the specified compat mode; other modes will still not be available.

What is the 'pythonic' equivalent to the 'fold' function from functional programming?

Starting Python 3.8, and the introduction of assignment expressions (PEP 572) (:= operator), which gives the possibility to name the result of an expression, we can use a list comprehension to replicate what other languages call fold/foldleft/reduce operations:

Given a list, a reducing function and an accumulator:

items = [1, 2, 3, 4, 5]
f = lambda acc, x: acc * x
accumulator = 1

we can fold items with f in order to obtain the resulting accumulation:

[accumulator := f(accumulator, x) for x in items]
# accumulator = 120

or in a condensed formed:

acc = 1; [acc := acc * x for x in [1, 2, 3, 4, 5]]
# acc = 120

Note that this is actually also a "scanleft" operation as the result of the list comprehension represents the state of the accumulation at each step:

acc = 1
scanned = [acc := acc * x for x in [1, 2, 3, 4, 5]]
# scanned = [1, 2, 6, 24, 120]
# acc = 120

linq query to return distinct field values from a list of objects

If just want to user pure Linq, you can use groupby:

List<obj> distinct =
  objs.GroupBy(car => car.typeID).Select(g => g.First()).ToList();

If you want a method to be used all across the app, similar to what MoreLinq does:

public static IEnumerable<TSource> DistinctBy<TSource, TKey>
    (this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
    HashSet<TKey> seenKeys = new HashSet<TKey>();
    foreach (TSource element in source)
        if (!seenKeys.Contains(keySelector(element)))
            yield return element;

Using this method to find the distinct values using just the Id property, you could use:

var query = objs.DistinctBy(p => p.TypeId);

you can use multiple properties:

var query = objs.DistinctBy(p => new { p.TypeId, p.Name });