# Programs & Examples On #Ultrawingrid

WinGrid™ is a component of the Infragistics NetAdvantage suite. It is a hierarchical data grid control with full support for bound and unbound data display that surpasses other .NET grids on the market and shifts your data-driven WinForms app into a new realm of more productive possibilities.

### How to work with complex numbers in C?

``````#include <stdio.h>      /* Standard Library of Input and Output */
#include <complex.h>    /* Standard Library of Complex Numbers */

int main() {

double complex z1 = 1.0 + 3.0 * I;
double complex z2 = 1.0 - 4.0 * I;

printf("Working with complex numbers:\n\v");

printf("Starting values: Z1 = %.2f + %.2fi\tZ2 = %.2f %+.2fi\n", creal(z1), cimag(z1), creal(z2), cimag(z2));

double complex sum = z1 + z2;
printf("The sum: Z1 + Z2 = %.2f %+.2fi\n", creal(sum), cimag(sum));

double complex difference = z1 - z2;
printf("The difference: Z1 - Z2 = %.2f %+.2fi\n", creal(difference), cimag(difference));

double complex product = z1 * z2;
printf("The product: Z1 x Z2 = %.2f %+.2fi\n", creal(product), cimag(product));

double complex quotient = z1 / z2;
printf("The quotient: Z1 / Z2 = %.2f %+.2fi\n", creal(quotient), cimag(quotient));

double complex conjugate = conj(z1);
printf("The conjugate of Z1 = %.2f %+.2fi\n", creal(conjugate), cimag(conjugate));

return 0;
}
``````

with:

`creal(z1)`: get the real part (for float `crealf(z1)`, for long double `creall(z1)`)

`cimag(z1)`: get the imaginary part (for float `cimagf(z1)`, for long double `cimagl(z1)`)

Another important point to remember when working with complex numbers is that functions like `cos()`, `exp()` and `sqrt()` must be replaced with their complex forms, e.g. `ccos()`, `cexp()`, `csqrt()`.

### FIFO based Queue implementations?

Here is example code for usage of java's built-in FIFO queue:

``````public static void main(String[] args) {
System.out.println(myQ);   // 1 6 3
int first = myQ.poll();    // retrieve and remove the first element
System.out.println(first); // 1
System.out.println(myQ);   // 6 3
}
``````

Bring up the Package Manager Console in Visual Studio - it's in Tools / NuGet Package Manager / Package Manager Console. Then run the Install-Package command:

``````Install-Package Common.Logging -Version 1.2.0
``````

See the command reference for details.

Edit: In order to list versions of a package you can use the Get-Package command with the remote argument and a filter:

``````Get-Package -ListAvailable -Filter Common.Logging -AllVersions
``````

By pressing tab after the version option in the `Install-Package` command, you get a list of the latest available versions.

### How to upgrade R in ubuntu?

Since R is already installed, you should be able to upgrade it with this method. First of all, you may want to have the packages you installed in the previous version in the new one,so it is convenient to check this post. Then, follow the instructions from here

1. Open the `sources.list` file:

`````` sudo nano /etc/apt/sources.list
``````
2. Add a line with the source from where the packages will be retrieved. For example:

`````` deb https://cloud.r-project.org/bin/linux/ubuntu/ version/
``````

Replace `https://cloud.r-project.org` with whatever mirror you would like to use, and replace `version/` with whatever version of Ubuntu you are using (eg, `trusty/`, `xenial/`, and so on). If you're getting a "Malformed line error", check to see if you have a space between `/ubuntu/` and `version/`.

3. Fetch the secure APT key:

`````` gpg --keyserver keyserver.ubuntu.com --recv-key E298A3A825C0D65DFD57CBB651716619E084DAB9
``````

or

``````    gpg --hkp://keyserver keyserver.ubuntu.com:80 --recv-key E298A3A825C0D65DFD57CBB651716619E084DAB9
``````

`````` gpg -a --export E084DAB9 | sudo apt-key add -
``````

`````` sudo apt-get update && sudo apt-get upgrade
``````
3. Install the new version

`````` sudo apt-get install r-base-dev
``````
4. Recover your old packages following the solution that best suits to you (see this). For instance, to recover all the packages (not only those from CRAN) the idea is:

-- copy the packages from `R-oldversion/library` to `R-newversion/library`, (do not overwrite a package if it already exists in the new version!).

-- Run the R command `update.packages(checkBuilt=TRUE, ask=FALSE)`.

### Reading file from Workspace in Jenkins with Groovy script

As mentioned in a different post Read .txt file from workspace groovy script in Jenkins I was struggling to make it work for the pom modules for a file in the workspace, in the Extended Choice Parameter. Here is my solution with the printlns:

``````import groovy.util.XmlSlurper
import java.util.Map
import jenkins.*
import jenkins.model.*
import hudson.*
import hudson.model.*

try{
//get Jenkins instance
def jenkins = Jenkins.instance
//get job Item
def item = jenkins.getItemByFullName("The_JOB_NAME")
println item
// get workspacePath for the job Item
def workspacePath = jenkins.getWorkspaceFor (item)
println workspacePath

def file = new File(workspacePath.toString()+"\\pom.xml")
def pomFile = new XmlSlurper().parse(file)
def pomModules = pomFile.modules.children().join(",")
return pomModules
} catch (Exception ex){
println ex.message
}
``````

### Java integer list

If you want to rewrite a line on console, print a control character `\r` (carriage return).

``````List<Integer> myCoords = new ArrayList<Integer>();
Iterator<Integer> myListIterator = myCoords.iterator();
while (myListIterator.hasNext()) {
Integer coord = myListIterator.next();
System.out.print("\r");
System.out.print(coord);
}
``````

### How to conclude your merge of a file?

Check status (`git status`) of your repository. Every unmerged file (after you resolve conficts by yourself) should be added (`git add`), and if there is no unmerged file you should `git commit`

### Writing JSON object to a JSON file with fs.writeFileSync

When sending data to a web server, the data has to be a string (here). You can convert a JavaScript object into a string with `JSON.stringify()`. Here is a working example:

``````var fs = require('fs');

var originalNote = {
title: 'Meeting',
description: 'Meeting John Doe at 10:30 am'
};

var originalNoteString = JSON.stringify(originalNote);

fs.writeFileSync('notes.json', originalNoteString);

var note = JSON.parse(noteString);

console.log(`TITLE: \${note.title} DESCRIPTION: \${note.description}`);
``````

Hope it could help.

### I can't install intel HAXM

I think your problem was that you thought that the installer in Android SDK Manager would actually INSTALL the Intel HAXM. But the hook is that it WILL NOT INSTALL it. What it does is extracts the files needed for (really) install Intel HAXM.

I found that out when I got the same problem and then read this in Intel's web page:

... Other steps ...

5) The SDK Manager will download the installer to the "extras" directory, under the main SDK directory. Even though the SDK manager says "Installed" it actually means that the Intel HAXM executable was downloaded. You will still need to run the installer from the "extras" directory to get it installed.

6) Run the installer inside the /sdk/extras/intel/Hardware_Accelerated_Execution_Manager/ directory and follow the installation instructions for your platform.

So all I needed to do was go to folder where my Android SDK was, opened that folder (`sdk_location/sdk/extras/intel/Hardware_Accelerated_Execution_Manager`) and run the `silent_install.bat`.

After this when I launched my emulator, it said this:

HAXM is working and emulator runs fast virt mode

and everything works as should!

You can also use some useful parameters with silent_install.bat:

• -v Print HAXM version
• -c Check VT/NX capability of the platform
• -h Print usage

### Verify if file exists or not in C#

You wrote asp.net - are you looking to upload a file?
if so you can use the html

<input type="file" ...

### Take a char input from the Scanner

There are three ways to approach this problem:

• Call `next()` on the Scanner, and extract the first character of the String (e.g. `charAt(0)`) If you want to read the rest of the line as characters, iterate over the remaining characters in the String. Other answers have this code.

• Use `setDelimiter("")` to set the delimiter to an empty string. This will cause `next()` to tokenize into strings that are exactly one character long. So then you can repeatedly call `next().charAt(0)` to iterate the characters. You can then set the delimiter to its original value and resume scanning in the normal way!

• Use the Reader API instead of the Scanner API. The `Reader.read()` method delivers a single character read from the input stream. For example:

``````Reader reader = new InputStreamReader(System.in);
if (ch != -1) {  // check for EOF
// we have a character ...
}
``````

When you read from the console via `System.in`, the input is typically buffered by the operating system, and only "released" to the application when the user types ENTER. So if you intend your application to respond to individual keyboard strokes, this is not going to work. You would need to do some OS-specific native code stuff to turn off or work around line-buffering for console at the OS level.

Reference:

### Proper way to make HTML nested list?

Option 2 is correct.

The nested list should be inside a `<li>` element of the list in which it is nested.

Link to the W3C Wiki on Lists (taken from comment below): HTML Lists Wiki.

Link to the HTML5 W3C `ul` spec: HTML5 `ul`. Note that a `ul` element may contain exactly zero or more `li` elements. The same applies to HTML5 `ol`. The description list (HTML5 `dl`) is similar, but allows both `dt` and `dd` elements.

More Notes:

• `dl` = definition list.
• `ol` = ordered list (numbers).
• `ul` = unordered list (bullets).

### nodejs get file name from absolute path?

Use the `basename` method of the `path` module:

``````path.basename('/foo/bar/baz/asdf/quux.html')
// returns
'quux.html'
``````

Here is the documentation the above example is taken from.

### jQuery selector to get form by name

You have no combinator (space, `>`, `+`...) so no children will get involved, ever.

However, you could avoid the need for jQuery by using an `ID` and `getElementById`, or you could use the old `getElementsByName("frmSave")[0]` or the even older `document.forms['frmSave']`. jQuery is unnecessary here.

### How do I insert an image in an activity with android studio?

When you have image into yours drawable gallery then you just need to pick the option of image view pick and drag into app activity you want to show and select the required image.

### Rearrange columns using cut

Expanding on the answer from @Met, also using Perl:
If the input and output are TAB-delimited:

``````perl -F'\t' -lane 'print join "\t", @F[1, 0]' in_file
``````

If the input and output are whitespace-delimited:

``````perl -lane 'print join " ", @F[1, 0]' in_file
``````

Here,
`-e` tells Perl to look for the code inline, rather than in a separate script file,
`-n` reads the input 1 line at a time,
`-l` removes the input record separator (`\n` on *NIX) after reading the line (similar to `chomp`), and add output record separator (`\n` on *NIX) to each `print`,
`-a` splits the input line on whitespace into array `@F`,
`-F'\t'` in combination with `-a` splits the input line on TABs, instead of whitespace into array `@F`.

`@F[1, 0]` is the array made up of the 2nd and 1st elements of array `@F`, in this order. Remember that arrays in Perl are zero-indexed, while fields in `cut` are 1-indexed. So fields in `@F[0, 1]` are the same fields as the ones in `cut -f1,2`.

Note that such notation enables more flexible manipulation of input than in some other answers posted above (which are fine for a simple task). For example:

``````# reverses the order of fields:
perl -F'\t' -lane 'print join "\t", reverse @F' in_file

# prints last and first fields only:
perl -F'\t' -lane 'print join "\t", @F[-1, 0]' in_file
``````

### Getting execute permission to xp_cmdshell

To expand on what has been provided for automatically exporting data as csv to a network share via SQL Server Agent.

(1) Enable the xp_cmdshell procedure:

``````-- To allow advanced options to be changed.
EXEC sp_configure 'show advanced options', 1
RECONFIGURE
GO

-- Enable the xp_cmdshell procedure
EXEC sp_configure 'xp_cmdshell', 1
RECONFIGURE
GO
``````

(2) Create a login 'Domain\TestUser' (windows user) for the non-sysadmin user that has public access to the master database. Done through user mapping

(3) Give log on as batch job: Navigate to Local Security Policy -> Local Policies -> User Rights Assignment. Add user to "Log on as a batch job"

(4) Give read/write permissions to network folder for domain\user

(5) Grant EXEC permission on the xp_cmdshell stored procedure:

``````GRANT EXECUTE ON xp_cmdshell TO [Domain\TestUser]
``````

(6) Create a proxy account that xp_cmdshell will be run under using sp_xp_cmdshell_proxy_account

``````EXEC sp_xp_cmdshell_proxy_account 'Domain\TestUser', 'password_for_domain_user'
``````

(7) If the sp_xp_cmdshell_proxy_account command doesn't work, manually create it

``````create credential ##xp_cmdshell_proxy_account## with identity = 'Domain\DomainUser', secret = 'password'
``````

(8) Enable SQL Server Agent. Open SQL Server Configuration Manager, navigate to SQL Server Services, enable SQL Server Agent.

(9) Create automated job. Open SSMS, select SQL Server Agent, then right-click jobs and click "New Job".

(10) Select "Owner" as your created user. Select "Steps", make "type" = T-SQL. Fill out command field similar to below. Set delimiter as ','

``````EXEC master..xp_cmdshell 'SQLCMD -q "select * from master" -o file.csv -s ","
``````

(11) Fill out schedules accordingly.

### How to check if Receiver is registered in Android?

I am not sure the API provides directly an API, if you consider this thread:

I was wondering the same thing.
In my case I have a `BroadcastReceiver` implementation that calls `Context#unregisterReceiver(BroadcastReceiver)` passing itself as the argument after handling the Intent that it receives.
There is a small chance that the receiver's `onReceive(Context, Intent)` method is called more than once, since it is registered with multiple `IntentFilters`, creating the potential for an `IllegalArgumentException` being thrown from `Context#unregisterReceiver(BroadcastReceiver)`.

In my case, I can store a private synchronized member to check before calling `Context#unregisterReceiver(BroadcastReceiver)`, but it would be much cleaner if the API provided a check method.

### how do I create an array in jquery?

Here is the clear working example:

``````//creating new array
var custom_arr1 = [];

//storing value in array
custom_arr1.push("test");
custom_arr1.push("test1");

//output will be  test,test1
``````

### Apply CSS style attribute dynamically in Angular JS

Simply do this:

_x000D_
_x000D_
``<div ng-style="{'background-color': '{{myColorVariable}}', height: '2rem'}"></div>``
_x000D_
_x000D_
_x000D_

### How to change a css class style through Javascript?

``````<!DOCTYPE html>
<html>
<script>
return "par" ;
});
});
</script>
<style>
.par {
color: blue;
}
</style>
<body>
<div class="test">This is a paragraph.</div>
</body>
</html>
``````

### HTML5 Video Stop onClose

To save hours of coding time, use a jquery plug-in already optimized for embedded video iframes.

I spent a couple days trying to integrate Vimeo's moogaloop API with jquery tools unsuccessfully. See this list for a handful of easier options.

### Get Enum from Description attribute

The solution works good except if you have a Web Service.

You would need to do the Following as the Description Attribute is not serializable.

``````[DataContract]
public enum ControlSelectionType
{
[EnumMember(Value = "Not Applicable")]
NotApplicable = 1,
[EnumMember(Value = "Single Select Radio Buttons")]
[EnumMember(Value = "Completely Different Display Text")]
SingleSelectDropDownList = 3,
}

{
EnumMemberAttribute attribute = value.GetType()
.GetField(value.ToString())
.GetCustomAttributes(typeof(EnumMemberAttribute), false)
.SingleOrDefault() as EnumMemberAttribute;
return attribute == null ? value.ToString() : attribute.Value;
}
``````

### How to unpackage and repackage a WAR file

Adapting from the above answers, this works for Tomcat, but can be adapted for JBoss as well or any container:

``````sudo -u tomcat /opt/tomcat/bin/shutdown.sh
cd /opt/tomcat/webapps
sudo mkdir tmp; cd tmp
sudo jar -xvf ../myapp.war
#make edits...
sudo vi WEB-INF/classes/application.properties
#end of making edits
sudo jar -cvf myapp0.0.1.war *
sudo cp myapp0.0.1.war ..
cd ..
sudo chown tomcat:tomcat myapp0.0.1.war
sudo rm -rf tmp
sudo -u tomcat /opt/tomcat/bin/startup.sh
``````

### Java: How to convert List to Map

I like Kango_V's answer, but I think it's too complex. I think this is simpler - maybe too simple. If inclined, you could replace String with a Generic marker, and make it work for any Key type.

``````public static <E> Map<String, E> convertListToMap(Collection<E> sourceList, ListToMapConverterInterface<E> converterInterface) {
Map<String, E> newMap = new HashMap<String, E>();
for( E item : sourceList ) {
newMap.put( converterInterface.getKeyForItem( item ), item );
}
return newMap;
}

public interface ListToMapConverterInterface<E> {
public String getKeyForItem(E item);
}
``````

Used like this:

``````        Map<String, PricingPlanAttribute> pricingPlanAttributeMap = convertListToMap( pricingPlanAttributeList,
new ListToMapConverterInterface<PricingPlanAttribute>() {

@Override
public String getKeyForItem(PricingPlanAttribute item) {
return item.getFullName();
}
} );
``````

### Vue.js unknown custom element

OK, this error may seem obvious, but one day I was looking for an answer JUST TO FOUND OUT THAT I HAD 2 times COMPONENTS declared. it was driving me nuts as VueJS does not complain at all when you declare it 2 times, obvious I had a lot of code in between, and when I added a new component, I placed the declaration in the top, while I also had one close to the bottom. So next time looks for this first, saves a lot of time

### NoSQL Use Case Scenarios or WHEN to use NoSQL

It really is an "it depends" kinda question. Some general points:

• NoSQL is typically good for unstructured/"schemaless" data - usually, you don't need to explicitly define your schema up front and can just include new fields without any ceremony
• NoSQL typically favours a denormalised schema due to no support for JOINs per the RDBMS world. So you would usually have a flattened, denormalized representation of your data.
• Using NoSQL doesn't mean you could lose data. Different DBs have different strategies. e.g. MongoDB - you can essentially choose what level to trade off performance vs potential for data loss - best performance = greater scope for data loss.
• It's often very easy to scale out NoSQL solutions. Adding more nodes to replicate data to is one way to a) offer more scalability and b) offer more protection against data loss if one node goes down. But again, depends on the NoSQL DB/configuration. NoSQL does not necessarily mean "data loss" like you infer.
• IMHO, complex/dynamic queries/reporting are best served from an RDBMS. Often the query functionality for a NoSQL DB is limited.
• It doesn't have to be a 1 or the other choice. My experience has been using RDBMS in conjunction with NoSQL for certain use cases.
• NoSQL DBs often lack the ability to perform atomic operations across multiple "tables".

You really need to look at and understand what the various types of NoSQL stores are, and how they go about providing scalability/data security etc. It's difficult to give an across-the-board answer as they really are all different and tackle things differently.

For MongoDb as an example, check out their Use Cases to see what they suggest as being "well suited" and "less well suited" uses of MongoDb.

### Linux: command to open URL in default browser

``````###1     Desktop's -or- Console use:
sensible-browser \$URL; # Opinion: best. Target preferred APP.
# My-Server translates to: w3m [options] [URL or filename]
## [ -z "\$BROWSER" ] && echo "Empty"
# Then, Set the BROWSER environment variable to your desired browser.

###2     Alternative
# Desktop (if [command-not-found] out-Dated)
x-www-browser http://tv.jimmylandstudios.xyz # firefox

###3     !- A Must Know -!
# Desktop (/usr/share/applications/*.desktop)
xdg-open \$URI # opens about anything on Linux (w/ .desktop file)
``````

### how to pass data in an hidden field from one jsp page to another?

The code from Alex works great. Just note that when you use request.getParameter you must use a request dispatcher

``````//Pass results back to the client
RequestDispatcher dispatcher =   getServletContext().getRequestDispatcher("TestPages/ServiceServlet.jsp");
dispatcher.forward(request, response);
``````

### C++: How to round a double to an int?

Casting to an `int` truncates the value. Adding `0.5` causes it to do proper rounding.

``````int y = (int)(x + 0.5);
``````

### Moment.js - how do I get the number of years since a date, not rounded up?

When you want to show years and the remaining days:

``````var m = moment(d.birthday.date, "DD.MM.YYYY");
var years = moment().diff(m, 'years', false);
var days = moment().diff(m.add(years, 'years'), 'days', false);
alert(years + ' years, ' + days + ' days');
``````

### How to change UINavigationBar background color from the AppDelegate

You can set UINavigation Background color by using this code in any view controller

``````self.navigationController.navigationBar.backgroundColor = [UIColor colorWithRed:10.0f/255.0f green:30.0f/255.0f blue:200.0f/255.0f alpha:1.0f];
``````

### How to see the values of a table variable at debug time in T-SQL?

I have come to the conclusion that this is not possible without any plugins.

### I forgot the password I entered during postgres installation

The `pg_hba.conf` (`C:\Program Files\PostgreSQL\9.3\data`) file has changed since these answers were given. What worked for me, in Windows, is to open the file and change the `METHOD` from `md5` to `trust`:

``````# TYPE  DATABASE        USER            ADDRESS                 METHOD

# IPv4 local connections:
host    all             all             127.0.0.1/32            trust
# IPv6 local connections:
host    all             all             ::1/128                 trust
``````

Then, using pgAdmin III, I logged in using no password and changed user `postgres'` password by going to `File -> Change Password`

### How do I check if an array includes a value in JavaScript?

As others have mentioned you can use `Array.indexOf`, but it isn't available in all browsers. Here's the code from https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf to make it work the same in older browsers.

indexOf is a recent addition to the ECMA-262 standard; as such it may not be present in all browsers. You can work around this by inserting the following code at the beginning of your scripts, allowing use of indexOf in implementations which do not natively support it. This algorithm is exactly the one specified in ECMA-262, 5th edition, assuming Object, TypeError, Number, Math.floor, Math.abs, and Math.max have their original value.

``````if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
"use strict";
if (this == null) {
throw new TypeError();
}
var t = Object(this);
var len = t.length >>> 0;
if (len === 0) {
return -1;
}
var n = 0;
if (arguments.length > 1) {
n = Number(arguments[1]);
if (n != n) { // shortcut for verifying if it's NaN
n = 0;
} else if (n != 0 && n != Infinity && n != -Infinity) {
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
}
if (n >= len) {
return -1;
}
var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
for (; k < len; k++) {
if (k in t && t[k] === searchElement) {
return k;
}
}
return -1;
}
}
``````

### NPM Install Error:Unexpected end of JSON input while parsing near '...nt-webpack-plugin":"0'

These commands worked for me

``````sudo npm cache clean --force

sudo npm cache verify

sudo npm i npm@latest -g
``````

### bootstrap responsive table content wrapping

EDIT

I think the reason that your table is not responsive to start with was you did not wrap in `.container`, `.row` and `.col-md-x` classes like this one

``````<div class="container">
<div class="row">
<div class="col-md-12">
<!-- or use any other number .col-md- -->
<div class="table-responsive">
<div class="table">
</div>
</div>
</div>
</div>
</div>
``````

With this, you can still use `<p>` tags and even make it responsive.

Please see the Bootply example here

### How do I set the time zone of MySQL?

You have to set up the your location timezone. So that follow below process
Open your MSQLWorkbench write a simple sql command like this;

``````select now();
``````

And also your url could be like this;

``````url = "jdbc:mysql://localhost:3306/your_database_name?serverTimezone=UTC";
``````

### Get child node index

ES—Shorter

``````[...element.parentNode.children].indexOf(element);
``````

The spread Operator is a shortcut for that

### How do I get the day of week given a date?

This is a solution if the date is a datetime object.

``````import datetime
def dow(date):
days=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"]
dayNumber=date.weekday()
print days[dayNumber]
``````

### String to Dictionary in Python

This data is JSON! You can deserialize it using the built-in `json` module if you're on Python 2.6+, otherwise you can use the excellent third-party `simplejson` module.

``````import json    # or `import simplejson as json` if on Python < 2.6

json_string = u'{ "id":"123456789", ... }'
obj = json.loads(json_string)    # obj now contains a dict of the data
``````

### Waiting for background processes to finish before exiting script

A while ago, I faced a similar problem: from a Tcl script, launch a number of processes, then wait for all of them to finish. Here is a demo script I wrote to solve this problem.

#### main.tcl

``````#!/usr/bin/env tclsh

# Launches many processes and wait for them to finish.
# This script will works on systems that has the ps command such as
# BSD, Linux, and OS X

package require Tclx; # For process-management utilities

proc updatePidList {stat} {
global pidList
global allFinished

# Parse the process ID of the just-finished process
lassign \$stat processId howProcessEnded exitCode

# Remove this process ID from the list of process IDs
set pidList [lindex [intersect3 \$pidList \$processId] 0]
set processCount [llength \$pidList]

# Occasionally, a child process quits but the signal was lost. This
# block of code will go through the list of remaining process IDs
# and remove those that has finished
set updatedPidList {}
foreach pid \$pidList {
if {![catch {exec ps \$pid} errmsg]} {
lappend updatedPidList \$pid
}
}

set pidList \$updatedPidList

# Show the remaining processes
if {\$processCount > 0} {
puts "Waiting for [llength \$pidList] processes"
} else {
set allFinished 1
puts "All finished"
}
}

# A signal handler that gets called when a child process finished.
# This handler needs to exit quickly, so it delegates the real works to
# the proc updatePidList
proc childTerminated {} {
# Restart the handler
signal -restart trap SIGCHLD childTerminated

# Update the list of process IDs
while {![catch {wait -nohang} stat] && \$stat ne {}} {
after idle [list updatePidList \$stat]
}
}

#
# Main starts here
#

puts "Main begins"
set NUMBER_OF_PROCESSES_TO_LAUNCH 10
set pidList {}
set allFinished 0

# When a child process exits, call proc childTerminated
signal -restart trap SIGCHLD childTerminated

# Spawn many processes
for {set i 0} {\$i < \$NUMBER_OF_PROCESSES_TO_LAUNCH} {incr i} {
set childId [exec tclsh child.tcl \$i &]
puts "child #\$i, pid=\$childId"
lappend pidList \$childId
after 1000
}

# Do some processing
puts "list of processes: \$pidList"
puts "Waiting for child processes to finish"
# Do some more processing if required

# After all done, wait for all to finish before exiting
vwait allFinished

puts "Main ends"
``````

#### child.tcl

``````#!/usr/bin/env tclsh
# child script: simulate some lengthy operations

proc randomInteger {min max} {
return [expr int(rand() * (\$max - \$min + 1) * 1000 + \$min)]
}

set duration [randomInteger 10 30]
puts "  child #\$argv runs for \$duration miliseconds"
after \$duration
puts "  child #\$argv ends"
``````

#### Sample output for running main.tcl

``````Main begins
child #0, pid=64525
child #0 runs for 17466 miliseconds
child #1, pid=64526
child #1 runs for 14181 miliseconds
child #2, pid=64527
child #2 runs for 10856 miliseconds
child #3, pid=64528
child #3 runs for 7464 miliseconds
child #4, pid=64529
child #4 runs for 4034 miliseconds
child #5, pid=64531
child #5 runs for 1068 miliseconds
child #6, pid=64532
child #6 runs for 18571 miliseconds
child #5 ends
child #7, pid=64534
child #7 runs for 15374 miliseconds
child #8, pid=64535
child #8 runs for 11996 miliseconds
child #4 ends
child #9, pid=64536
child #9 runs for 8694 miliseconds
list of processes: 64525 64526 64527 64528 64529 64531 64532 64534 64535 64536
Waiting for child processes to finish
Waiting for 8 processes
Waiting for 8 processes
child #3 ends
Waiting for 7 processes
child #2 ends
Waiting for 6 processes
child #1 ends
Waiting for 5 processes
child #0 ends
Waiting for 4 processes
child #9 ends
Waiting for 3 processes
child #8 ends
Waiting for 2 processes
child #7 ends
Waiting for 1 processes
child #6 ends
All finished
Main ends
``````

### iOS - UIImageView - how to handle UIImage image orientation

This method first checks the current orientation of UIImage and then it changes the orientation in a clockwise way and return UIImage.You can show this image as

self.imageView.image = rotateImage(currentUIImage)

``````   func rotateImage(image:UIImage)->UIImage
{
var rotatedImage = UIImage();
switch image.imageOrientation
{
case UIImageOrientation.Right:
rotatedImage = UIImage(CGImage:image.CGImage!, scale: 1, orientation:UIImageOrientation.Down);

case UIImageOrientation.Down:
rotatedImage = UIImage(CGImage:image.CGImage!, scale: 1, orientation:UIImageOrientation.Left);

case UIImageOrientation.Left:
rotatedImage = UIImage(CGImage:image.CGImage!, scale: 1, orientation:UIImageOrientation.Up);

default:
rotatedImage = UIImage(CGImage:image.CGImage!, scale: 1, orientation:UIImageOrientation.Right);
}
return rotatedImage;
}
``````

#### Swift 4 version

``````func rotateImage(image:UIImage) -> UIImage
{
var rotatedImage = UIImage()
switch image.imageOrientation
{
case .right:
rotatedImage = UIImage(cgImage: image.cgImage!, scale: 1.0, orientation: .down)

case .down:
rotatedImage = UIImage(cgImage: image.cgImage!, scale: 1.0, orientation: .left)

case .left:
rotatedImage = UIImage(cgImage: image.cgImage!, scale: 1.0, orientation: .up)

default:
rotatedImage = UIImage(cgImage: image.cgImage!, scale: 1.0, orientation: .right)
}

return rotatedImage
}
``````

### How to use the new Material Design Icon themes: Outlined, Rounded, Two-Tone and Sharp?

If you already have material-icons working in your web project, just need to update your reference in the html file and the used class for icons:

html reference:

Before

``````<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet" />
``````

After

``````<link href="https://fonts.googleapis.com/css?family=Material+Icons|Material+Icons+Outlined|Material+Icons+Two+Tone|Material+Icons+Round|Material+Icons+Sharp"
rel="stylesheet" />
``````

material icons class:

After that just check wich className are you using:

Before:

``````<i className="material-icons">weekend</i>
``````

After:

``````<i className="material-icons-outlined">weekend</i>
``````

that works for me... Pura vida!

### PostgreSQL : cast string to date DD/MM/YYYY

The documentation says

The output format of the date/time types can be set to one of the four styles ISO 8601, SQL (Ingres), traditional POSTGRES (Unix date format), or German. The default is the ISO format.

So this particular format can be controlled with `postgres` date time output, eg:

``````t=# select now();
now
-------------------------------
2017-11-29 09:15:25.348342+00
(1 row)

t=# set datestyle to DMY, SQL;
SET
t=# select now();
now
-------------------------------
29/11/2017 09:15:31.28477 UTC
(1 row)

t=# select now()::date;
now
------------
29/11/2017
(1 row)
``````

Mind that as @Craig mentioned in his answer, changing `datestyle` will also (and in first turn) change the way postgres parses date.

### How can I merge two MySQL tables?

``````INSERT
INTO    first_table f
SELECT  *
FROM    second_table s
ON DUPLICATE KEY
UPDATE
s.column1 = DO_WHAT_EVER_MUST_BE_DONE_ON_KEY_CLASH(f.column1)
``````

### Typescript - multidimensional array initialization

If you want to do it typed:

``````class Something {

areas: Area[][];

constructor() {
this.areas = new Array<Array<Area>>();
for (let y = 0; y <= 100; y++) {
let row:Area[]  = new Array<Area>();
for (let x = 0; x <=100; x++){
row.push(new Area(x, y));
}
this.areas.push(row);
}
}
}
``````

### Make more than one chart in same IPython Notebook cell

Make the multiple axes first and pass them to the Pandas plot function, like:

``````fig, axs = plt.subplots(1,2)

df['korisnika'].plot(ax=axs[0])
df['osiguranika'].plot(ax=axs[1])
``````

It still gives you 1 figure, but with two different plots next to each other.

### how to use javascript Object.defineProperty

defineProperty is a method on Object which allow you to configure the properties to meet some criterias. Here is a simple example with an employee object with two properties firstName & lastName and append the two properties by overriding the toString method on the object.

``````var employee = {
firstName: "Jameel",
lastName: "Moideen"
};
employee.toString=function () {
return this.firstName + " " + this.lastName;
};
console.log(employee.toString());
``````

You will get Output as : Jameel Moideen

I am going to change the same code by using defineProperty on the object

``````var employee = {
firstName: "Jameel",
lastName: "Moideen"
};
Object.defineProperty(employee, 'toString', {
value: function () {
return this.firstName + " " + this.lastName;
},
writable: true,
enumerable: true,
configurable: true
});
console.log(employee.toString());
``````

The first parameter is the name of the object and then second parameter is name of the property we are adding , in our case it’s toString and then the last parameter is json object which have a value going to be a function and three parameters writable,enumerable and configurable.Right now I just declared everything as true.

If u run the example you will get Output as : Jameel Moideen

Let’s understand why we need the three properties such as writable,enumerable and configurable.

writable

One of the very annoying part of the javascript is , if you change the toString property to something else for example

if you run this again , everything gets breaks. Let’s change writable to false. If run the same again you will get the correct output as ‘Jameel Moideen’ . This property will prevent overwrite this property later.

enumerable

if you print all the keys inside the object , you can see all the properties including toString.

``````console.log(Object.keys(employee));
``````

if you set enumerable to false , you can hide toString property from everybody else. If run this again you will get firstName,lastName

configurable

if someone later redefined the object on later for example enumerable to true and run it. You can see toString property came again.

``````var employee = {
firstName: "Jameel",
lastName: "Moideen"
};
Object.defineProperty(employee, 'toString', {
value: function () {
return this.firstName + " " + this.lastName;
},
writable: false,
enumerable: false,
configurable: true
});

//change enumerable to false
Object.defineProperty(employee, 'toString', {

enumerable: true
});
employee.toString="changed";
console.log(Object.keys(employee));
``````

you can restrict this behavior by set configurable to false.

Orginal reference of this information is from my personal Blog

### Why is it common to put CSRF prevention tokens in cookies?

Besides the session cookie (which is kind of standard), I don't want to use extra cookies.

I found a solution which works for me when building a Single Page Web Application (SPA), with many AJAX requests. Note: I am using server side Java and client side JQuery, but no magic things so I think this principle can be implemented in all popular programming languages.

My solution without extra cookies is simple:

#### Client Side

Store the CSRF token which is returned by the server after a succesful login in a global variable (if you want to use web storage instead of a global thats fine of course). Instruct JQuery to supply a X-CSRF-TOKEN header in each AJAX call.

The main "index" page contains this JavaScript snippet:

``````// Intialize global variable CSRF_TOKEN to empty sting.
// This variable is set after a succesful login
window.CSRF_TOKEN = '';

// the supplied callback to .ajaxSend() is called before an Ajax request is sent
\$( document ).ajaxSend( function( event, jqXHR ) {
});
``````

#### Server Side

On successul login, create a random (and long enough) CSRF token, store this in the server side session and return it to the client. Filter certain (sensitive) incoming requests by comparing the X-CSRF-TOKEN header value to the value stored in the session: these should match.

Sensitive AJAX calls (POST form-data and GET JSON-data), and the server side filter catching them, are under a /dataservice/* path. Login requests must not hit the filter, so these are on another path. Requests for HTML, CSS, JS and image resources are also not on the /dataservice/* path, thus not filtered. These contain nothing secret and can do no harm, so this is fine.

``````@WebFilter(urlPatterns = {"/dataservice/*"})
...
String sessionCSRFToken = req.getSession().getAttribute("CSRFToken") != null ? (String) req.getSession().getAttribute("CSRFToken") : null;
resp.sendError(401);
} else
chain.doFilter(request, response);
}
``````

### how to drop database in sqlite?

To create a new database, just do sqlite_open(). To drop a database, delete the file.

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

Try `str_detect()` from the stringr package, which detects the presence or absence of a pattern in a string.

Here is an approach that also incorporates the `%>%` pipe and `filter()` from the dplyr package:

``````library(stringr)
library(dplyr)

CO2 %>%
filter(str_detect(Treatment, "non"))

Plant        Type  Treatment conc uptake
1    Qn1      Quebec nonchilled   95   16.0
2    Qn1      Quebec nonchilled  175   30.4
3    Qn1      Quebec nonchilled  250   34.8
4    Qn1      Quebec nonchilled  350   37.2
5    Qn1      Quebec nonchilled  500   35.3
...
``````

This filters the sample CO2 data set (that comes with R) for rows where the Treatment variable contains the substring "non". You can adjust whether `str_detect` finds fixed matches or uses a regex - see the documentation for the stringr package.

### Text File Parsing in Java

Have a look at these pages. They contain many open source CSV parsers. JSaPar is one of them.

### iOS how to set app icon and launch images

To save a bit time:

1) You can mark your app icon images all in finder and drag them into your Assets catalog all at once by dragging into one of the empty slots of the app icon imageset. When you hold your drag over the slot, several of the other slots look selected and when you drop those all will be filled up at once. Note that this works in XCode 8 (I haven't tried XCode 7), but in XCode 9 beta not yet.

2) The "Technical Q&A QA1686" apple documentation site has the sizes per app icon slot already calculated for you in a nice image and also contains the correct image names conventions.

### Converting list to numpy array

If you have a list of lists, you only needed to use ...

``````import numpy as np
...
npa = np.asarray(someListOfLists, dtype=np.float32)
``````

per this LINK in the scipy / numpy documentation. You just needed to define dtype inside the call to asarray.

### Creating a new user and password with Ansible

Mxx's answer is correct but you the python `crypt.crypt()` method is not safe when different operating systems are involved (related to glibc hash algorithm used on your system.)

For example, It won't work if your generate your hash from MacOS and run a playbook on linux. In such case , You can use passlib (`pip install passlib` to install locally).

``````from passlib.hash import md5_crypt
python -c 'import crypt; print md5_crypt.encrypt("This is my Password,salt="SomeSalt")'
'\$1\$SomeSalt\$UqddPX3r4kH3UL5jq5/ZI.'
``````

### How can I switch views programmatically in a view controller? (Xcode, iPhone)

If you want to present a new view in the same storyboard,

In CurrentViewController.m,

``````#import "YourViewController.h"

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
YourViewController *viewController = (YourViewController *)[storyboard instantiateViewControllerWithIdentifier:@"YourViewControllerIdentifier"];
[self presentViewController:viewController animated:YES completion:nil];
``````

To set identifier to a view controller, Open MainStoryBoard.storyboard. Select YourViewController View-> Utilities -> ShowIdentityInspector. There you can specify the identifier.

### How do I check the difference, in seconds, between two dates?

if you want to compute differences between two known dates, use `total_seconds` like this:

``````import datetime as dt

a = dt.datetime(2013,12,30,23,59,59)
b = dt.datetime(2013,12,31,23,59,59)

(b-a).total_seconds()
``````

86400.0

``````#note that seconds doesn't give you what you want:
(b-a).seconds
``````

0

### Regular expression that matches valid IPv6 addresses

The regex allows the use of leading zeros in the IPv4 parts.

Some Unix and Mac distros convert those segments into octals.

I suggest using `25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d` as an IPv4 segment.

### How can I account for period (AM/PM) using strftime?

You used `%H` (24 hour format) instead of `%I` (12 hour format).

### What's the difference between a POST and a PUT HTTP REQUEST?

HTTP PUT:

PUT puts a file or resource at a specific URI, and exactly at that URI. If there's already a file or resource at that URI, PUT replaces that file or resource. If there is no file or resource there, PUT creates one. PUT is idempotent, but paradoxically PUT responses are not cacheable.

HTTP 1.1 RFC location for PUT

HTTP POST:

POST sends data to a specific URI and expects the resource at that URI to handle the request. The web server at this point can determine what to do with the data in the context of the specified resource. The POST method is not idempotent, however POST responses are cacheable so long as the server sets the appropriate Cache-Control and Expires headers.

The official HTTP RFC specifies POST to be:

• Annotation of existing resources;
• Posting a message to a bulletin board, newsgroup, mailing list, or similar group of articles;
• Providing a block of data, such as the result of submitting a form, to a data-handling process;
• Extending a database through an append operation.

HTTP 1.1 RFC location for POST

Difference between POST and PUT:

The RFC itself explains the core difference:

The fundamental difference between the POST and PUT requests is reflected in the different meaning of the Request-URI. The URI in a POST request identifies the resource that will handle the enclosed entity. That resource might be a data-accepting process, a gateway to some other protocol, or a separate entity that accepts annotations. In contrast, the URI in a PUT request identifies the entity enclosed with the request -- the user agent knows what URI is intended and the server MUST NOT attempt to apply the request to some other resource. If the server desires that the request be applied to a different URI, it MUST send a 301 (Moved Permanently) response; the user agent MAY then make its own decision regarding whether or not to redirect the request.

Additionally, and a bit more concisely, RFC 7231 Section 4.3.4 PUT states (emphasis added),

4.3.4. PUT

The PUT method requests that the state of the target resource be `created` or `replaced` with the state defined by the representation enclosed in the request message payload.

Using the right method, unrelated aside:

One benefit of REST ROA vs SOAP is that when using HTTP REST ROA, it encourages the proper usage of the HTTP verbs/methods. So for example you would only use PUT when you want to create a resource at that exact location. And you would never use GET to create or modify a resource.

### Joining pairs of elements of a list

``````>>> lst =  ['abcd', 'e', 'fg', 'hijklmn', 'opq', 'r']
>>> print [lst[2*i]+lst[2*i+1] for i in range(len(lst)/2)]
['abcde', 'fghijklmn', 'opqr']
``````

### How to use jQuery to call an ASP.NET web service?

I don't know about that specific SharePoint web service, but you can decorate a page method or a web service with `<WebMethod()>` (in VB.NET) to ensure that it serializes to JSON. You can probably just wrap the method that webservice.asmx uses internally, in your own web service.

Dave Ward has a nice walkthrough on this.

### How to unzip a list of tuples into individual lists?

If you want a list of lists:

``````>>> [list(t) for t in zip(*l)]
[[1, 3, 8], [2, 4, 9]]
``````

If a list of tuples is OK:

``````>>> zip(*l)
[(1, 3, 8), (2, 4, 9)]
``````

### Add a user control to a wpf window

You probably need to add the namespace:

``````<Window x:Class="UserControlTest.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:UserControlTest"
Title="User Control Test" Height="300" Width="300">
<local:UserControl1 />
</Window>
``````

### Regular expression for first and last name

This seems to do the job for me:

``````[\S]{2,} [\S]{2,}( [\S]{2,})*
``````

### How do I declare an array of undefined or no initial size?

The way it's often done is as follows:

• allocate an array of some initial (fairly small) size;
• read into this array, keeping track of how many elements you've read;
• once the array is full, reallocate it, doubling the size and preserving (i.e. copying) the contents;
• repeat until done.

I find that this pattern comes up pretty frequently.

What's interesting about this method is that it allows one to insert `N` elements into an empty array one-by-one in amortized `O(N)` time without knowing `N` in advance.

### Better way to find index of item in ArrayList?

Use indexOf() method to find first occurrence of the element in the collection.

### How do I get a platform-dependent new line character?

You can use

``````System.getProperty("line.separator");
``````

to get the line separator

### Detect backspace and del on "input" event?

on android devices using chrome we can't detect a backspace. You can use workaround for it:

``````var oldInput = '',
newInput = '';

\$("#ID").keyup(function () {
newInput = \$('#ID').val();
if(newInput.length < oldInput.length){
//backspace pressed
}
oldInput = newInput;
})
``````

### HTML text-overflow ellipsis detection

The solution @ItaloBorssatto is perfect. But before looking at SO - I made my decision. Here it is :)

_x000D_
_x000D_
``````const elems = document.querySelectorAll('span');_x000D_
elems.forEach(elem => {_x000D_
checkEllipsis(elem);_x000D_
});_x000D_
_x000D_
function checkEllipsis(elem){_x000D_
const canvas = document.createElement('canvas');_x000D_
const ctx = canvas.getContext('2d');_x000D_
const styles = getComputedStyle(elem);_x000D_
ctx.font = `\${styles.fontWeight} \${styles.fontSize} \${styles.fontFamily}`;_x000D_
const widthTxt = ctx.measureText(elem.innerText).width;_x000D_
if (widthTxt > parseFloat(styles.width)){_x000D_
elem.style.color = 'red'_x000D_
}_x000D_
}``````
_x000D_
``````span.cat {_x000D_
display: block;_x000D_
border: 1px solid black;_x000D_
white-space: nowrap;_x000D_
width: 100px;_x000D_
overflow: hidden;_x000D_
text-overflow: ellipsis;_x000D_
}``````
_x000D_
`````` <span class="cat">Small Cat</span>_x000D_
<span class="cat">Looooooooooooooong Cat</span>``````
_x000D_
_x000D_
_x000D_

### Get URL query string parameters

For getting each node in the URI, you can use function `explode()` to \$_SERVER['REQUEST_URI']. If you want to get strings without knowing if it is passed or not. you may use the function I defined myself to get query parameters from \$_REQUEST (as it works both for POST and GET params).

``````function getv(\$key, \$default = '', \$data_type = '')
{
\$param = (isset(\$_REQUEST[\$key]) ? \$_REQUEST[\$key] : \$default);

if (!is_array(\$param) && \$data_type == 'int') {
\$param = intval(\$param);
}

return \$param;
}
``````

There might be some cases when we want to get query parameters converted into Integer type, so I added the third parameter to this function.

### Difference between Static methods and Instance methods

If state of a method is not supposed to be changed or its not going to use any instance variables.

You want to call method without instance.

If it only works on arguments provided to it.

Utility functions are good instance of static methods. i.e math.pow(), this function is not going to change the state for different values. So it is static.

You have to first obtain the Range object. Also, getCell() will not return the value of the cell but instead will return a Range object of the cell. So, use something on the lines of

``````function email() {

// Opens SS by its ID

// Get the name of this SS

var name = ss.getName();  // Not necessary

// Read cell 1,1 * Line below does't work *

// var data = Range.getCell(0, 0);
var sheet = ss.getSheetByName('Sheet1'); // or whatever is the name of the sheet
var range = sheet.getRange(1,1);
var data = range.getValue();

}
``````

The hierarchy is Spreadsheet --> Sheet --> Range --> Cell.

### Eclipse No tests found using JUnit 5 caused by NoClassDefFoundError for LauncherFactory

I got the same problem after creating a new TestCase: Eclipse -> New -> JUnit Test Case. It creates a class without access level modifier. I could solve the problem by just putting a public before the class keyword.

### How can I check if a value is a json object?

i tried all of the suggested answers, nothing worked for me, so i had to use

``````jQuery.isEmptyObject()
``````

hoe that helps someone else out with this issue

### How to create a new instance from a class object in Python

If you have a module with a class you want to import, you can do it like this.

``````module = __import__(filename)
instance = module.MyClass()
``````

If you do not know what the class is named, you can iterate through the classes available from a module.

``````import inspect
module = __import__(filename)
for c in module.__dict__.values():
if inspect.isclass(c):
# You may need do some additional checking to ensure
# it's the class you want
instance = c()
``````

### What's the difference between map() and flatMap() methods in Java 8?

One line answer: `flatMap` helps to flatten a `Collection<Collection<T>>` into a `Collection<T>`. In the same way, it will also flatten an `Optional<Optional<T>>` into `Optional<T>`.

As you can see, with `map()` only:

• The intermediate type is `Stream<List<Item>>`
• The return type is `List<List<Item>>`

and with `flatMap()`:

• The intermediate type is `Stream<Item>`
• The return type is `List<Item>`

This is the test result from the code used right below:

``````-------- Without flatMap() -------------------------------
collect() returns: [[Laptop, Phone], [Mouse, Keyboard]]

-------- With flatMap() ----------------------------------
collect() returns: [Laptop, Phone, Mouse, Keyboard]
``````

Code used:

``````import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

public class Parcel {
String name;
List<String> items;

public Parcel(String name, String... items) {
this.name = name;
this.items = Arrays.asList(items);
}

public List<String> getItems() {
return items;
}

public static void main(String[] args) {
Parcel amazon = new Parcel("amazon", "Laptop", "Phone");
Parcel ebay = new Parcel("ebay", "Mouse", "Keyboard");
List<Parcel> parcels = Arrays.asList(amazon, ebay);

System.out.println("-------- Without flatMap() ---------------------------");
List<List<String>> mapReturn = parcels.stream()
.map(Parcel::getItems)
.collect(Collectors.toList());
System.out.println("\t collect() returns: " + mapReturn);

System.out.println("\n-------- With flatMap() ------------------------------");
List<String> flatMapReturn = parcels.stream()
.map(Parcel::getItems)
.flatMap(Collection::stream)
.collect(Collectors.toList());
System.out.println("\t collect() returns: " + flatMapReturn);
}
}
``````

### How to make a drop down list in yii2?

This is about generating data, and so is more properly done from the model. Imagine if you ever wanted to change the way data is displayed in the drop-down box, say add a surname or something. You'd have to find every drop-down box and change the `arrayHelper`. I use a function in my models to return the data for a dropdown, so I don't have to repeat code in views. It also has the advantage that I can specify filter here and have them apply to every dropdown created from this model;

``````/* Model Standard.php */

public function getDropdown(){
return ArrayHelper::map(self::find()->all(), 's_id', 'name'));
}
``````

You can use this in your view file like this;

``````echo \$form->field(\$model, 'attribute')
->dropDownList(
\$model->dropDown
);
``````

### What's the correct way to communicate between controllers in AngularJS?

I've actually started using Postal.js as a message bus between controllers.

There are lots of benefits to it as a message bus such as AMQP style bindings, the way postal can integrate w/ iFrames and web sockets, and many more things.

I used a decorator to get Postal set up on `\$scope.\$bus`...

``````angular.module('MyApp')
.config(function (\$provide) {
\$provide.decorator('\$rootScope', ['\$delegate', function (\$delegate) {
Object.defineProperty(\$delegate.constructor.prototype, '\$bus', {
get: function() {
var self = this;

return {
subscribe: function() {
var sub = postal.subscribe.apply(postal, arguments);

self.\$on('\$destroy',
function() {
sub.unsubscribe();
});
},
channel: postal.channel,
publish: postal.publish
};
},
enumerable: false
});

return \$delegate;
}]);
});
``````

Here's a link to a blog post on the topic...
http://jonathancreamer.com/an-angular-event-bus-with-postal-js/

### How to create roles in ASP.NET Core and assign them to users?

In addition to Temi Lajumoke's answer, it's worth noting that after creating the required roles and assigning them to specific users in ASP.NET Core 2.1 MVC Web Application, after launching the application, you may encounter a method error, such as registering or managing an account:

InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Identity.UI.Services.IEmailSender' while attempting to activate 'WebApplication.Areas.Identity.Pages.Account.Manage.IndexModel'.

A similar error can be quickly corrected in the ConfigureServices method by adding the AddDefaultUI() method:

``````services.AddIdentity<IdentityUser, IdentityRole>()
``````

Check

and related topic on github:

And for assigning role to specific user could be used IdentityUser class instead of ApplicationUser.

### How do I expire a PHP session after 30 minutes?

You should implement a session timeout of your own. Both options mentioned by others (session.gc_maxlifetime and session.cookie_lifetime) are not reliable. I'll explain the reasons for that.

First:

session.gc_maxlifetime specifies the number of seconds after which data will be seen as 'garbage' and cleaned up. Garbage collection occurs during session start.

But the garbage collector is only started with a probability of session.gc_probability divided by session.gc_divisor. And using the default values for those options (1 and 100 respectively), the chance is only at 1%.

Well, you could simply adjust these values so that the garbage collector is started more often. But when the garbage collector is started, it will check the validity for every registered session. And that is cost-intensive.

Furthermore, when using PHP's default session.save_handler files, the session data is stored in files in a path specified in session.save_path. With that session handler, the age of the session data is calculated on the file's last modification date and not the last access date:

Note: If you are using the default file-based session handler, your filesystem must keep track of access times (atime). Windows FAT does not so you will have to come up with another way to handle garbage collecting your session if you are stuck with a FAT filesystem or any other filesystem where atime tracking is not available. Since PHP 4.2.3 it has used mtime (modified date) instead of atime. So, you won't have problems with filesystems where atime tracking is not available.

So it additionally might occur that a session data file is deleted while the session itself is still considered as valid because the session data was not updated recently.

And second:

Yes, that's right. This only affects the cookie lifetime and the session itself may still be valid. But it's the server's task to invalidate a session, not the client. So this doesn't help anything. In fact, having session.cookie_lifetime set to `0` would make the session’s cookie a real session cookie that is only valid until the browser is closed.

Conclusion / best solution:

The best solution is to implement a session timeout of your own. Use a simple time stamp that denotes the time of the last activity (i.e. request) and update it with every request:

``````if (isset(\$_SESSION['LAST_ACTIVITY']) && (time() - \$_SESSION['LAST_ACTIVITY'] > 1800)) {
// last request was more than 30 minutes ago
session_unset();     // unset \$_SESSION variable for the run-time
session_destroy();   // destroy session data in storage
}
\$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
``````

Updating the session data with every request also changes the session file's modification date so that the session is not removed by the garbage collector prematurely.

You can also use an additional time stamp to regenerate the session ID periodically to avoid attacks on sessions like session fixation:

``````if (!isset(\$_SESSION['CREATED'])) {
\$_SESSION['CREATED'] = time();
} else if (time() - \$_SESSION['CREATED'] > 1800) {
// session started more than 30 minutes ago
session_regenerate_id(true);    // change session ID for the current session and invalidate old session ID
\$_SESSION['CREATED'] = time();  // update creation time
}
``````

Notes:

• `session.gc_maxlifetime` should be at least equal to the lifetime of this custom expiration handler (1800 in this example);
• if you want to expire the session after 30 minutes of activity instead of after 30 minutes since start, you'll also need to use `setcookie` with an expire of `time()+60*30` to keep the session cookie active.

### how to get 2 digits after decimal point in tsql?

Your format syntax is wrong actual syntax is

`````` FORMAT ( value, format [, culture ] )
``````

### How to center a table of the screen (vertically and horizontally)

One way to center any element of unknown height and width both horizontally and vertically:

``````table {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
``````

See Example

Alternatively, use a flex container:

``````.parent-element {
display: flex;
justify-content: center;
align-items: center;
}
``````

### How do I set up the database.yml file in Rails?

The `database.yml` is a file that is created with new rails applications in `/config` and defines the database configurations that your application will use in different environments. Read this for details.

Example database.yml:

``````development:
database: db/development.sqlite3
pool: 5
timeout: 5000

test:
database: db/test.sqlite3
pool: 5
timeout: 5000

production:
encoding: utf8
database: your_db
socket: /tmp/mysql.sock
host: your_db_ip     #defaults to 127.0.0.1
port: 3306
``````

### git - pulling from specific branch

It's often clearer to separate the two actions `git pull` does. The first thing it does is update the local tracking branc that corresponds to the remote branch. This can be done with `git fetch`. The second is that it then merges in changes, which can of course be done with `git merge`, though other options such as `git rebase` are occasionally useful.

### Set "Homepage" in Asp.Net MVC

Look at the `Default.aspx/Default.aspx.cs` and the Global.asax.cs

You can set up a default route:

``````        routes.MapRoute(
"Default", // Route name
"",        // URL with parameters
new { controller = "Home", action = "Index"}  // Parameter defaults
);
``````

Just change the Controller/Action names to your desired default. That should be the last route in the Routing Table.

### Threading pool similar to the multiprocessing Pool?

``````import concurrent.futures
for i in range(10):
a = executor.submit(arg1, arg2,....)
``````

### How to change font size in Eclipse for Java text editors?

I tend to use menu Windows ? Preferences ? General ? Appearances ? Colors and Fonts ? Java Text Editors ? Change ? Apply.

### Remove Identity from a column in a table

Bellow code working as fine, when we don't know identity column name.

Need to copy data into new temp table like `Invoice_DELETED`. and next time we using:

``````insert into Invoice_DELETED select * from Invoice where ...

SELECT t1.*
INTO Invoice_DELETED
FROM Invoice t1
LEFT JOIN Invoice ON 1 = 0
--WHERE t1.InvoiceID = @InvoiceID
``````

For more explanation see: https://dba.stackexchange.com/a/138345/101038

### Target WSGI script cannot be loaded as Python module

As this question became sort of a pool for collecting solutions for problems that result in the error giving this question its title, I'd like to add this one, too.

In my case, I want to run OpenStack Keystone (Ocata) using Apache and WSGI on Ubuntu 16.04.2. The processes start but as soon as I query keystone I get

``````mod_wsgi (pid=20103): Target WSGI script '/opt/openstack/bin/keystone-wsgi-public' cannot be loaded as Python module.
``````

``````WSGIDaemonProcess keystone-public ...
WSGIProcessGroup keystone-public ...
``````

``````WSGIDaemonProcess keystone-admin ...
``````

I solved the problem by renaming them. The vhost entries now read:

``````WSGIDaemonProcess kst-pub ...
WSGIProcessGroup kst-pub ...
``````

and

``````WSGIDaemonProcess kst-adm ...
``````

I didn't investigate any further. Solved as works for me.

For Apache 2.4, you would use the Require IP directive. So to only allow machines from the 192.168.0.0/24 network (range 192.168.0.0 - 192.168.0.255)

``````<VirtualHost *:80>
<Location />
Require ip 192.168.0.0/24
</Location>
...
</VirtualHost>
``````

And if you just want the localhost machine to have access, then there's a special Require local directive.

The local provider allows access to the server if any of the following conditions is true:

• the client address matches 127.0.0.0/8
• the client address is ::1
• both the client and the server address of the connection are the same

This allows a convenient way to match connections that originate from the local host:

``````<VirtualHost *:80>
<Location />
Require local
</Location>
...
</VirtualHost>
``````

In order to make the terminal always have the file `~/.bashrc` and there put the path you wish to use, by adding:

``````export PATH=\$PATH:/XXX
``````

where XXX is the path that you wish to use.

for adb, here's what i use:

``````export PATH=\$PATH:/home/user/Android/android-sdk-linux_x86/platform-tools/
``````

(where "user" is my user name).

### How to get folder path from file path with CMD

In case anyone wants an alternative method...

If it is the last subdirectory in the path, you can use this one-liner:

``````cd "c:\directory\subdirectory\filename.exe\..\.." && dir /ad /b /s
``````

This would return the following:

``````c:\directory\subdirectory
``````

The .... drops back to the previous directory. /ad shows only directories /b is a bare format listing /s includes all subdirectories. This is used to get the full path of the directory to print.

### CSS: On hover show and hide different div's at the same time?

http://jsfiddle.net/MBLZx/

Here is the code

_x000D_
_x000D_
`````` .showme{ _x000D_
display: none;_x000D_
}_x000D_
.showhim:hover .showme{_x000D_
display : block;_x000D_
}_x000D_
.showhim:hover .ok{_x000D_
display : none;_x000D_
}``````
_x000D_
`````` <div class="showhim">_x000D_
HOVER ME_x000D_
<div class="showme">hai</div>_x000D_
<div class="ok">ok</div>_x000D_
</div>_x000D_
_x000D_
``````
_x000D_
_x000D_
_x000D_

### NUnit Unit tests not showing in Test Explorer with Test Adapter installed

If you're using a NUnit3+ version, there is a new Test Adapter available.

Go to "Tools -> Extensions and Updates -> Online" and search for "NUnit3 Test Adapter" and then install.

### I get Access Forbidden (Error 403) when setting up new alias

Apache 2.4 virtual hosts hack

1.In http.conf specify the ports , below “Listen”

``````Listen 80
Listen 4000
Listen 7000
Listen 9000
``````
1. In httpd-vhosts.conf

``````<VirtualHost *:80>
DocumentRoot "C:/Users/Vikas/Documents/NetBeansProjects/slider_website_hitesh/public_html"
ServerName hitesh_web.dev
ErrorLog "logs/dummy-host2.example.com-error.log"
CustomLog "logs/dummy-host2.example.com-access.log" common

<Directory "C:/Users/Vikas/Documents/NetBeansProjects/slider_website_hitesh/public_html">
Allow from all
Require all granted
</Directory>

</VirtualHost>
``````

# this is 2nd virtual host

``````<VirtualHost *:80>
DocumentRoot "E:/dabkick_git/DabKickWebsite"
ServerName  www.my_mobile.dev
ErrorLog "logs/dummy-host2.example.com-error.log"
CustomLog "logs/dummy-host2.example.com-access.log" common

<Directory "E:/dabkick_git/DabKickWebsite">
Allow from all
Require all granted
</Directory>
</VirtualHost>
``````
2. In hosts.ics file of windows os “C:\Windows\System32\drivers\etc\host.ics”

``````127.0.0.1             localhost
127.0.0.1             hitesh_web.dev
127.0.0.1             www.my_mobile.dev
127.0.0.1             demo.multisite.dev
``````

4.now type your “domain names” in the browser it will ping the particular folder specified in the documentRoot path

5.if you want to access those files in a particular port then replace 80 in httpd-vhosts.conf with port numbers like below and restart apache

``````   <VirtualHost *:4000>
DocumentRoot "C:/Users/Vikas/Documents/NetBeansProjects/slider_website_hitesh/public_html"
ServerName hitesh_web.dev
ErrorLog "logs/dummy-host2.example.com-error.log"
CustomLog "logs/dummy-host2.example.com-access.log" common

<Directory "C:/Users/Vikas/Documents/NetBeansProjects/slider_website_hitesh/public_html">
Allow from all
Require all granted
</Directory>

</VirtualHost>
``````

# this is the 2nd vhost

``````<VirtualHost *:7000>
DocumentRoot "E:/dabkick_git/DabKickWebsite"
ServerName  www.dabkick_mobile.dev
ErrorLog "logs/dummy-host2.example.com-error.log"
CustomLog "logs/dummy-host2.example.com-access.log" common

<Directory "E:/dabkick_git/DabKickWebsite">
Allow from all
Require all granted
</Directory>
</VirtualHost>
``````

Note: for port number given virtual hosts you have to ping in browser like “http://hitesh_web.dev:4000/” or “http://www.dabkick_mobile.dev:7000/

6.After doing all those changes you have to save the files and restart apache respectively.

### git status (nothing to commit, working directory clean), however with changes commited

The problem is that you are not specifying the name of the remote: Instead of

``````git remote add https://github.com/username/project.git
``````

you should use:

``````git remote add origin https://github.com/username/project.git
``````

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

The Date constructor expects years in the format of years since 1900, zero-based months, one-based days, and sets hours/minutes/seconds/milliseconds to zero.

``````Date result = new Date(year, month, day);
``````

So using the Calendar replacement (zero-based years, zero-based months, one-based days) for the deprecated Date constructor, we need something like:

``````Calendar calendar = Calendar.getInstance();
calendar.clear(); // Sets hours/minutes/seconds/milliseconds to zero
calendar.set(year + 1900, month, day);
Date result = calendar.getTime();
``````

Or using Java 1.8 (which has zero-based year, and one-based months and days):

``````Date result = Date.from(LocalDate.of(year + 1900, month + 1, day).atStartOfDay(ZoneId.systemDefault()).toInstant());
``````

Here are equal versions of Date, Calendar, and Java 1.8:

``````int year = 1985; // 1985
int month = 1; // January
int day = 1; // 1st

// Original, 1900-based year, zero-based month, one-based day
Date date1 = new Date(year - 1900, month - 1, day);

// Calendar, zero-based year, zero-based month, one-based day
Calendar calendar = Calendar.getInstance();
calendar.clear(); // Sets hours/minutes/seconds/milliseconds to zero
calendar.set(year, month - 1, day);
Date date2 = calendar.getTime();

// Java-time back to Date, zero-based year, one-based month, one-based day
Date date3 = Date.from(LocalDate.of(year, month, day).atStartOfDay(ZoneId.systemDefault()).toInstant());

SimpleDateFormat format = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss.SSS");

// All 3 print "1985-Jan-01 00:00:00.000"
System.out.println(format.format(date1));
System.out.println(format.format(date2));
System.out.println(format.format(date3));
``````

### jQuery validation plugin: accept only alphabetical characters?

Just a small addition to Nick's answer (which works great !) :

If you want to allow spaces in between letters, for example , you may restrict to enter only letters in full name, but it should allow space as well - just list the space as below with a comma. And in the same way if you need to allow any other specific character:

``````jQuery.validator.addMethod("lettersonly", function(value, element)
{
return this.optional(element) || /^[a-z," "]+\$/i.test(value);
}, "Letters and spaces only please");
``````

### Cannot connect to the Docker daemon on macOS

I first tried docker and docker-compose via homebrew, but it had the problem listed here. I had to install docker's official install from https://docs.docker.com/docker-for-mac/install/ and then everything worked as expected.

### MySQL Orderby a number, Nulls last

To achieve following result :

`1, 2, 3, 4, NULL, NULL, NULL.`

USE syntax, place `-(minus sign)` before field name and use inverse order_type(Like: If you want order by ASC order then use DESC or if you want DESC order then use ASC)

`SELECT * FROM tablename WHERE visible=1 ORDER BY -position DESC`

### Calculate distance in meters when you know longitude and latitude in java

You can use the Java Geodesy Library for GPS, it uses the Vincenty's formulae which takes account of the earths surface curvature.

Implementation goes like this:

``````import org.gavaghan.geodesy.*;

...

GeodeticCalculator geoCalc = new GeodeticCalculator();

Ellipsoid reference = Ellipsoid.WGS84;

GlobalPosition pointA = new GlobalPosition(latitude, longitude, 0.0); // Point A

GlobalPosition userPos = new GlobalPosition(userLat, userLon, 0.0); // Point B

double distance = geoCalc.calculateGeodeticCurve(reference, userPos, pointA).getEllipsoidalDistance(); // Distance between Point A and Point B
``````

The resulting distance is in meters.

### setting global sql_mode in mysql

In my case i have to change file `/etc/mysql/mysql.conf.d/mysqld.cnf` change this under [`mysqld`]

Paste this line on [`mysqld`] portion

``````sql_mode = "STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"
``````

### Get file from project folder java

This sounds like the file is embedded within your application.

You should be using `getClass().getResource("/path/to/your/resource.txt")`, which returns an `URL` or `getClass().getResourceAsStream("/path/to/your/resource.txt");`

If it's not an embedded resource, then you need to know the relative path from your application's execution context to where your file exists

### Regex to replace multiple spaces with a single space

``````var myregexp = new RegExp(/ {2,}/g);

str = str.replace(myregexp,' ');
``````

### AngularJs: How to set radio button checked based on model

One way that I see more powerful and avoid having a `isDefault` in all the models is by using the ng-attributes `ng-model`, `ng-value` and `ng-checked`.

ng-model: binds the value to your model.

ng-value: the value to pass to the `ng-model` binding.

ng-checked: value or expression that is evaluated. Useful for radio-button and check-boxes.

Example of use: In the following example, I have my model and a list of languages that my site supports. To display the different languages supported and updating the model with the selecting language we can do it in this way.

``````<!-- Radio -->
<div ng-repeat="language in languages">

<div>
<label>

<input ng-model="site.lang"
ng-value="language"
ng-checked="(site.lang == language)"
name="localizationOptions"

<span> {{language}} </span>

</label>
</div>

</div>
``````

Our model `site.lang` will get a `language` value whenever the expression under evaluation `(site.lang == language)` is true. This will allow you to sync it with server easily since your model already has the change.

### error: 'Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)' -- Missing /var/run/mysqld/mysqld.sock

This solution can help others, sometimes the fix is very simple.

In your live environment restart mysql server and apache

``````sudo service mysql restart
sudo apache services restart
``````

this is a common problem when you install a plugin or execute any database commands.

### Reading a string with scanf

I think that this below is accurate and it may help. Feel free to correct it if you find any errors. I'm new at C.

``````char str[]
``````
1. array of values of type char, with its own address in memory
2. array of values of type char, with its own address in memory as many consecutive addresses as elements in the array
3. including termination null character `'\0'` `&str`, `&str[0]` and `str`, all three represent the same location in memory which is address of the first element of the array `str`

char *strPtr = &str[0]; //declaration and initialization

alternatively, you can split this in two:

``````char *strPtr; strPtr = &str[0];
``````
1. `strPtr` is a pointer to a `char`
2. `strPtr` points at array `str`
3. `strPtr` is a variable with its own address in memory
4. `strPtr` is a variable that stores value of address `&str[0]`
5. `strPtr` own address in memory is different from the memory address that it stores (address of array in memory a.k.a &str[0])
6. `&strPtr` represents the address of strPtr itself

I think that you could declare a pointer to a pointer as:

``````char **vPtr = &strPtr;
``````

declares and initializes with address of strPtr pointer

Alternatively you could split in two:

``````char **vPtr;
*vPtr = &strPtr
``````
1. `*vPtr` points at strPtr pointer
2. `*vPtr` is a variable with its own address in memory
3. `*vPtr` is a variable that stores value of address &strPtr
4. final comment: you can not do `str++`, `str` address is a `const`, but you can do `strPtr++`

### Error:Execution failed for task ':app:dexDebug'. com.android.ide.common.process.ProcessException

I encountered the same exact error message. I am not quite sure if my solution will solve also your issue.

In Project Structure (app) I changed the Compile SDK Version from API 22 to API 21 and changed Build Tools Version from 22.0.0 to 21.1.2.

When I downloaded the latest API 22 Adroid 5.1, every project I create is using this API and causes me the problem. Maybe, Android Team is looking for a fix for this one.

### How do I install jmeter on a Mac?

You have 2 options:

`brew update` to update homebrew packages

`brew install jmeter` to install jmeter

Read this blog to know how to map folders from standard jmeter to homebrew installed version.

• Install using standard version which I would advise you to do. Steps are:

1. Install Last compatible JDK version (7 or 8 as of JMeter 3.1).

3. Unzip folder and run from the folder:

`bin/jmeter`

### How to secure RESTful web services?

There's another, very secure method. It's client certificates. Know how servers present an SSL Cert when you contact them on https? Well servers can request a cert from a client so they know the client is who they say they are. Clients generate certs and give them to you over a secure channel (like coming into your office with a USB key - preferably a non-trojaned USB key).

You load the public key of the cert client certificates (and their signer's certificate(s), if necessary) into your web server, and the web server won't accept connections from anyone except the people who have the corresponding private keys for the certs it knows about. It runs on the HTTPS layer, so you may even be able to completely skip application-level authentication like OAuth (depending on your requirements). You can abstract a layer away and create a local Certificate Authority and sign Cert Requests from clients, allowing you to skip the 'make them come into the office' and 'load certs onto the server' steps.

Pain the neck? Absolutely. Good for everything? Nope. Very secure? Yup.

It does rely on clients keeping their certificates safe however (they can't post their private keys online), and it's usually used when you sell a service to clients rather then letting anyone register and connect.

Anyway, it may not be the solution you're looking for (it probably isn't to be honest), but it's another option.

### C++ template typedef

C++11 added alias declarations, which are generalization of `typedef`, allowing templates:

``````template <size_t N>
using Vector = Matrix<N, 1>;
``````

The type `Vector<3>` is equivalent to `Matrix<3, 1>`.

In C++03, the closest approximation was:

``````template <size_t N>
struct Vector
{
typedef Matrix<N, 1> type;
};
``````

Here, the type `Vector<3>::type` is equivalent to `Matrix<3, 1>`.

### In oracle, how do I change my session to display UTF8?

NLS_LANG cannot be changed by ALTER SESSION, NLS_LANGUAGE and NLS_TERRITORY can. However NLS_LANGUAGE and /or NLS_TERRITORY cannot be set as "standalone" parameters in the environment or registry on the client.

Evidently the "right" solution is, before logging into Oracle at all, setting the following environment variable:

``````export NLS_LANG=AMERICAN_AMERICA.UTF8
``````

Oracle gets a big fat F for usability.

### How to get every first element in 2 dimensional list

You can get it like

``````[ x[0] for x in a]
``````

which will return a list of the first element of each list in `a`

### TOMCAT - HTTP Status 404

1. Click on `Window > Show view > Server` or right click on the server in "Servers" view, select "Properties".
2. In the "General" panel, click on the "Switch Location" button.
3. The "Location: [workspace metadata]" should replace by something else.
4. Open the Overview screen for the server by double clicking it.
5. In the Server locations tab , select "Use Tomcat location".
6. Save the configurations and restart the Server.

You may want to follow the steps above before starting the server. Because server location section goes grayed-unreachable.

### Spring - No EntityManager with actual transaction available for current thread - cannot reliably process 'persist' call

This helped us, maybe it can help others in the future. `@Transaction` was not working for us, but this did:

`@ConditionalOnMissingClass("org.springframework.orm.jpa.JpaTransactionManager")`

### jQuery How to Get Element's Margin and Padding?

Edit:

use jquery plugin: jquery.sizes.js

``````\$('img').margin() or \$('img').padding()
``````

return:

``````{bottom: 10 ,left: 4 ,top: 0 ,right: 5}
``````

get value:

``````\$('img').margin().top
``````

### How to sum a list of integers with java streams?

This would be the shortest way to sum up `int` type array (for `long` array `LongStream`, for `double` array `DoubleStream` and so forth). Not all the primitive integer or floating point types have the `Stream` implementation though.

``````IntStream.of(integers).sum();
``````

### Create a directory if it does not exist and then create the files in that directory as well

Java 8+ version:

``````Files.createDirectories(Paths.get("/Your/Path/Here"));
``````

The `Files.createDirectories()` creates a new directory and parent directories that do not exist. This method does not throw an exception if the directory already exists.

### Undo a particular commit in Git that's been pushed to remote repos

Because it has already been pushed, you shouldn't directly manipulate history. `git revert` will revert specific changes from a commit using a new commit, so as to not manipulate commit history.

### Getting permission denied (public key) on gitlab

I use ubuntu 18.04, and it was actually permission issue in my local machine. The issue was gone when I set read/write permission to my .git folder.

### C# Base64 String to JPEG Image

``````public Image Base64ToImage(string base64String)
{
// Convert Base64 String to byte[]
byte[] imageBytes = Convert.FromBase64String(base64String);
MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);

// Convert byte[] to Image
ms.Write(imageBytes, 0, imageBytes.Length);
Image image = Image.FromStream(ms, true);

return image;
}
``````

### Adding a new value to an existing ENUM Type

just in case, if you are using Rails and you have several statements you will need to execute one by one, like:

``````execute "ALTER TYPE XXX ADD VALUE IF NOT EXISTS 'YYY';"
execute "ALTER TYPE XXX ADD VALUE IF NOT EXISTS 'ZZZ';"
``````

### PHP replacing special characters like à->a, è->e

Simple function. Transform strings like 'Ábç Éfg' to 'abc_efg'

``````/**
* @param \$str
* @return mixed
*/
function sanitizeString(\$str) {
\$str = preg_replace('/[áàãâä]/ui', 'a', \$str);
\$str = preg_replace('/[éèêë]/ui', 'e', \$str);
\$str = preg_replace('/[íìîï]/ui', 'i', \$str);
\$str = preg_replace('/[óòõôö]/ui', 'o', \$str);
\$str = preg_replace('/[úùûü]/ui', 'u', \$str);
\$str = preg_replace('/[ç]/ui', 'c', \$str);
\$str = preg_replace('/[^a-z0-9]/i', '_', \$str);
\$str = preg_replace('/_+/', '_', \$str);

return \$str;
}
``````

### Decompile Python 2.7 .pyc

Ned Batchelder has posted a short script that will unmarshal a .pyc file and disassemble any code objects within, so you'll be able to see the Python bytecode. It looks like with newer versions of Python, you'll need to comment out the lines that set `modtime` and print it (but don't comment the line that sets `moddate`).

Turning that back into Python source would be somewhat more difficult, although theoretically possible. I assume all these programs that work for older versions of Python do that.

### React Error: Target Container is not a DOM Element

I figured it out!

After reading this blog post I realized that the placement of this line:

``````<script src="{% static "build/react.js" %}"></script>
``````

was wrong. That line needs to be the last line in the `<body>` section, right before the `</body>` tag. Moving the line down solves the problem.

My explanation for this is that react was looking for the id in between the `<head>` tags, instead of in the `<body>` tags. Because of this it couldn't find the `content` id, and thus it wasn't a real DOM element.

### Is it possible to validate the size and type of input=file in html5

``````    <form  class="upload-form">
<input type=submit>
</form>
<script>
\$(function(){
var maxSize = fileInput.data('max-size');
if(fileInput.get(0).files.length){
var fileSize = fileInput.get(0).files[0].size; // in bytes
if(fileSize>maxSize){
alert('file size is more then' + maxSize + ' bytes');
return false;
}else{
alert('file size is correct- '+fileSize+' bytes');
}
}else{
return false;
}

});
});
</script>
``````

http://jsfiddle.net/9bhcB/2/

#### Quick Fix

First make sure that external added library has option embed is selected in General Tab, Embbed Binaries.

If still not works..

This happens because you have different, unmatched versions of libraries present.

Update the Pods

``````pod update
``````

Important: Check all libraries are included in the Build Settings -> libraries and frameworks list and you have given option to embbed in the build

Just working awesome

### Make a dictionary with duplicate keys in Python

You can refer to the following article: http://www.wellho.net/mouth/3934_Multiple-identical-keys-in-a-Python-dict-yes-you-can-.html

In a dict, if a key is an object, there are no duplicate problems.

For example:

``````class p(object):
def __init__(self, name):
self.name = name
def __repr__(self):
return self.name
def __str__(self):
return self.name
d = {p('k'): 1, p('k'): 2}
``````

### libstdc++.so.6: cannot open shared object file: No such file or directory

Try this:

``````apt-get install lib32stdc++6
``````

### String replace a Backslash

Try `replaceAll("\\\\", "")` or `replaceAll("\\\\/", "/")`.

The problem here is that a backslash is (1) an escape chararacter in Java string literals, and (2) an escape character in regular expressions – each of this uses need doubling the character, in effect needing 4 `\` in row.

Of course, as Bozho said, you need to do something with the result (assign it to some variable) and not throw it away. And in this case the non-regex variant is better.

### How to size an Android view based on its parent's dimensions

You can now use PercentRelativeLayout. Boom! Problem solved.

### How to make CSS3 rounded corners hide overflow in Chrome/Opera

If you are looking to create a mask for an image and position the image inside the container don't set the 'position: absolute' attribute. All you have to do is change the margin-left and margin-right. Chrome/Opera will adhere to the overflow: hidden and border-radius rules.

``````// Breaks in Chrome/Opera.
.container {
overflow: hidden;
img {
position: absolute;
left: 20px;
right: 20px;
}
}

// Works in Chrome/Opera.
.container {
overflow: hidden;
img {
margin-left: 20px;
margin-right: 20px;
}
}
``````

### How do I choose the URL for my Spring Boot webapp?

You need to set the property `server.contextPath` to `/myWebApp`.

Check out this part of the documentation

The easiest way to set that property would be in the properties file you are using (most likely `application.properties`) but Spring Boot provides a whole lot of different way to set properties. Check out this part of the documentation

EDIT

As has been mentioned by @AbdullahKhan, as of Spring Boot 2.x the property has been deprecated and should be replaced with `server.servlet.contextPath` as has been correctly mentioned in this answer.

### show/hide html table columns using css

if you're looking for a simple column hide you can use the :nth-child selector as well.

``````#tableid tr td:nth-child(3),
#tableid tr th:nth-child(3) {
display: none;
}
``````

I use this with the @media tag sometimes to condense wider tables when the screen is too narrow.

### JavaScript: Create and destroy class instance through class method

1- There is no way to actually destroy an object in javascript, but using `delete`, we could remove a reference from an object:

``````var obj = {};
obj.mypointer = null;
delete obj.mypointer;
``````

2- The important point about the `delete` keyword is that it does not actually destroy the object BUT if only after deleting that reference to the object, there is no other reference left in the memory pointed to the same object, that object would be marked as collectible. The `delete` keyword deletes the reference but doesn't GC the actual object. it means if you have several references of the same object, the object will be collected just after you delete all the pointed references.

3- there are also some tricks and workarounds that could help us out, when we want to make sure we do not leave any memory leaks behind. for instance if you have an array consisting several objects, without any other pointed reference to those objects, if you recreate the array all those objects would be killed. For instance if you have `var array = [{}, {}]` overriding the value of the array like `array = []` would remove the references to the two objects inside the array and those two objects would be marked as collectible.

4- for your solution the easiest way is just this:

``````var storage = {};
storage.instance = new Class();
//since 'storage.instance' is your only reference to the object, whenever you wanted to destroy do this:
storage.instance = null;
// OR
delete storage.instance;
``````

As mentioned above, either setting `storage.instance = null` or `delete storage.instance` would suffice to remove the reference to the object and allow it to be cleaned up by the GC. The difference is that if you set it to `null` then the storage object still has a property called instance (with the value null). If you `delete storage.instance` then the storage object no longer has a property named instance.

and WHAT ABOUT destroy method ??

the paradoxical point here is if you use `instance.destroy` in the destroy function you have no access to the actual `instance` pointer, and it won't let you delete it.

The only way is to pass the reference to the destroy function and then delete it:

``````// Class constructor
var Class = function () {
this.destroy = function (baseObject, refName) {
delete baseObject[refName];
};
};

// instanciate
var storage = {};
storage.instance = new Class();
storage.instance.destroy(object, "instance");
console.log(storage.instance); // now it is undefined
``````

BUT if I were you I would simply stick to the first solution and delete the object like this:

``````storage.instance = null;
// OR
delete storage.instance;
``````

WOW it was too much :)

### How would I get everything before a : in a string Python

Using `index`:

``````>>> string = "Username: How are you today?"
>>> string[:string.index(":")]
``````

The index will give you the position of `:` in string, then you can slice it.

If you want to use regex:

``````>>> import re
>>> re.match("(.*?):",string).group()
``````

`match` matches from the start of the string.

you can also use `itertools.takewhile`

``````>>> import itertools
>>> "".join(itertools.takewhile(lambda x: x!=":", string))
``````

### How to get Locale from its String representation in Java?

If you are using Spring framework in your project you can also use:

``````org.springframework.util.StringUtils.parseLocaleString("en_US");
``````

Parse the given String representation into a Locale

### Delete all data in SQL Server database

``````EXEC sp_MSForEachTable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL'

EXEC sp_MSForEachTable 'ALTER TABLE ? DISABLE TRIGGER ALL'

EXEC sp_MSForEachTable 'DELETE FROM ?'

EXEC sp_MSForEachTable 'ALTER TABLE ? CHECK CONSTRAINT ALL'

EXEC sp_MSForEachTable 'ALTER TABLE ? ENABLE TRIGGER ALL'

EXEC sp_MSFOREACHTABLE 'SELECT * FROM ?'

GO
``````

### How do I create a new user in a SQL Azure database?

I think the templates use the following notation: variable name, variable type, default value.

Sysname is a built-in data type which can hold the names of system objects.

It is limited to 128 Unicode character.

``````-- same as sysname type
declare @my_sysname nvarchar(128);
``````

### how to read all files inside particular folder

``````using System.IO;
...
foreach (string file in Directory.EnumerateFiles(folderPath, "*.xml"))
{
}
``````

Note the above uses a .NET 4.0 feature; in previous versions replace `EnumerateFiles` with `GetFiles`). Also, replace `File.ReadAllText` with your preferred way of reading xml files - perhaps `XDocument`, `XmlDocument` or an `XmlReader`.

### CMD: How do I recursively remove the "Hidden"-Attribute of files and directories

just type

``````attrib -h -r -s /s /d j:*.*
``````

where j is the drive letter... unlocks all the locked stuff in j drive

if u want to make it specific..then go to a specific location using cmd and then type

``````attrib -h -r -s /s /d "foldername"
``````

it can also be used to lock drives or folders just alter "-" with "+"

``````attrib +h +r +s /s /d "foldername"
``````

### Bootstrap 4 datapicker.js not included

Maybe you want to try this: https://bootstrap-datepicker.readthedocs.org/en/latest/index.html

It's a flexible datepicker widget in the Bootstrap style.

### api-ms-win-crt-runtime-l1-1-0.dll is missing when opening Microsoft Office file

While the answer from alireza is correct, it has one gotcha:

You can't install Microsoft Visual C++ 2015 redist (runtime) unless you have Windows Update KB2999226 installed (at least on Windows 7 64-bit SP1).

### C# : Passing a Generic Object

You need to define something in the interface, such as:

``````public interface ITest
{
string Name { get; }
}
``````

Implement `ITest` in your classes:

``````public class MyClass1 : ITest
{
public string Name { get { return "Test1"; } }
}

public class MyClass2 : ITest
{
public string Name { get { return "Test2"; } }
}
``````

Then restrict your generic `Print` function, to `ITest`:

``````public void Print<T>(T test) where T : ITest
{
}
``````

### What are the ascii values of up down left right?

The ascii values of the:

1. Up key - 224 72

2. Down key - 224 80

3. Left key - 224 75

4. Right key - 224 77

Each of these has two integer values for ascii value, because they are special keys, as opposed to the code for \$, which is simply 36. These 2 byte special keys usually have the first digit as either 224, or 0. this can be found with the F# in windows, or the delete key.

EDIT : This may actually be unicode looking back, but they do work.

### Fling gesture detection on grid layout

I do it a little different, and wrote an extra detector class that implements the `View.onTouchListener`

`onCreate`is simply add it to the lowest layout like this:

``````ActivitySwipeDetector activitySwipeDetector = new ActivitySwipeDetector(this);
lowestLayout = (RelativeLayout)this.findViewById(R.id.lowestLayout);
lowestLayout.setOnTouchListener(activitySwipeDetector);
``````

where id.lowestLayout is the id.xxx for the view lowest in the layout hierarchy and lowestLayout is declared as a RelativeLayout

And then there is the actual activity swipe detector class:

``````public class ActivitySwipeDetector implements View.OnTouchListener {

static final String logTag = "ActivitySwipeDetector";
private Activity activity;
static final int MIN_DISTANCE = 100;
private float downX, downY, upX, upY;

public ActivitySwipeDetector(Activity activity){
this.activity = activity;
}

public void onRightSwipe(){
Log.i(logTag, "RightToLeftSwipe!");
activity.doSomething();
}

public void onLeftSwipe(){
Log.i(logTag, "LeftToRightSwipe!");
activity.doSomething();
}

public void onDownSwipe(){
Log.i(logTag, "onTopToBottomSwipe!");
activity.doSomething();
}

public void onUpSwipe(){
Log.i(logTag, "onBottomToTopSwipe!");
activity.doSomething();
}

public boolean onTouch(View v, MotionEvent event) {
switch(event.getAction()){
case MotionEvent.ACTION_DOWN: {
downX = event.getX();
downY = event.getY();
return true;
}
case MotionEvent.ACTION_UP: {
upX = event.getX();
upY = event.getY();

float deltaX = downX - upX;
float deltaY = downY - upY;

// swipe horizontal?
if(Math.abs(deltaX) > Math.abs(deltaY))
{
if(Math.abs(deltaX) > MIN_DISTANCE){
// left or right
if(deltaX > 0) { this.onRightSwipe(); return true; }
if(deltaX < 0) { this.onLeftSwipe(); return true; }
}
else {
Log.i(logTag, "Horizontal Swipe was only " + Math.abs(deltaX) + " long, need at least " + MIN_DISTANCE);
return false; // We don't consume the event
}
}
// swipe vertical?
else
{
if(Math.abs(deltaY) > MIN_DISTANCE){
// top or down
if(deltaY < 0) { this.onDownSwipe(); return true; }
if(deltaY > 0) { this.onUpSwipe(); return true; }
}
else {
Log.i(logTag, "Vertical Swipe was only " + Math.abs(deltaX) + " long, need at least " + MIN_DISTANCE);
return false; // We don't consume the event
}
}

return true;
}
}
return false;
}

}
``````

Works really good for me!

### Populating Spring @Value during Unit Test

Since Spring 4.1 you could set up property values just in code by using `org.springframework.test.context.TestPropertySource` annotation on Unit Tests class level. You could use this approach even for injecting properties into dependent bean instances

For example

``````@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = FooTest.Config.class)
@TestPropertySource(properties = {
"some.bar.value=testValue",
})
public class FooTest {

@Value("\${some.bar.value}")
String bar;

@Test
public void testValueSetup() {
assertEquals("testValue", bar);
}

@Configuration
static class Config {

@Bean
public static PropertySourcesPlaceholderConfigurer propertiesResolver() {
return new PropertySourcesPlaceholderConfigurer();
}

}

}
``````

Note: It's necessary to have instance of `org.springframework.context.support.PropertySourcesPlaceholderConfigurer` in Spring context

Edit 24-08-2017: If you are using SpringBoot 1.4.0 and later you could initialize tests with `@SpringBootTest` and `@SpringBootConfiguration` annotations. More info here

In case of SpringBoot we have following code

``````@SpringBootTest
@SpringBootConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@TestPropertySource(properties = {
"some.bar.value=testValue",
})
public class FooTest {

@Value("\${some.bar.value}")
String bar;

@Test
public void testValueSetup() {
assertEquals("testValue", bar);
}

}
``````

### Converting java date to Sql timestamp

Take a look at `SimpleDateFormat`:

``````java.util.Date utilDate = new java.util.Date();
java.sql.Timestamp sq = new java.sql.Timestamp(utilDate.getTime());

SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
System.out.println(sdf.format(sq));
``````

### How do I use Join-Path to combine more than two strings into a file path?

If you are still using .NET 2.0, then `[IO.Path]::Combine` won't have the `params string[]` overload which you need to join more than two parts, and you'll see the error Cannot find an overload for "Combine" and the argument count: "3".

Slightly less elegant, but a pure PowerShell solution is to manually aggregate path parts:

``````Join-Path C: (Join-Path  "Program Files" "Microsoft Office")
``````

or

``````Join-Path  (Join-Path  C: "Program Files") "Microsoft Office"
``````

### Why can't I use background image and color together?

To tint an image, you can use CSS3 `background` to stack images and a `linear-gradient`. In the example below, I use a `linear-gradient` with no actual gradient. The browser treats gradients as images (I think it actually generates a bitmap and overlays it) and thus, is actually stacking multiple images.

``````background: linear-gradient(0deg, rgba(2,173,231,0.5), rgba(2,173,231,0.5)), url(images/mba-grid-5px-bg.png) repeat;
``````

Will yield a graph-paper with light blue tint, if you had the png. Note that the stacking order might work in reverse to your mental model, with the first item being on top.

Excellent documentation by Mozilla, here:

https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Using_multiple_backgrounds

Note - doesn't work in IE11! I'll post an update when I find out why, since its supposed to.

### Fully custom validation error message with Rails

``````object.errors.each do |attr,msg|
if msg.is_a? String
if attr == :base
content_tag :li, msg
elsif msg[0] == "^"
content_tag :li, msg[1..-1]
else
content_tag :li, "#{object.class.human_attribute_name(attr)} #{msg}"
end
end
end
``````

When you want to override the error message without the attribute name, simply prepend the message with ^ like so:

``````validates :last_name,
uniqueness: {
scope: [:first_name, :course_id, :user_id],
case_sensitive: false,
message: "^This student has already been registered."
}
``````

### WordPress path url in js script file

For users working with the Genesis framework.

Add the following to your child theme `functions.php`

``````add_action( 'genesis_before', 'script_urls' );

function script_urls() {
?>
<script type="text/javascript">
var stylesheetDir = '<?= get_bloginfo("stylesheet_directory"); ?>';
</script>
<?php
}
``````

And use that variable to set the relative url in your script. For example:

``````Reset.style.background = " url('"+stylesheetDir+"/images/searchfield_clear.png') ";
``````

### how to clear JTable

If we use `tMOdel.setRowCount(0);` we can get Empty table.

``````DefaultTableModel tMOdel = (DefaultTableModel) jtableName.getModel();
tMOdel.setRowCount(0);
``````

### How to load html string in a webview?

``````wv.loadData(yourData, "text/html", "UTF-8");
``````

You can check this example

http://developer.android.com/reference/android/webkit/WebView.html

[Edit 1]

You should add -- \ -- before -- " -- for example --> name=\"spanish press\"

below string worked for me

``````String webData =  "<!DOCTYPE html><head> <meta http-equiv=\"Content-Type\" " +
"content=\"text/html; charset=utf-8\"> <html><head><meta http-equiv=\"content-type\" content=\"text/html; charset=windows-1250\">"+
"<meta name=\"spanish press\" content=\"spain, spanish newspaper, news,economy,politics,sports\"><title></title></head><body id=\"body\">"+
"<script src=\"http://www.myscript.com/a\"></script>slkassldkassdksasdkasskdsk</body></html>";
``````

### What is JavaScript's highest integer value that a number can go to without losing precision?

I write it like this:

``````var max_int = 0x20000000000000;
var min_int = -0x20000000000000;
(max_int + 1) === 0x20000000000000;  //true
(max_int - 1) < 0x20000000000000;    //true
``````

Same for int32

``````var max_int32 =  0x80000000;
var min_int32 = -0x80000000;
``````

### how do I print an unsigned char as hex in c++ using ostream?

I use the following on win32/linux(32/64 bit):

``````#include <iostream>
#include <iomanip>

template <typename T>
std::string HexToString(T uval)
{
std::stringstream ss;
ss << "0x" << std::setw(sizeof(uval) * 2) << std::setfill('0') << std::hex << +uval;
return ss.str();
}
``````

### Get current date/time in seconds

`````` Date.now()
``````

gives milliseconds since epoch. No need to use `new`.

Check out the reference here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now

(Not supported in IE8.)

### How do I change the figure size for a seaborn plot?

Note that if you are trying to pass to a "figure level" method in seaborn (for example `lmplot`, `catplot` / `factorplot`, `jointplot`) you can and should specify this within the arguments using `height` and `aspect`.

``````sns.catplot(data=df, x='xvar', y='yvar',
hue='hue_bar', height=8.27, aspect=11.7/8.27)
``````

See https://github.com/mwaskom/seaborn/issues/488 and Plotting with seaborn using the matplotlib object-oriented interface for more details on the fact that figure level methods do not obey axes specifications.

### Java: Detect duplicates in ArrayList?

If you are looking to avoid having duplicates at all, then you should just cut out the middle process of detecting duplicates and use a Set.

### json Uncaught SyntaxError: Unexpected token :

I have spent the last few days trying to figure this out myself. Using the old json dataType gives you cross origin problems, while setting the dataType to jsonp makes the data "unreadable" as explained above. So there are apparently two ways out, the first hasn't worked for me but seems like a potential solution and that I might be doing something wrong. This is explained here [ https://learn.jquery.com/ajax/working-with-jsonp/ ].

The one that worked for me is as follows: 1- download the ajax cross origin plug in [ http://www.ajax-cross-origin.com/ ]. 2- add a script link to it just below the normal jQuery link. 3- add the line "crossOrigin: true," to your ajax function.

Good to go! here is my working code for this:

_x000D_
_x000D_
``````  \$.ajax({_x000D_
crossOrigin: true,_x000D_
type : "GET",_x000D_
success:function(data){_x000D_
console.log(data);_x000D_
}_x000D_
})``````
_x000D_
_x000D_
_x000D_

Do not name your file nltk.py I used the same code and name it nltk, and got the same error as you have, I changed the file name and it went well.

# Error-Handling with SQL Stored Procedures

`TRY`/`CATCH` error handling can take place either within or outside of a procedure (or both). The examples below demonstrate error handling in both cases.

If you want to experiment further, you can fork the query on Stack Exchange Data Explorer.

(This uses a temporary stored procedure... we can't create regular SP's on SEDE, but the functionality is the same.)

``````--our Stored Procedure
create procedure #myProc as --we can only create #temporary stored procedures on SEDE.
begin
BEGIN TRY
print 'This is our Stored Procedure.'
print 1/0                          --<-- generate a "Divide By Zero" error.
print 'We are not going to make it to this line.'
END TRY

BEGIN CATCH
print 'This is the CATCH block within our Stored Procedure:'
+ ' Error Line #'+convert(varchar,ERROR_LINE())
+ ' of procedure '+isnull(ERROR_PROCEDURE(),'(Main)')
--print 1/0                        --<-- generate another "Divide By Zero" error.
-- uncomment the line above to cause error within the CATCH ¹
END CATCH
end
go

--our MAIN code block:
BEGIN TRY
print 'This is our MAIN Procedure.'
execute #myProc  --execute the Stored Procedure
--print 1/0                        --<-- generate another "Divide By Zero" error.
-- uncomment the line above to cause error within the MAIN Procedure ²
print 'Now our MAIN sql code block continues.'
END TRY

BEGIN CATCH
print 'This is the CATCH block for our MAIN sql code block:'
+ ' Error Line #'+convert(varchar,ERROR_LINE())
+ ' of procedure '+isnull(ERROR_PROCEDURE(),'(Main)')
END CATCH
``````

Here's the result of running the above sql as-is:

``````This is our MAIN Procedure.
This is our Stored Procedure.
This is the CATCH block within our Stored Procedure: Error Line #5 of procedure #myProc
Now our MAIN sql code block continues.
``````

¹ Uncommenting the "additional error line" from the Stored Procedure's CATCH block will produce:

``````This is our MAIN procedure.
This is our Stored Procedure.
This is the CATCH block within our Stored Procedure: Error Line #5 of procedure #myProc
This is the CATCH block for our MAIN sql code block: Error Line #13 of procedure #myProc
``````

² Uncommenting the "additional error line" from the MAIN procedure will produce:

``````This is our MAIN Procedure.
This is our Stored Pprocedure.
This is the CATCH block within our Stored Procedure: Error Line #5 of procedure #myProc
This is the CATCH block for our MAIN sql code block: Error Line #4 of procedure (Main)
``````

# Use a single procedure for error handling

On topic of stored procedures and error handling, it can be helpful (and tidier) to use a single, dynamic, stored procedure to handle errors for multiple other procedures or code sections.

Here's an example:

``````--our error handling procedure
create procedure #myErrorHandling as
begin
print ' Error #'+convert(varchar,ERROR_NUMBER())+': '+ERROR_MESSAGE()
print ' occurred on line #'+convert(varchar,ERROR_LINE())
+' of procedure '+isnull(ERROR_PROCEDURE(),'(Main)')
if ERROR_PROCEDURE() is null       --check if error was in MAIN Procedure
print '*Execution cannot continue after an error in the MAIN Procedure.'
end
go

create procedure #myProc as     --our test Stored Procedure
begin
BEGIN TRY
print 'This is our Stored Procedure.'
print 1/0                       --generate a "Divide By Zero" error.
print 'We will not make it to this line.'
END TRY
BEGIN CATCH
execute #myErrorHandling
END CATCH
end
go

BEGIN TRY                       --our MAIN Procedure
print 'This is our MAIN Procedure.'
execute #myProc                     --execute the Stored Procedure
print '*The error halted the procedure, but our MAIN code can continue.'
print 1/0                           --generate another "Divide By Zero" error.
print 'We will not make it to this line.'
END TRY
BEGIN CATCH
execute #myErrorHandling
END CATCH
``````

#### Example Output: (This query can be forked on SEDE here.)

``````This is our MAIN procedure.
This is our stored procedure.
Error #8134: Divide by zero error encountered.
occurred on line #5 of procedure #myProc
*The error halted the procedure, but our MAIN code can continue.
Error #8134: Divide by zero error encountered.
occurred on line #5 of procedure (Main)
*Execution cannot continue after an error in the MAIN procedure.
``````

# Documentation:

In the scope of a `TRY`/`CATCH` block, the following system functions can be used to obtain information about the error that caused the `CATCH` block to be executed:

(Source)

Note that there are two types of SQL errors: Terminal and Catchable. `TRY`/`CATCH` will [obviously] only catch the "Catchable" errors. This is one of a number of ways of learning more about your SQL errors, but it probably the most useful.

It's "better to fail now" (during development) compared to later because, as Homer says . . .

### What is the difference between the HashMap and Map objects in Java?

Map has the following implementations:

1. HashMap `Map m = new HashMap();`

2. LinkedHashMap `Map m = new LinkedHashMap();`

3. Tree Map `Map m = new TreeMap();`

4. WeakHashMap `Map m = new WeakHashMap();`

Suppose you have created one method (this is just pseudocode).

``````public void HashMap getMap(){
return map;
}
``````

1. The method should return map contents - Need to return `HashMap`.
2. The method should return map key's in insertion order - Need to change return type `HashMap` to `LinkedHashMap`.
3. The method should return map key's in sorted order - Need to change return type `LinkedHashMap` to `TreeMap`.

If your method returns specific classes instead of something that implements the `Map` interface, you have to change the return type of `getMap()` method each time.

But if you use the polymorphism feature of Java, and instead of returning specific classes, use the interface `Map`, it improves code reusability and reduces the impact of requirement changes.

### Missing artifact com.sun:tools:jar

Problem is system is not able to find the file tools.jar

So first check that the file is there in the JDK installation of the directory.

Make the below entry in POM.xml as rightly pointed by others

``````<dependency>
<groupId>com.sun</groupId>
<artifactId>tools</artifactId>
<version>1.6</version>
<scope>system</scope>
<systemPath>C:\Program Files\Java\jdk1.8.0_241\lib\tools.jar</systemPath>
</dependency>
``````

then Follow the below steps also to remove the problem

1) Right Click on your project

2) Click on Build path

As per the below image, select the workspace default JRE and click on finish.

### Pandas column of lists, create a row for each list element

A bit longer than I expected:

``````>>> df
samples  subject  trial_num
0  [-0.07, -2.9, -2.44]        1          1
1   [-1.52, -0.35, 0.1]        1          2
2  [-0.17, 0.57, -0.65]        1          3
3  [-0.82, -1.06, 0.47]        2          1
4   [0.79, 1.35, -0.09]        2          2
5   [1.17, 1.14, -1.79]        2          3
>>>
>>> s = df.apply(lambda x: pd.Series(x['samples']),axis=1).stack().reset_index(level=1, drop=True)
>>> s.name = 'sample'
>>>
>>> df.drop('samples', axis=1).join(s)
subject  trial_num  sample
0        1          1   -0.07
0        1          1   -2.90
0        1          1   -2.44
1        1          2   -1.52
1        1          2   -0.35
1        1          2    0.10
2        1          3   -0.17
2        1          3    0.57
2        1          3   -0.65
3        2          1   -0.82
3        2          1   -1.06
3        2          1    0.47
4        2          2    0.79
4        2          2    1.35
4        2          2   -0.09
5        2          3    1.17
5        2          3    1.14
5        2          3   -1.79
``````

If you want sequential index, you can apply `reset_index(drop=True)` to the result.

update:

``````>>> res = df.set_index(['subject', 'trial_num'])['samples'].apply(pd.Series).stack()
>>> res = res.reset_index()
>>> res.columns = ['subject','trial_num','sample_num','sample']
>>> res
subject  trial_num  sample_num  sample
0         1          1           0    1.89
1         1          1           1   -2.92
2         1          1           2    0.34
3         1          2           0    0.85
4         1          2           1    0.24
5         1          2           2    0.72
6         1          3           0   -0.96
7         1          3           1   -2.72
8         1          3           2   -0.11
9         2          1           0   -1.33
10        2          1           1    3.13
11        2          1           2   -0.65
12        2          2           0    0.10
13        2          2           1    0.65
14        2          2           2    0.15
15        2          3           0    0.64
16        2          3           1   -0.10
17        2          3           2   -0.76
``````

### How to mock static methods in c# using MOQ framework?

As mentioned in the other answers MOQ cannot mock static methods and, as a general rule, one should avoid statics where possible.

Sometimes it is not possible. One is working with legacy or 3rd party code or with even with the BCL methods that are static.

A possible solution is to wrap the static in a proxy with an interface which can be mocked

``````    public interface IFileProxy {
void Delete(string path);
}

public class FileProxy : IFileProxy {
public void Delete(string path) {
System.IO.File.Delete(path);
}
}

public class MyClass {

private IFileProxy _fileProxy;

public MyClass(IFileProxy fileProxy) {
_fileProxy = fileProxy;
}

public void DoSomethingAndDeleteFile(string path) {
// Do Something with file
// ...
// Delete
System.IO.File.Delete(path);
}

public void DoSomethingAndDeleteFileUsingProxy(string path) {
// Do Something with file
// ...
// Delete
_fileProxy.Delete(path);

}
}
``````

The downside is that the ctor can become very cluttered if there are a lot of proxies (though it could be argued that if there are a lot of proxies then the class may be trying to do too much and could be refactored)

Another possibility is to have a 'static proxy' with different implementations of the interface behind it

``````   public static class FileServices {

static FileServices() {
Reset();
}

internal static IFileProxy FileProxy { private get; set; }

public static void Reset(){
FileProxy = new FileProxy();
}

public static void Delete(string path) {
FileProxy.Delete(path);
}

}
``````

Our method now becomes

``````    public void DoSomethingAndDeleteFileUsingStaticProxy(string path) {
// Do Something with file
// ...
// Delete
FileServices.Delete(path);

}
``````

For testing, we can set the FileProxy property to our mock. Using this style reduces the number of interfaces to be injected but makes dependencies a bit less obvious (though no more so than the original static calls I suppose).

### function to return a string in java

Your code is fine. There's no problem with returning `Strings` in this manner.

In Java, a `String` is a reference to an immutable object. This, coupled with garbage collection, takes care of much of the potential complexity: you can simply pass a `String` around without worrying that it would disapper on you, or that someone somewhere would modify it.

If you don't mind me making a couple of stylistic suggestions, I'd modify the code like so:

``````public String time_to_string(long t) // time in milliseconds
{
if (t < 0)
{
return "-";
}
else
{
int secs = (int)(t/1000);
int mins = secs/60;
secs = secs - (mins * 60);
return String.format("%d:%02d", mins, secs);
}
}
``````

As you can see, I've pushed the variable declarations as far down as I could (this is the preferred style in C++ and Java). I've also eliminated `ans` and have replaced the mix of string concatenation and `String.format()` with a single call to `String.format()`.

### How to do "If Clicked Else .."

This is all you need: http://api.jquery.com/click/

Having an "else" doesn't apply in this scenario, else would mean "did not click", in which case you just wouldn't do anything.

### How to sparsely checkout only one single file from a git repository?

If you have edited a local version of a file and wish to revert to the original version maintained on the central server, this can be easily achieved using Git Extensions.

• Initially the file will be marked for commit, since it has been modified
• Select (double click) the file in the file tree menu
• The revision tree for the single file is listed.
• Select the top/HEAD of the tree and right click save as
• Save the file to overwrite the modified local version of the file
• The file now has the correct version and will no longer be marked for commit!

Easy!

### Oracle SqlDeveloper JDK path

For those who use Mac, edit this file:

``````/Applications/SQLDeveloper.app/Contents/MacOS/sqldeveloper.sh
``````

``````export JAVA_HOME=`/usr/libexec/java_home -v 1.7`
``````

and I changed it to 1.8 and it stopped complaining about java version.

### How to explicitly obtain post data in Spring MVC?

Another answer to the OP's exact question is to set the `consumes` content type to `"text/plain"` and then declare a `@RequestBody String` input parameter. This will pass the text of the POST data in as the declared `String` variable (`postPayload` in the following example).

Of course, this presumes your POST payload is text data (as the OP stated was the case).

Example:

``````    @RequestMapping(value = "/your/url/here", method = RequestMethod.POST, consumes = "text/plain")
public ModelAndView someMethod(@RequestBody String postPayload) {
// ...
}
``````

### how do you filter pandas dataframes by multiple columns

In case somebody wonders what is the faster way to filter (the accepted answer or the one from @redreamality):

``````import pandas as pd
import numpy as np

length = 100_000
df = pd.DataFrame()
df['Year'] = np.random.randint(1950, 2019, size=length)
df['Gender'] = np.random.choice(['Male', 'Female'], length)

%timeit df.query('Gender=="Male" & Year=="2014" ')
%timeit df[(df['Gender']=='Male') & (df['Year']==2014)]
``````

Results for 100,000 rows:

``````6.67 ms ± 557 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
5.54 ms ± 536 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
``````

Results for 10,000,000 rows:

``````326 ms ± 6.52 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
472 ms ± 25.1 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
``````

So results depend on the size and the data. On my laptop, `query()` gets faster after 500k rows. Further, the string search in `Year=="2014"` has an unnecessary overhead (`Year==2014` is faster).

### What is the shortest function for reading a cookie by name in JavaScript?

This will only ever hit document.cookie ONE time. Every subsequent request will be instant.

``````(function(){

for(i=c.length-1; i>=0; i--){
C = c[i].split('=');
}

}

})();
``````

I'm afraid there really isn't a faster way than this general logic unless you're free to use `.forEach` which is browser dependent (even then you're not saving that much)

Your own example slightly compressed to `120 bytes`:

``````function read_cookie(k,r){return(r=RegExp('(^|; )'+encodeURIComponent(k)+'=([^;]*)').exec(document.cookie))?r[2]:null;}
``````

You can get it to `110 bytes` if you make it a 1-letter function name, `90 bytes` if you drop the `encodeURIComponent`.

I've gotten it down to `73 bytes`, but to be fair it's `82 bytes` when named `readCookie` and `102 bytes` when then adding `encodeURIComponent`:

``````function C(k){return(document.cookie.match('(^|; )'+k+'=([^;]*)')||0)[2]}
``````

### What is the default Jenkins password?

On ubuntu 19.04, the default password are stored in the home directory:

``````cat ~/.jenkins/secrets/initialAdminPassword
``````

### rotate image with css

The trouble looks like the image isn't square and the browser adjusts as such. After rotation ensure the dimensions are retained by changing the image margin.

``````.imagetest img {
transform: rotate(270deg);
...
margin: 10px 0px;
}
``````

The amount will depend on the difference in height x width of the image. You may also need to add `display:inline-block;` or `display:block` to get it to recognize the margin parameter.

### Which Android phones out there do have a gyroscope?

Since I have recently developed an Android application using gyroscope data (steady compass), I tried to collect a list with such devices. This is not an exhaustive list at all, but it is what I have so far:

*** Phones:

• HTC Sensation
• HTC Sensation XL
• HTC Evo 3D
• HTC One S
• HTC One X
• Huawei Ascend P1
• Huawei Ascend X (U9000)
• Huawei Honor (U8860)
• LG Nitro HD (P930)
• LG Optimus 2x (P990)
• LG Optimus Black (P970)
• LG Optimus 3D (P920)
• Samsung Galaxy S II (i9100)
• Samsung Galaxy S III (i9300)
• Samsung Galaxy R (i9103)
• Samsung Google Nexus S (i9020)
• Samsung Galaxy Nexus (i9250)
• Samsung Galaxy J3 (2017) model
• Samsung Galaxy Note (n7000)
• Sony Xperia P (LT22i)
• Sony Xperia S (LT26i)

*** Tablets:

• Acer Iconia Tab A100 (7")
• Acer Iconia Tab A500 (10.1")
• Asus Eee Pad Transformer (TF101)
• Asus Eee Pad Transformer Prime (TF201)
• Motorola Xoom (mz604)
• Samsung Galaxy Tab (p1000)
• Samsung Galaxy Tab 7 plus (p6200)
• Samsung Galaxy Tab 10.1 (p7100)
• Sony Tablet P
• Sony Tablet S
• Toshiba Thrive 7"
• Toshiba Trhive 10"

Hope the list keeps growing and hope that gyros will be soon available on mid and low price smartphones.

### How to convert PDF files to images

The PDF engine used in Google Chrome, called PDFium, is open source under the "BSD 3-clause" license. I believe this allows redistribution when used in a commercial product.

There is a .NET wrapper for it called PdfiumViewer (NuGet) which works well to the extent I have tried it. It is under the Apache license which also allows redistribution.

(Note that this is NOT the same 'wrapper' as https://pdfium.patagames.com/ which requires a commercial license*)

(There is one other PDFium .NET wrapper, PDFiumSharp, but I have not evaluated it.)

In my opinion, so far, this may be the best choice of open-source (free as in beer) PDF libraries to do the job which do not put restrictions on the closed-source / commercial nature of the software utilizing them. I don't think anything else in the answers here satisfy that criteria, to the best of my knowledge.

### How do you Sort a DataTable given column and direction?

Create a DataView. You cannot sort a DataTable directly, but you can create a DataView from the DataTable and sort that.

The following code example creates a view that shows all the products where the number of units in stock is less than or equal to the reorder level, sorted first by supplier ID and then by product name.

```DataView prodView = new DataView(prodDS.Tables["Products"], "UnitsInStock <= ReorderLevel", "SupplierID, ProductName", DataViewRowState.CurrentRows);```

### Shortest distance between a point and a line segment

This algorithm is based on finding the intersection between the specified line and the orthogonal line, which contains the specified point, and calculating its distance. In case of a line segment, we must check if the intersection is between points of the line segment, if that's not the case then the minimum distance is between the specified point and one of the ending points of the line segment. This is a C# implementation.

``````Double Distance(Point a, Point b)
{
double xdiff = a.X - b.X, ydiff = a.Y - b.Y;
return Math.Sqrt((long)xdiff * xdiff + (long)ydiff * ydiff);
}

Boolean IsBetween(double x, double a, double b)
{
return ((a <= b && x >= a && x <= b) || (a > b && x <= a && x >= b));
}

Double GetDistance(Point pt, Point pt1, Point pt2, out Point intersection)
{
Double a, x, y, R;

if (pt1.X != pt2.X) {
a = (double)(pt2.Y - pt1.Y) / (pt2.X - pt1.X);
x = (a * (pt.Y - pt1.Y) + a * a * pt1.X + pt.X) / (a * a + 1);
y = a * x + pt1.Y - a * pt1.X; }
else { x = pt1.X;  y = pt.Y; }

if (IsBetween(x, pt1.X, pt2.X) && IsBetween(y, pt1.Y, pt2.Y)) {
intersection = new Point((int)x, (int)y);
R = Distance(intersection, pt); }
else {
double d1 = Distance(pt, pt1), d2 = Distance(pt, pt2);
if (d1 < d2) { intersection = pt1; R = d1; }
else { intersection = pt2; R = d2; }}

return R;
}
``````

### java.io.FileNotFoundException: (Access is denied)

Here's a gotcha that I just discovered - perhaps it might help someone else. If using windows the classes folder must not have encryption enabled! Tomcat doesn't seem to like that. Right click on the classes folder, select "Properties" and then click the "Advanced..." button. Make sure the "Encrypt contents to secure data" checkbox is cleared. Restart Tomcat.

It worked for me so here's hoping it helps someone else, too.

### How to get response as String using retrofit without using GSON or any other library in android

** Update ** A scalars converter has been added to retrofit that allows for a `String` response with less ceremony than my original answer below.

Example interface --

``````public interface GitHubService {
@GET("/users/{user}")
Call<String> listRepos(@Path("user") String user);
}
``````

Add the `ScalarsConverterFactory` to your retrofit builder. Note: If using `ScalarsConverterFactory` and another factory, add the scalars factory first.

``````Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
// add other factories here, if needed.
.build();
``````

You will also need to include the scalars converter in your gradle file --

``````implementation 'com.squareup.retrofit2:converter-scalars:2.1.0'
``````

--- Original Answer (still works, just more code) ---

I agree with @CommonsWare that it seems a bit odd that you want to intercept the request to process the JSON yourself. Most of the time the POJO has all the data you need, so no need to mess around in `JSONObject` land. I suspect your specific problem might be better solved using a custom gson `TypeAdapter` or a retrofit `Converter` if you need to manipulate the JSON. However, retrofit provides more the just JSON parsing via Gson. It also manages a lot of the other tedious tasks involved in REST requests. Just because you don't want to use one of the features, doesn't mean you have to throw the whole thing out. There are times you just want to get the raw stream, so here is how to do it -

First, if you are using Retrofit 2, you should start using the `Call` API. Instead of sending an object to convert as the type parameter, use `ResponseBody` from okhttp --

``````public interface GitHubService {
@GET("/users/{user}")
Call<ResponseBody> listRepos(@Path("user") String user);
}
``````

then you can create and execute your call --

``````GitHubService service = retrofit.create(GitHubService.class);
result.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Response<ResponseBody> response) {
try {
System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}

@Override
public void onFailure(Throwable t) {
e.printStackTrace();
}
});
``````

Note The code above calls `string()` on the response object, which reads the entire response into a String. If you are passing the body off to something that can ingest streams, you can call `charStream()` instead. See the `ResponseBody` docs.

### vba error handling in loop

I do not want to craft special error handlers for every loop structure in my code so I have a way of finding problem loops using my standard error handler so that I can then write a special error handler for them.

If an error occurs in a loop, I normally want to know about what caused the error rather than just skip over it. To find out about these errors, I write error messages to a log file as many people do. However writing to a log file is dangerous if an error occurs in a loop as the error can be triggered for every time the loop iterates and in my case 80 000 iterations is not uncommon. I have therefore put some code into my error logging function that detects identical errors and skips writing them to the error log.

My standard error handler that is used on every procedure looks like this. It records the error type, procedure the error occurred in and any parameters the procedure received (FileType in this case).

``````procerr:
Resume exitproc
``````

My error logging function which writes to a table (I am in ms-access) is as follows. It uses static variables to retain the previous values of error data and compare them to current versions. The first error is logged, then the second identical error pushes the application into debug mode if I am the user or if in other user mode, quits the application.

``````Public Function NewErrorLog(ErrCode As Variant, ErrDesc As Variant, Optional Source As Variant = "", Optional ErrData As Variant = Null) As Boolean
On Error GoTo errLogError

'Records errors from application code
Dim dbs As Database
Dim rst As Recordset

Dim ErrorLogID As Long
Dim StackInfo As String
Dim MustQuit As Boolean
Dim i As Long

Static ErrCodeOld As Long
Static SourceOld As String
Static ErrDataOld As String

'Detects errors that occur in loops and records only the first two.
If Nz(ErrCode, 0) = ErrCodeOld And Nz(Source, "") = SourceOld And Nz(ErrData, "") = ErrDataOld Then
MsgBox "Error has occured in a loop: " & Nz(ErrCode, 0) & Space(1) & Nz(ErrDesc, "") & ": " & Nz(Source, "") & "[" & Nz(ErrData, "") & "]", vbExclamation, Appname
If Not gDeveloping Then  'Allow debugging
Stop
Exit Function
Else
ErrDesc = "[loop]" & Nz(ErrDesc, "")  'Flag this error as coming from a loop
MsgBox "Error has been logged, now Quiting", vbInformation, Appname
MustQuit = True  'will Quit after error has been logged
End If
Else
'Save current values to static variables
ErrCodeOld = Nz(ErrCode, 0)
SourceOld = Nz(Source, "")
ErrDataOld = Nz(ErrData, "")
End If

'From FMS tools pushstack/popstack - tells me the names of the calling procedures
For i = 1 To UBound(mCallStack)
If Len(mCallStack(i)) > 0 Then StackInfo = StackInfo & "\" & mCallStack(i)
Next

'Open error table
Set dbs = CurrentDb()
Set rst = dbs.OpenRecordset("tbl_ErrLog", dbOpenTable)

'Write the error to the error table
With rst
!ErrSource = Source
!ErrTime = Now()
!ErrCode = ErrCode
!ErrDesc = ErrDesc
!ErrData = ErrData
!StackTrace = StackInfo
.Update
.BookMark = .LastModified
ErrorLogID = !ErrLogID
End With

rst.Close: Set rst = Nothing
dbs.Close: Set dbs = Nothing
DoCmd.Hourglass False
DoCmd.Echo True
DoEvents
If MustQuit = True Then DoCmd.Quit

exitLogError:
Exit Function

errLogError:
MsgBox "An error occured whilst logging the details of another error " & vbNewLine & _
"Send details to Developer: " & Err.number & ", " & Err.Description, vbCritical, "Please e-mail this message to developer"
Resume exitLogError

End Function
``````

Note that an error logger has to be the most bullet proofed function in your application as the application cannot gracefully handle errors in the error logger. For this reason, I use NZ() to make sure that nulls cannot sneak in. Note that I also add [loop] to the second identical error so that I know to look in the loops in the error procedure first.

### What is the difference between parseInt(string) and Number(string) in JavaScript?

The `parseInt` function allows you to specify a radix for the input string and is limited to integer values.

``````parseInt('Z', 36) === 35
``````

The `Number` constructor called as a function will parse the string with a grammar and is limited to base 10 and base 16.

```StringNumericLiteral :::
StrWhiteSpaceopt
StrWhiteSpaceopt StrNumericLiteral StrWhiteSpaceopt

StrWhiteSpace :::
StrWhiteSpaceChar StrWhiteSpaceopt

StrWhiteSpaceChar :::
WhiteSpace
LineTerminator

StrNumericLiteral :::
StrDecimalLiteral
HexIntegerLiteral

StrDecimalLiteral :::
StrUnsignedDecimalLiteral
+ StrUnsignedDecimalLiteral
- StrUnsignedDecimalLiteral

StrUnsignedDecimalLiteral :::
Infinity
DecimalDigits . DecimalDigitsopt ExponentPartopt
. DecimalDigits ExponentPartopt
DecimalDigits ExponentPartopt

DecimalDigits :::
DecimalDigit
DecimalDigits DecimalDigit

DecimalDigit ::: one of
0 1 2 3 4 5 6 7 8 9

ExponentPart :::
ExponentIndicator SignedInteger

ExponentIndicator ::: one of
e E

SignedInteger :::
DecimalDigits
+ DecimalDigits
- DecimalDigits

HexIntegerLiteral :::
0x HexDigit
0X HexDigit
HexIntegerLiteral HexDigit

HexDigit ::: one of
0 1 2 3 4 5 6 7 8 9 a b c d e f A B C D E F
```

### Input mask for numeric and decimal

Try imaskjs. It has Number, RegExp and other masks. Very simple to extend.

### Return row number(s) for a particular value in a column in a dataframe

Use `which(mydata_2\$height_chad1 == 2585)`

Short example

``````df <- data.frame(x = c(1,1,2,3,4,5,6,3),
y = c(5,4,6,7,8,3,2,4))
df
x y
1 1 5
2 1 4
3 2 6
4 3 7
5 4 8
6 5 3
7 6 2
8 3 4

which(df\$x == 3)
[1] 4 8

length(which(df\$x == 3))
[1] 2

count(df, vars = "x")
x freq
1 1    2
2 2    1
3 3    2
4 4    1
5 5    1
6 6    1

df[which(df\$x == 3),]
x y
4 3 7
8 3 4
``````

As Matt Weller pointed out, you can use the `length` function. The `count` function in `plyr` can be used to return the count of each unique column value.

### How do I create sql query for searching partial matches?

First of all, this approach won't scale in the large, you'll need a separate index from words to item (like an inverted index).

If your data is not large, you can do

``````SELECT DISTINCT(name) FROM mytable WHERE name LIKE '%mall%' OR description LIKE '%mall%'
``````

using `OR` if you have multiple keywords.

### How do you get the logical xor of two variables in Python?

• Python logical `or`: `A or B`: returns `A` if `bool(A)` is `True`, otherwise returns `B`
• Python logical `and`: `A and B`: returns `A` if `bool(A)` is `False`, otherwise returns `B`

To keep most of that way of thinking, my logical xor definintion would be:

``````def logical_xor(a, b):
if bool(a) == bool(b):
return False
else:
return a or b
``````

That way it can return `a`, `b`, or `False`:

``````>>> logical_xor('this', 'that')
False
>>> logical_xor('', '')
False
>>> logical_xor('this', '')
'this'
>>> logical_xor('', 'that')
'that'
``````

### What is HTTP "Host" header?

The `Host` Header tells the webserver which virtual host to use (if set up). You can even have the same virtual host using several aliases (= domains and wildcard-domains). In this case, you still have the possibility to read that header manually in your web app if you want to provide different behavior based on different domains addressed. This is possible because in your webserver you can (and if I'm not mistaken you must) set up one vhost to be the default host. This default vhost is used whenever the `host` header does not match any of the configured virtual hosts.

That means: You get it right, although saying "multiple hosts" may be somewhat misleading: The host (the addressed machine) is the same, what really gets resolved to the IP address are different domain names (including subdomains) that are also referred to as hostnames (but not hosts!).

Although not part of the question, a fun fact: This specification led to problems with SSL in early days because the web server has to deliver the certificate that corresponds to the domain the client has addressed. However, in order to know what certificate to use, the webserver should have known the addressed hostname in advance. But because the client sends that information only over the encrypted channel (which means: after the certificate has already been sent), the server had to assume you browsed the default host. That meant one ssl-secured domain per IP address / port-combination.

This has been overcome with Server Name Indication; however, that again breaks some privacy, as the server name is now transferred in plain text again, so every man-in-the-middle would see which hostname you are trying to connect to.

Although the webserver would know the hostname from Server Name Indication, the `Host` header is not obsolete, because the Server Name Indication information is only used within the TLS handshake. With an unsecured connection, there is no Server Name Indication at all, so the `Host` header is still valid (and necessary).

Another fun fact: Most webservers (if not all) reject your HTTP request if it does not contain exactly one `Host` header, even if it could be omitted because there is only the default vhost configured. That means the minimum required information in an http-(get-)request is the first line containing `METHOD` `RESOURCE` and `PROTOCOL VERSION` and at least the `Host` header, like this:

``````GET /someresource.html HTTP/1.1
Host: www.example.com
``````

In the MDN Documentation on the "Host" header they actually phrase it like this:

A Host header field must be sent in all HTTP/1.1 request messages. A 400 (Bad Request) status code will be sent to any HTTP/1.1 request message that lacks a Host header field or contains more than one.

As mentioned by Darrel Miller, the complete specs can be found in RFC7230.

### Get all rows from SQLite

Update `queueAll()` method as below:

``````public Cursor queueAll() {

String selectQuery = "SELECT * FROM " + MYDATABASE_TABLE;
Cursor cursor = sqLiteDatabase.rawQuery(selectQuery, null);

return cursor;
}
``````

Update `readFileFromSQLite()` method as below:

``````public ArrayList<String> readFileFromSQLite() {

fileName = new ArrayList<String>();

if (cursor != null) {
if (cursor.moveToFirst()) {
do
{