# Programs & Examples On #Physics

Refers to real-world physics. For simulation of physics in games use the [game-physics] tag instead, for questions using an existing physics engine use [physics-engine]. Physics is a science that studies the interactions of energy and matter. Questions with this tag concern the simulation or implementation of real-world physics concepts in programming.

### Unity 2d jumping script

``````GetComponent<Rigidbody2D>().AddForce(new Vector2(0,10), ForceMode2D.Impulse);
``````

I also want to add that this leaves the jump height super private and only editable in the script, so this is what I did...

``````    public float playerSpeed;  //allows us to be able to change speed in Unity
public Vector2 jumpHeight;

// Use this for initialization
void Start () {

}
// Update is called once per frame
void Update ()
{
transform.Translate(playerSpeed * Time.deltaTime, 0f, 0f);  //makes player run

if (Input.GetMouseButtonDown(0) || Input.GetKeyDown(KeyCode.Space))  //makes player jump
{
``````

This makes it to where you can edit the jump height in Unity itself without having to go back to the script.

Side note - I wanted to comment on the answer above, but I can't because I'm new here. :)

### Ball to Ball Collision - Detection and Handling

After some trial and error, I used this document's method for 2D collisions : https://www.vobarian.com/collisions/2dcollisions2.pdf (that OP linked to)

I applied this within a JavaScript program using p5js, and it works perfectly. I had previously attempted to use trigonometrical equations and while they do work for specific collisions, I could not find one that worked for every collision no matter the angle at the which it happened.

The method explained in this document uses no trigonometrical functions whatsoever, it's just plain vector operations, I recommend this to anyone trying to implement ball to ball collision, trigonometrical functions in my experience are hard to generalize. I asked a Physicist at my university to show me how to do it and he told me not to bother with trigonometrical functions and showed me a method that is analogous to the one linked in the document.

NB : My masses are all equal, but this can be generalised to different masses using the equations presented in the document.

Here's my code for calculating the resulting speed vectors after collision :

``````    //you just need a ball object with a speed and position vector.
class TBall {
constructor(x, y, vx, vy) {
this.r = [x, y];
this.v = [0, 0];
}
}

//throw two balls into this function and it'll update their speed vectors
//if they collide, you need to call this in your main loop for every pair of
//balls.
function collision(ball1, ball2) {
n = [ (ball1.r)[0] - (ball2.r)[0], (ball1.r)[1] - (ball2.r)[1] ];
un = [n[0] /  vecNorm(n), n[1] / vecNorm(n) ] ;
ut = [ -un[1], un[0] ];
v1n = dotProd(un, (ball1.v));
v1t = dotProd(ut, (ball1.v) );
v2n = dotProd(un, (ball2.v) );
v2t = dotProd(ut, (ball2.v) );
v1t_p = v1t; v2t_p = v2t;
v1n_p = v2n; v2n_p = v1n;
v1n_pvec = [v1n_p * un[0], v1n_p * un[1] ];
v1t_pvec = [v1t_p * ut[0], v1t_p * ut[1] ];
v2n_pvec = [v2n_p * un[0], v2n_p * un[1] ];
v2t_pvec = [v2t_p * ut[0], v2t_p * ut[1] ];
ball1.v = vecSum(v1n_pvec, v1t_pvec); ball2.v = vecSum(v2n_pvec, v2t_pvec);
}

``````

### Heap space out of memory

There is no way to dynamically increase the heap programatically since the heap is allocated when the Java Virtual Machine is started.

However, you can use this command

``````java -Xmx1024M YourClass
``````

to set the memory to 1024

or, you can set a min max

``````java -Xms256m -Xmx1024m YourClassNameHere
``````

### JSON for List of int

JSON is perfectly capable of expressing lists of integers, and the JSON you have posted is valid. You can simply separate the integers by commas:

``````{
"Id": "610",
"Name": "15",
"Description": "1.99",
"ItemModList": [42, 47, 139]
}
``````

### How do I make a transparent border with CSS?

hey this is the best solution I ever experienced.. this is CSS3

use following property to your div or anywhere you wanna put border trasparent

e.g.

``````div_class {
border: 10px solid #999;
background-clip: padding-box; /* Firefox 4+, Opera, for IE9+, Chrome */
}
``````

this will work..

### Java: Check if enum contains a given string?

It is an enum, those are constant values so if its in a switch statement its just doing something like this:

``````case: val1
case: val2
``````

Also why would you need to know what is declared as a constant?

### How to check size of a file using Bash?

I would use `du`'s `--threshold` for this. Not sure if this option is available in all versions of `du` but it is implemented in GNU's version.

Quoting from du(1)'s manual:

``````-t, --threshold=SIZE
exclude entries smaller than SIZE if positive, or entries greater
than SIZE if negative
``````

Here's my solution, using `du --threshold=` for OP's use case:

``````THRESHOLD=90k
if [[ -z "\$(du --threshold=\${THRESHOLD} file.txt)" ]]; then
mail -s "file.txt size is below \${THRESHOLD}, please fix. " [email protected] < /dev/null
mv -f /root/tmp/file.txt /var/www/file.txt
fi
``````

The advantage of that, is that `du` can accept an argument to that option in a known format - either human as in `10K`, `10MiB` or what ever you feel comfortable with - you don't need to manually convert between formats / units since `du` handles that.

For reference, here's the explanation on this `SIZE` argument from the man page:

``````The SIZE argument is an integer and optional unit (example: 10K is
10*1024). Units are K,M,G,T,P,E,Z,Y (powers of 1024) or KB,MB,... (powers
of 1000). Binary prefixes can be used, too: KiB=K, MiB=M, and so on.
``````

### How to fix "Only one expression can be specified in the select list when the subquery is not introduced with EXISTS" error?

Try this:

`````` Select
Id,
Salt,
BannedEndDate,
(Select Count(*)
From Users
``````

And I recommend you strongly to use parameters in your query to avoid security risks with sql injection attacks!

Hope that helps!

### How do I ALTER a PostgreSQL table and make a column unique?

I figured it out from the PostgreSQL docs, the exact syntax is:

``````ALTER TABLE the_table ADD CONSTRAINT constraint_name UNIQUE (thecolumn);
``````

Thanks Fred.

### PHP - syntax error, unexpected T_CONSTANT_ENCAPSED_STRING

``````'<option value=''.\$key.'">'
``````

should be

``````'<option value="'.\$key.'">'
``````

### socket.error: [Errno 10013] An attempt was made to access a socket in a way forbidden by its access permissions

I solved this on Windows 10 by editing an outbound firewall rule. Right click "allow" on rule "Block network access for R local user accounts in SQL Server instance MSSQLSERVER"

Screenshot from Windows 10 Firewall - Outbound rules- this is what was blocking my instance

### final keyword in method parameters

final means you can't change the value of that variable once it was assigned.

Meanwhile, the use of final for the arguments in those methods means it won't allow the programmer to change their value during the execution of the method. This only means that inside the method the final variables can not be reassigned.

### Get the records of last month in SQL server

SQL query to get record of the present month only

``````SELECT * FROM CUSTOMER
WHERE MONTH(DATE) = MONTH(CURRENT_TIMESTAMP) AND YEAR(DATE) = YEAR(CURRENT_TIMESTAMP);
``````

### CFNetwork SSLHandshake failed iOS 9

After two days of attempts and failures, what worked for me is this code of womble

with One change, according to this post we should stop using sub-keys associated with the NSExceptionDomains dictionary of that kind of Convention

``````  NSTemporaryExceptionMinimumTLSVersion
``````

And use at the new Convention

``````  NSExceptionMinimumTLSVersion
``````

apple documentation

my code

``````<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>YOUR_HOST.COM</key>
<dict>
<true/>
<key>NSExceptionMinimumTLSVersion</key>
<string>TLSv1.0</string>
<key>NSExceptionRequiresForwardSecrecy</key>
<false/>
<key>NSIncludesSubdomains</key>
<true/>
</dict>
</dict>
</dict>
``````

### Loop through an array in JavaScript

``````//Make array
var array = ["1","2","3","4","5","6","7","8","9","10"]
//Loop
for(var i = 0; i < array.length; i++){
console.log((i+1) + " --> " + array[i])
}
``````

For the ACTUAL number for `i`, you need to change `(i+1)` to `i` or `(i)`, if you want.
Hope this helped.

### Installing SetupTools on 64-bit Windows

Get the file `register.py` from this gist. Save it on your C drive or D drive, go to CMD to run it with:

``````'python register.py'
``````

Then you will be able to install it.

### How do I make a https post in Node Js without any third party module?

For example, like this:

``````const querystring = require('querystring');
const https = require('https');

var postData = querystring.stringify({
'msg' : 'Hello World!'
});

var options = {
hostname: 'posttestserver.com',
port: 443,
path: '/post.php',
method: 'POST',
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': postData.length
}
};

var req = https.request(options, (res) => {
console.log('statusCode:', res.statusCode);

res.on('data', (d) => {
process.stdout.write(d);
});
});

req.on('error', (e) => {
console.error(e);
});

req.write(postData);
req.end();
``````

### Angular 5 ngHide ngShow [hidden] not working

If you add [hidden]="true" to div, the actual thing that happens is adding a class [hidden] to this element conditionally with display: none

Please check the style of the element in the browser to ensure no other style affect the display property of an element like this:

If you found display of [hidden] class is overridden, you need to add this css code to your style:

``````[hidden] {
display: none !important;
}
``````

### how to remove untracked files in Git?

While `git clean` works well, I still find it useful to use my own script to clean the git repo, it has some advantages.

This shows a list of files to be cleaned, then interactively prompts to clean or not. This is nearly always what I want since interactively prompting per file gets tedious.

It also allows manual filtering of the list which comes in handy when there are file types you don't want to clean (and have reason not to commit).

`git_clean.sh`

``````#!/bin/bash
readarray -t -d '' FILES < <(
git ls-files -z --other --directory |
grep --null-data --null -v '.bin\$\|Cargo.lock\$'
)
if [ "\$FILES" = "" ]; then
echo  "Nothing to clean!"
exit 0
fi

echo "Dirty files:"
printf '  %s\n' "\${FILES[@]}"

DO_REMOVE=0
while true; do
echo ""
read -p "Remove \${#FILES[@]} files? [y/n]: " choice
case "\$choice" in
y|Y )
DO_REMOVE=1
break ;;
n|N )
echo "Exiting!"
break ;;
* ) echo "Invalid input, expected [Y/y/N/n]"
continue ;;
esac
done

if [ "\$DO_REMOVE" -eq 1 ];then
echo "Removing!"
for f in "\${FILES[@]}"; do
rm -rfv "\$f"
done
fi
``````

### Check cell for a specific letter or set of letters

You can use `RegExMatch`:

``````=IF(RegExMatch(A1;"Bla");"YES";"NO")
``````

### How can I add a vertical scrollbar to my div automatically?

To show vertical scroll bar in your div you need to add

``````height: 100px;
overflow-y : scroll;
``````

or

``````height: 100px;
overflow-y : auto;
``````

### How to give a pattern for new line in grep?

just found

``````grep \$'\r'
``````

It's using `\$'\r'` for c-style escape in Bash.

### Why are primes important in cryptography?

I'm not a mathematician or cryptician, so here's an outside observation in layman's terms (no fancy equations, sorry).

This whole thread is filled with explanations about HOW primes are used in cryptography, it's hard to find anyone in this thread explaining in an easy way WHY primes are used ... most likely because everyone takes that knowledge for granted.

Only looking at the problem from the outside can generate a reaction like; but if they use the sums of two primes, why not create a list of all possible sums any two primes can generate?

On this site there's a list of 455,042,511 primes, where the highest primes is 9,987,500,000 (10 digits).

The largest known prime (as of feb 2015) is 2 to the power of 257,885,161 - 1 which is 17,425,170 digits.

This means that there's no point keeping a list of all the known primes and much less all their possible sums. It's easier to take a number and check if it's a prime.

Calculating big primes in itself is a monumental task, so reverse calculating two primes that has been multiplied with each other both cryptographers and mathematicians would say is hard enough ... today.

### Convert time span value to format "hh:mm Am/Pm" using C#

``````Parse timespan to DateTime. For Example.
//The time will be "8.30 AM" or "10.00 PM" or any time like this format.
public TimeSpan GetTimeSpanValue(string displayValue)
{
DateTime dateTime = DateTime.Now;
if (displayValue.StartsWith("10") || displayValue.StartsWith("11") || displayValue.StartsWith("12"))
dateTime = DateTime.ParseExact(displayValue, "hh:mm tt", CultureInfo.InvariantCulture);
else
dateTime = DateTime.ParseExact(displayValue, "h:mm tt", CultureInfo.InvariantCulture);
return dateTime.TimeOfDay;
}
``````

### oracle varchar to number

I have tested the suggested solutions, they should all work:

``````select * from dual where (105 = to_number('105'))
``````

=> delivers one dummy row

``````select * from dual where (10 = to_number('105'))
``````

=> empty result

``````select * from dual where ('105' = to_char(105))
``````

=> delivers one dummy row

``````select * from dual where ('105' = to_char(10))
``````

=> empty result

### Restart container within pod

There are cases when you want to restart a specific container instead of deleting the pod and letting Kubernetes recreate it.

Doing a `kubectl exec POD_NAME -c CONTAINER_NAME /sbin/killall5` worked for me.

(I changed the command from `reboot` to `/sbin/killall5` based on the below recommendations.)

### What is the meaning of the CascadeType.ALL for a @ManyToOne JPA association

In JPA 2.0 if you want to delete an address if you removed it from a User entity you can add `orphanRemoval=true` (instead of `CascadeType.REMOVE`) to your `@OneToMany`.

More explanation between `orphanRemoval=true` and `CascadeType.REMOVE` is here.

### rails 3 validation on uniqueness on multiple attributes

#### Multiple Scope Parameters:

``````class TeacherSchedule < ActiveRecord::Base
validates_uniqueness_of :teacher_id, :scope => [:semester_id, :class_id]
end
``````

http://apidock.com/rails/ActiveRecord/Validations/ClassMethods/validates_uniqueness_of

### How to configure slf4j-simple

You can programatically change it by setting the system property:

``````public class App {

public static void main(String[] args) {

System.setProperty(org.slf4j.impl.SimpleLogger.DEFAULT_LOG_LEVEL_KEY, "TRACE");

final org.slf4j.Logger log = LoggerFactory.getLogger(App.class);

log.trace("trace");
log.debug("debug");
log.info("info");
log.warn("warning");
log.error("error");

}
}
``````

The log levels are ERROR > WARN > INFO > DEBUG > TRACE.

Please note that once the logger is created the log level can't be changed. If you need to dynamically change the logging level you might want to use log4j with SLF4J.

### Git stash pop- needs merge, unable to refresh index

You need to add `app.coffee` to staging.

Do `git add app.coffee` and then you will be able to apply your stash (after that commit and push).

### Difference Between \$.getJSON() and \$.ajax() in jQuery

Replace

``````data: { patientID: "1" },
``````

with

``````data: "{ 'patientID': '1' }",
``````

Further reading: 3 mistakes to avoid when using jQuery with ASP.NET

### Insert variable values in the middle of a string

1 You can use `string.Replace` method

``````var sample = "testtesttesttest#replace#testtesttest";
var result = sample.Replace("#replace#", yourValue);
``````

2 You can also use `string.Format`

``````var result = string.Format("your right part {0} Your left Part", yourValue);
``````

3 You can use Regex class

### JavaScript replace/regex

In terms of pattern interpretation, there's no difference between the following forms:

• `/pattern/`
• `new RegExp("pattern")`

If you want to replace a literal string using the `replace` method, I think you can just pass a string instead of a regexp to `replace`.

Otherwise, you'd have to escape any regexp special characters in the pattern first - maybe like so:

``````function reEscape(s) {
return s.replace(/([.*+?^\$|(){}\[\]])/mg, "\\\$1");
}

// ...

var re = new RegExp(reEscape(pattern), "mg");
this.markup = this.markup.replace(re, value);
``````

### Using SSH keys inside docker container

One cross-platform solution is to use a bind mount to share the host's `.ssh` folder to the container:

``````docker run -v /home/<host user>/.ssh:/home/<docker user>/.ssh <image>
``````

Similar to agent forwarding this approach will make the public keys accessible to the container. An additional upside is that it works with a non-root user too and will get you connected to GitHub. One caveat to consider, however, is that all contents (including private keys) from the `.ssh` folder will be shared so this approach is only desirable for development and only for trusted container images.

### How can I hide an HTML table row <tr> so that it takes up no space?

HTML:

``````<input type="checkbox" id="attraction" checked="checked" onchange="updateMap()">poi.attraction</input>
``````

JavaScript:

``````function updateMap() {
map.setOptions({'styles': getStyles() });
}

function getStyles() {
var styles = [];
for (var i=0; i < types.length; i++) {
var style = {};
var type = types[i];
var enabled = document.getElementById(type).checked;
style['featureType'] = 'poi.' + type;
style['elementType'] = 'labels';
style['stylers'] = [{'visibility' : (enabled ? 'on' : 'off') }];
styles.push(style);
}
return styles;
}
``````

### source of historical stock data

Yahoo is the simplest option to get preliminary free data. The link described in eckesicle's answer could be easily used in a python code, but you first need all the tickers. I'd use the NYSE for this example, but this can be used for different exchanges as well.

I used this wiki page to download all company tickers with the following script (I'm not a very talented Pythonist, sorry if this code isn't very efficient):

``````import string
import urllib2
from bs4 import BeautifulSoup

global f

aurl = urllib2.urlopen(url)

print url

for row in soup('table')[1]('tr'):
tds = row('td')
if (len(tds) > 0):
f.write(tds[1].string + '\n')

f = open('stock_names.txt', 'w')

url_part1 = 'http://en.wikipedia.org/wiki/Companies_listed_on_the_New_York_Stock_Exchange_'
url = url_part1 + '(0-9)'

for letter in string.uppercase[:26]:
url_part2 = letter
url = url_part1 + '(' + letter + ')'

f.close()
``````

``````import string
import urllib2
from bs4 import BeautifulSoup

global f

url_part1 = 'http://ichart.finance.yahoo.com/table.csv?s='
url_part2 = '&d=0&e=28&f=2010&g=d&a=3&b=12&c=1996&ignore=.csv'

print "Starting"

f = open('stock_names.txt', 'r')
count = 1;

for ticker in file_content:
ticker = ticker.strip()
url = url_part1 + ticker + url_part2

try:
# This will cause exception on a 404
response = urllib2.urlopen(url)

count = count + 1
history_file = open('C:\\Users\\Nitay\\Desktop\\Historical Data\\' + ticker + '.csv', 'w')
history_file.close()

except Exception, e:
pass

f.close()
``````

Notice that the major downside to this method is that different data is available for different companies - Companies that don't have data existing in the requested dates (newly listed) will get you a 404 page.

Also keep in mind that this method is only good for preliminary data - If you really want to test your algorithm you should pay a bit and use a trusted data supplier like CSIData or others

### How to put labels over geom_bar for each bar in R with ggplot2

To add to rcs' answer, if you want to use position_dodge() with geom_bar() when x is a POSIX.ct date, you must multiply the width by 86400, e.g.,

``````ggplot(data=dat, aes(x=Types, y=Number, fill=sample)) +
geom_bar(position = "dodge", stat = 'identity') +
geom_text(aes(label=Number), position=position_dodge(width=0.9*86400), vjust=-0.25)
``````

### Difference between long and int data types

A typical best practice is not using long/int/short directly. Instead, according to specification of compilers and OS, wrap them into a header file to ensure they hold exactly the amount of bits that you want. Then use int8/int16/int32 instead of long/int/short. For example, on 32bit Linux, you could define a header like this

``````typedef char int8;
typedef short int16;
typedef int int32;
typedef unsigned int uint32;
``````

### How to lookup JNDI resources on WebLogic?

`java` is the root JNDI namespace for resources. What the original snippet of code means is that the container the application was initially deployed in did not apply any additional namespaces to the JNDI context you retrieved (as an example, Tomcat automatically adds all resources to the namespace `comp/env`, so you would have to do `dataSource = (javax.sql.DataSource) context.lookup("java:comp/env/jdbc/myDataSource");` if the resource reference name is `jdbc/myDataSource`).

To avoid having to change your legacy code I think if you register the datasource with the name `myDataSource` (remove the `jdbc/`) you should be fine. Let me know if that works.

### Spark specify multiple column conditions for dataframe join

There is a Spark column/expression API join for such case:

``````Leaddetails.join(
Utm_Master,
"left"
)
``````

The `<=>` operator in the example means "Equality test that is safe for null values".

The main difference with simple Equality test (`===`) is that the first one is safe to use in case one of the columns may have null values.

### How to compile or convert sass / scss to css with node-sass (no Ruby)?

In Windows 10 using node v6.11.2 and npm v3.10.10, in order to execute directly in any folder:

``````> node-sass [options] <input.scss> [output.css]
``````

I only followed the instructions in node-sass Github:

1. Add node-gyp prerequisites by running as Admin in a Powershell (it takes a while):

``````> npm install --global --production windows-build-tools
``````
2. In a normal command-line shell (Win+R+cmd+Enter) run:

``````> npm install -g node-gyp
> npm install -g node-sass
``````

The `-g` places these packages under `%userprofile%\AppData\Roaming\npm\node_modules`. You may check that `npm\node_modules\node-sass\bin\node-sass` now exists.

3. Check if your local account (not the System) `PATH` environment variable contains:

``````%userprofile%\AppData\Roaming\npm
``````

If this path is not present, npm and node may still run, but the modules bin files will not!

Close the previous shell and reopen a new one and run either `> node-gyp` or `> node-sass`.

Note:

• The `windows-build-tools` may not be necessary (if no compiling is done? I'd like to read if someone made it without installing these tools), but it did add to the admin account the `GYP_MSVS_VERSION` environment variable with `2015` as a value.
• I am also able to run directly other modules with bin files, such as `> uglifyjs main.js main.min.js` and `> mocha`

### Can I use complex HTML with Twitter Bootstrap's Tooltip?

Just as normal, using `data-original-title`:

Html:

``````<div rel='tooltip' data-original-title='<h1>big tooltip</h1>'>Visible text</div>
``````

Javascript:

``````\$("[rel=tooltip]").tooltip({html:true});
``````

The html parameter specifies how the tooltip text should be turned into DOM elements. By default Html code is escaped in tooltips to prevent XSS attacks. Say you display a username on your site and you show a small bio in a tooltip. If the html code isn't escaped and the user can edit the bio themselves they could inject malicious code.

### Oracle "SQL Error: Missing IN or OUT parameter at index:: 1"

Based on the comments left above I ran this under sqlplus instead of SQL Developer and the UPDATE statement ran perfectly, leaving me to believe this is an issue in SQL Developer particularly as there was no ORA error number being returned. Thank you for leading me in the right direction.

### Why won't my PHP app send a 404 error?

For the record, this is the all-case handler:

``````<?php

\$_SERVER['REDIRECT_STATUS'] = 404;
?> <!-- 404 contents below this line -->
``````

### Pass Multiple Parameters to jQuery ajax call

I successfully passed multiple parameters using json

``````data: "{'RecomendeeName':'" + document.getElementById('txtSearch').value + "'," + "'tempdata':'" +"myvalue" + "'}",
``````

### How do I change the background color of a plot made with ggplot2

To avoid deprecated `opts` and `theme_rect` use:

``````myplot + theme(panel.background = element_rect(fill='green', colour='red'))
``````

To define your own custom theme, based on theme_gray but with some of your changes and a few added extras including control of gridline colour/size (more options available to play with at ggplot2.org):

``````theme_jack <- function (base_size = 12, base_family = "") {
theme_gray(base_size = base_size, base_family = base_family) %+replace%
theme(
axis.text = element_text(colour = "white"),
axis.title.x = element_text(colour = "pink", size=rel(3)),
axis.title.y = element_text(colour = "blue", angle=45),
panel.background = element_rect(fill="green"),
panel.grid.minor.y = element_line(size=3),
panel.grid.major = element_line(colour = "orange"),
plot.background = element_rect(fill="red")
)
}
``````

To make your custom theme the default when ggplot is called in future, without masking:

``````theme_set(theme_jack())
``````

If you want to change an element of the currently set theme:

``````theme_update(plot.background = element_rect(fill="pink"), axis.title.x = element_text(colour = "red"))
``````

To store the current default theme as an object:

``````theme_pink <- theme_get()
``````

Note that `theme_pink` is a list whereas `theme_jack` was a function. So to return the theme to theme_jack use `theme_set(theme_jack())` whereas to return to theme_pink use `theme_set(theme_pink)`.

You can replace `theme_gray` by `theme_bw` in the definition of `theme_jack` if you prefer. For your custom theme to resemble `theme_bw` but with all gridlines (x, y, major and minor) turned off:

``````theme_nogrid <- function (base_size = 12, base_family = "") {
theme_bw(base_size = base_size, base_family = base_family) %+replace%
theme(
panel.grid = element_blank()
)
}
``````

Finally a more radical theme useful when plotting choropleths or other maps in ggplot, based on discussion here but updated to avoid deprecation. The aim here is to remove the gray background, and any other features that might distract from the map.

``````theme_map <- function (base_size = 12, base_family = "") {
theme_gray(base_size = base_size, base_family = base_family) %+replace%
theme(
axis.line=element_blank(),
axis.text.x=element_blank(),
axis.text.y=element_blank(),
axis.ticks=element_blank(),
axis.ticks.length=unit(0.3, "lines"),
axis.ticks.margin=unit(0.5, "lines"),
axis.title.x=element_blank(),
axis.title.y=element_blank(),
legend.background=element_rect(fill="white", colour=NA),
legend.key=element_rect(colour="white"),
legend.key.size=unit(1.2, "lines"),
legend.position="right",
legend.text=element_text(size=rel(0.8)),
legend.title=element_text(size=rel(0.8), face="bold", hjust=0),
panel.background=element_blank(),
panel.border=element_blank(),
panel.grid.major=element_blank(),
panel.grid.minor=element_blank(),
panel.margin=unit(0, "lines"),
plot.background=element_blank(),
plot.margin=unit(c(1, 1, 0.5, 0.5), "lines"),
plot.title=element_text(size=rel(1.2)),
strip.background=element_rect(fill="grey90", colour="grey50"),
strip.text.x=element_text(size=rel(0.8)),
strip.text.y=element_text(size=rel(0.8), angle=-90)
)
}
``````

### Display a angular variable in my html page

In your template, you have access to all the variables that are members of the current `\$scope`. So, `tobedone` should be `\$scope.tobedone`, and then you can display it with `{{tobedone}}`, or `[[tobedone]]` in your case.

### MySQL DAYOFWEEK() - my week begins with monday

How about subtracting one and changing Sunday

``````IF(DAYOFWEEK() = 1, 7, DAYOFWEEK() - 1)
``````

Of course you would have to do this for every query.

### Float a div in top right corner without overlapping sibling header

This worked for me:

``````h1 {
display: inline;
overflow: hidden;
}
div {
position: relative;
float: right;
}
``````

It's similar to the approach of the media object, by Stubbornella.

Edit: As they comment below, you need to place the element that's going to float before the element that's going to wrap (the one in your first fiddle)

### Convert file: Uri to File in Android

For this case, especially on Android, the way going for bytes is usually faster.

With this, I solved it by setting up a class `FileHelper` which is given the responsibility to deal with reading/writing bytes from/to file through stream and a class `UriHelper` which is given the responsibility to figure out path of Uri and permission.

As far as it's knew generally, `string.getBytes((charset == null) ? DEFAULT_CHARSET:charset)` can help us to transfer string you want to bytes you need.

How to let UriHelper and FileHelper you to copy a picture noted by Uri into a file, you can run:

``````FileHelper.getInstance().copy(UriHelper.getInstance().toFile(uri_of_a_picture)
, FileHelper.getInstance().createExternalFile(null, UriHelper.getInstance().generateFileNameBasedOnTimeStamp()
+ UriHelper.getInstance().getFileName(uri_of_a_picture, context), context)
);
``````

``````public class UriHelper {
private static UriHelper INSTANCE = new UriHelper();

public static UriHelper getInstance() {
return INSTANCE;
}

@SuppressLint("SimpleDateFormat")
public String generateFileNameBasedOnTimeStamp() {
return new SimpleDateFormat("yyyyMMdd_hhmmss").format(new Date()) + ".jpeg";
}

/**
* if uri.getScheme.equals("content"), open it with a content resolver.
* if the uri.Scheme.equals("file"), open it using normal file methods.
*/
//

public File toFile(Uri uri) {
if (uri == null) return null;
Logger.d(">>> uri path:" + uri.getPath());
Logger.d(">>> uri string:" + uri.toString());
return new File(uri.getPath());
}

public DocumentFile toDocumentFile(Uri uri) {
if (uri == null) return null;
Logger.d(">>> uri path:" + uri.getPath());
Logger.d(">>> uri string:" + uri.toString());
return DocumentFile.fromFile(new File(uri.getPath()));
}

public Uri toUri(File file) {
if (file == null) return null;
Logger.d(">>> file path:" + file.getAbsolutePath());
return Uri.fromFile(file); //returns an immutable URI reference representing the file
}

public String getPath(Uri uri, Context context) {
if (uri == null) return null;
if (uri.getScheme() == null) return null;
Logger.d(">>> uri path:" + uri.getPath());
Logger.d(">>> uri string:" + uri.toString());
String path;
if (uri.getScheme().equals("content")) {
//Cursor cursor = context.getContentResolver().query(uri, new String[] {MediaStore.Images.ImageColumns.DATA}, null, null, null);
Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
if (cursor == null) {
Logger.e("!!! cursor is null");
return null;
}
if (cursor.getCount() >= 0) {
Logger.d("... the numbers of rows:" + cursor.getCount()
+ "and the numbers of columns:" + cursor.getColumnCount());
if (cursor.isBeforeFirst()) {
while (cursor.moveToNext()) {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i<cursor.getColumnCount(); i++) {
stringBuilder.append("... iterating cursor.getString(" + i +"(" + cursor.getColumnName(i) + ")):" + cursor.getString(i));
stringBuilder.append("\n");
}
Logger.d(stringBuilder.toString());
}
} else {
cursor.moveToFirst();
do {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i<cursor.getColumnCount(); i++) {
stringBuilder.append("... iterating cursor.getString(" + i +"(" + cursor.getColumnName(i) + ")):" + cursor.getString(i));
stringBuilder.append("\n");
}
Logger.d(stringBuilder.toString());
} while (cursor.moveToNext());
}
path = uri.getPath();
cursor.close();
Logger.d("... content scheme:" + uri.getScheme() + "  and return:" + path);
return path;
} else {
path = uri.getPath();
Logger.d("... content scheme:" + uri.getScheme()
+ " but the numbers of rows in the cursor is < 0:" + cursor.getCount()
+ "  and return:" + path);
return path;
}
} else {
path = uri.getPath();
Logger.d("... not content scheme:" + uri.getScheme() + "  and return:" + path);
return path;
}
}

public String getFileName(Uri uri, Context context) {
if (uri == null) return null;
if (uri.getScheme() == null) return null;
Logger.d(">>> uri path:" + uri.getPath());
Logger.d(">>> uri string:" + uri.toString());
String path;
if (uri.getScheme().equals("content")) {
//Cursor cursor = context.getContentResolver().query(uri, new String[] {MediaStore.Images.ImageColumns.DATA}, null, null, null);
Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
if (cursor == null) {
Logger.e("!!! cursor is null");
return null;
}
if (cursor.getCount() >= 0) {
Logger.d("... the numbers of rows:" + cursor.getCount()
+ "and the numbers of columns:" + cursor.getColumnCount());
if (cursor.isBeforeFirst()) {
while (cursor.moveToNext()) {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i<cursor.getColumnCount(); i++) {
stringBuilder.append("... iterating cursor.getString(" + i +"(" + cursor.getColumnName(i) + ")):" + cursor.getString(i));
stringBuilder.append("\n");
}
Logger.d(stringBuilder.toString());
}
} else {
cursor.moveToFirst();
do {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i<cursor.getColumnCount(); i++) {
stringBuilder.append("... iterating cursor.getString(" + i +"(" + cursor.getColumnName(i) + ")):" + cursor.getString(i));
stringBuilder.append("\n");
}
Logger.d(stringBuilder.toString());
} while (cursor.moveToNext());
}
cursor.moveToFirst();
path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.ImageColumns.DISPLAY_NAME));
cursor.close();
Logger.d("... content scheme:" + uri.getScheme() + "  and return:" + path);
return path;
} else {
path = uri.getLastPathSegment();
Logger.d("... content scheme:" + uri.getScheme()
+ " but the numbers of rows in the cursor is < 0:" + cursor.getCount()
+ "  and return:" + path);
return path;
}
} else {
path = uri.getLastPathSegment();
Logger.d("... not content scheme:" + uri.getScheme() + "  and return:" + path);
return path;
}
}
``````

}

``````public class FileHelper {
private static final String DEFAULT_DIR_NAME = "AmoFromTaiwan";
private static final int DEFAULT_BUFFER_SIZE = 1024;
private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
private static final int EOF = -1;
private static FileHelper INSTANCE = new FileHelper();

public static FileHelper getInstance() {
return INSTANCE;
}

private boolean isExternalStorageWritable(Context context) {
/*
String state = Environment.getExternalStorageState();
return Environment.MEDIA_MOUNTED.equals(state);
*/
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (context.checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
Logger.e("!!! checkSelfPermission() not granted");
return false;
}
} else { //permission is automatically granted on sdk<23 upon installation
return true;
}
}

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return true;
} else {
Logger.e("!!! checkSelfPermission() not granted");
return false;
}
} else { //permission is automatically granted on sdk<23 upon installation
return true;
}
}

@SuppressLint("SimpleDateFormat")
private String generateFileNameBasedOnTimeStamp() {
return new SimpleDateFormat("yyyyMMdd_hhmmss").format(new Date()) + ".jpeg";
}

public File createExternalFile(String dir_name, String file_name, Context context) {
String dir_path;
String file_path;
File dir ;
File file;
if (!isExternalStorageWritable(context)) {
Logger.e("!!! external storage not writable");
return null;
}
if (dir_name == null) {
dir_path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath() + File.separator + DEFAULT_DIR_NAME;
} else {
dir_path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath() + File.separator + dir_name;
}
Logger.d("... going to access an external dir:" + dir_path);
dir = new File(dir_path);
if (!dir.exists()) {
Logger.d("... going to mkdirs:" + dir_path);
if (!dir.mkdirs()) {
Logger.e("!!! failed to mkdirs");
return null;
}
}
if (file_name == null) {
file_path = dir_path + File.separator + generateFileNameBasedOnTimeStamp();
} else {
file_path = dir_path + File.separator + file_name;
}
Logger.d("... going to return an external dir:" + file_path);
file = new File(file_path);
if (file.exists()) {
Logger.d("... before creating to delete an external dir:" + file.getAbsolutePath());
if (!file.delete()) {
Logger.e("!!! failed to delete file");
return null;
}
}
return file;
}

public File createInternalFile(String dir_name, String file_name, Context context) {
String dir_path;
String file_path;
File dir ;
File file;
if (dir_name == null) {
dir = new ContextWrapper(context).getDir(DEFAULT_DIR_NAME, Context.MODE_PRIVATE);
} else {
dir = new ContextWrapper(context).getDir(dir_name, Context.MODE_PRIVATE);
}
dir_path = dir.getAbsolutePath();
Logger.d("... going to access an internal dir:" + dir_path);
if (!dir.exists()) {
Logger.d("... going to mkdirs:" + dir_path);
if (!dir.mkdirs()) {
Logger.e("!!! mkdirs failed");
return null;
}
}
if (file_name == null) {
file = new File(dir, generateFileNameBasedOnTimeStamp());
} else {
file = new File(dir, file_name);
}
file_path = file.getAbsolutePath();
Logger.d("... going to return an internal dir:" + file_path);
if (file.exists()) {
Logger.d("... before creating to delete an external dir:" + file.getAbsolutePath());
if (!file.delete()) {
Logger.e("!!! failed to delete file");
return null;
}
}
return file;
}

public File getExternalFile(String dir_name, String file_name, Context context) {
String dir_path;
String file_path;
File file;
if (!isExternalStorageWritable(context)) {
Logger.e("!!! external storage not writable");
return null;
}
if (dir_name == null) {
dir_path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath() + File.separator + DEFAULT_DIR_NAME;
} else {
dir_path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath() + File.separator + dir_name;
}
if (file_name == null) {
file_path = dir_path;
} else {
file_path = dir_path + File.separator + file_name;
}
Logger.d("... going to return an external file:" + file_path);
file = new File(file_path);
if (file.exists()) {
Logger.d("... file exists:" + file.getAbsolutePath());
} else {
Logger.e("!!! file does't exist:" + file.getAbsolutePath());
}
return file;
}

public File getInternalFile(String dir_name, String file_name, Context context) {
String file_path;
File dir ;
File file;
if (dir_name == null) {
dir = new ContextWrapper(context).getDir(DEFAULT_DIR_NAME, Context.MODE_PRIVATE);
} else {
dir = new ContextWrapper(context).getDir(dir_name, Context.MODE_PRIVATE);
}
if (file_name == null) {
file = new File(dir.getAbsolutePath());
} else {
file = new File(dir, file_name);
}
file_path = file.getAbsolutePath();
Logger.d("... going to return an internal dir:" + file_path);
if (file.exists()) {
Logger.d("... file exists:" + file.getAbsolutePath());
} else {
Logger.e("!!! file does't exist:" + file.getAbsolutePath());
}
return file;
}

Logger.d(">>> path:" + file.getAbsolutePath());
FileInputStream fis;
long file_length;
byte[] buffer;
int offset = 0;
int next = 0;
if (!file.exists()) {
Logger.e("!!! file doesn't exists");
return null;
}
if (file.length() > Integer.MAX_VALUE) {
Logger.e("!!! file length is out of max of int");
return null;
} else {
file_length = file.length();
}
try {
fis = new FileInputStream(file);
//buffer = new byte[(int) file_length];
buffer = new byte[(int) file.length()];
long time_start = System.currentTimeMillis();
while (true) {
Logger.d("... now next:" + next + " and offset:" + offset);
if (System.currentTimeMillis() - time_start > 1000) {
Logger.e("!!! left due to time out");
break;
}
if (next < 0 || offset >= buffer.length) {
break;
}
offset += next;
}
//if (offset < buffer.length) {
if (offset < (int) file_length) {
return null;
}
fis.close();
return buffer;
} catch (IOException e) {
e.printStackTrace();
Logger.e("!!! IOException");
return null;
}
}

public byte[] readBytesFromFile(File file, boolean is_fis_fos_only) {
if (file == null) return null;
if (is_fis_fos_only) {
}
Logger.d(">>> path:" + file.getAbsolutePath());
FileInputStream fis;
BufferedInputStream bis;
ByteArrayOutputStream bos;
byte[] buf = new byte[(int) file.length()];
if (!file.exists()) {
Logger.e("!!! file doesn't exists");
return null;
}
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
bos = new ByteArrayOutputStream();
long time_start = System.currentTimeMillis();
while (true) {
if (System.currentTimeMillis() - time_start > 1000) {
Logger.e("!!! left due to time out");
break;
}
}
buf = bos.toByteArray();
fis.close();
bis.close();
bos.close();
return buf;
} catch (FileNotFoundException e) {
e.printStackTrace();
Logger.e("!!! FileNotFoundException");
return null;
} catch (IOException e) {
e.printStackTrace();
Logger.e("!!! IOException");
return null;
}
}

/**
* streams (InputStream and OutputStream) transfer binary data
* if to write a string to a stream, must first convert it to bytes, or in other words encode it
*/
public boolean writeStringToFile(File file, String string, Charset charset) {
if (file == null) return false;
if (string == null) return false;
return writeBytesToFile(file, string.getBytes((charset == null) ? DEFAULT_CHARSET:charset));
}

public boolean writeBytesToFile(File file, byte[] data) {
if (file == null) return false;
if (data == null) return false;
FileOutputStream fos;
BufferedOutputStream bos;
try {
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(data, 0, data.length);
bos.flush();
bos.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
Logger.e("!!! IOException");
return false;
}
return true;
}

/**
* io blocks until some input/output is available.
*/
public boolean copy(File source, File destination) {
if (source == null || destination == null) return false;
Logger.d(">>> source:" + source.getAbsolutePath() + ", destination:" + destination.getAbsolutePath());
try {
FileInputStream fis = new FileInputStream(source);
FileOutputStream fos = new FileOutputStream(destination);
byte[] buffer = new byte[(int) source.length()];
int len;
while (EOF != (len = fis.read(buffer))) {
fos.write(buffer, 0, len);
}
if (true) { //debug
if (copies != null) {
int copy_len = copies.length;
Logger.d("... stream read and write done for " + copy_len + " bytes");
}
}
return destination.length() != 0;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}

public void list(final String path, final String end, final List<File> files) {
Logger.d(">>> path:" + path + ", end:" + end);
File file = new File(path);
if (file.isDirectory()) {
for (File child : file.listFiles()){
list(child.getAbsolutePath(), end, files);
}
} else if (file.isFile()) {
if (end.equals("")) {
} else {
}
}
}

public String[] splitFileName(File file, String split) {
String path;
String ext;
int lastIndexOfSplit = file.getAbsolutePath().lastIndexOf(split);
if (lastIndexOfSplit < 0) {
path = file.getAbsolutePath();
ext = "";
} else {
path = file.getAbsolutePath().substring(0, lastIndexOfSplit);
ext = file.getAbsolutePath().substring(lastIndexOfSplit);
}
return new String[] {path, ext};
}

public File rename(File old_file, String new_name) {
if (old_file == null || new_name == null) return null;
Logger.d(">>> old file path:" + old_file.getAbsolutePath() + ", new file name:" + new_name);
File new_file = new File(old_file, new_name);
if (!old_file.equals(new_file)) {
if (new_file.exists()) { //if find out previous file/dir at new path name exists
if (new_file.delete()) {
Logger.d("... succeeded to delete previous file at new abstract path name:" + new_file.getAbsolutePath());
} else {
Logger.e("!!! failed to delete previous file at new abstract path name");
return null;
}
}
if (old_file.renameTo(new_file)) {
Logger.d("... succeeded to rename old file to new abstract path name:" + new_file.getAbsolutePath());
} else {
Logger.e("!!! failed to rename old file to new abstract path name");
}
} else {
Logger.d("... new and old file have the equal abstract path name:" + new_file.getAbsolutePath());
}
return new_file;
}

public boolean remove(final String path, final String end) {
Logger.d(">>> path:" + path + ", end:" + end);
File file = new File(path);
boolean result = false;
if (file.isDirectory()) {
for (File child : file.listFiles()){
result = remove(child.getAbsolutePath(), end);
}
} else if (file.isFile()) {
if (end.equals("")) {
result = file.delete();
} else {
if (file.getName().endsWith(end)) result = file.delete();
}
} else {
Logger.e("!!! child is not file or directory");
}
return result;
}

@TargetApi(Build.VERSION_CODES.O)
public byte[] readNIOBytesFromFile(String path) throws IOException {
Logger.d(">>> path:" + path);
Logger.e("!!! file doesn't exists");
return null;
} else {
}
}

@TargetApi(Build.VERSION_CODES.O)
public File writeNIOBytesToFile(String dir, String name, byte[] data) {
Logger.d(">>> dir:" + dir + ", name:" + name);
Path path_dir;
Path path_file;
try {
Logger.d("... make a dir");
path_dir = Files.createDirectories(Paths.get(dir));
if (path_dir == null) {
Logger.e("!!! failed to make a dir");
return null;
}
}
path_file = Files.write(Paths.get(name), data);
return path_file.toFile();
} catch (IOException e) {
e.printStackTrace();
Logger.e("!!! IOException");
return null;
}
}

@TargetApi(Build.VERSION_CODES.O)
public void listNIO(final String dir, final String end, final List<File> files) throws IOException {
Logger.d(">>> dir:" + dir + ", end:" + end);
Files.walkFileTree(Paths.get(dir), new FileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
Logger.d("... file:" + dir.getFileName());
return FileVisitResult.CONTINUE;
}

@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
Logger.d("... file:" + file.getFileName());
if (end.equals("")) {
} else {
}
return FileVisitResult.CONTINUE;
}

@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) {
Logger.d("... file:" + file.getFileName());
if (end.equals("")) {
} else {
}
return FileVisitResult.CONTINUE;
}

@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
Logger.d("... file:" + dir.getFileName());
return FileVisitResult.CONTINUE;
}
});
}

/**
* recursion
*/
private int factorial (int x) {
if (x > 1) return (x*(factorial(x-1)));
else if (x == 1) return x;
else return 0;
}
``````

}

### Tesseract OCR simple example

In my case I had all these worked except for the correct character recognition.

But you need to consider these few things:

• Use correct tessnet2 library
• use correct tessdata language version
• tessdata should be somewhere out of your application folder where you can put in full path in the init parameter. use `ocr.Init(@"c:\tessdata", "eng", true);`
• Debugging will cause you headache. Then you need to update your app.config use this. (I can't put the xml code here. give me your email i will email it to you)

hope that this helps

### Why does javascript replace only first instance when using replace?

You need to set the g flag to replace globally:

``````date.replace(new RegExp("/", "g"), '')
// or
date.replace(/\//g, '')
``````

Otherwise only the first occurrence will be replaced.

### How to open generated pdf using jspdf in new window

this code will help you to open generated pdf in new tab with required title

`````` let pdf = new jsPDF();
pdf.setProperties({
title: "Report"
});
pdf.output('dataurlnewwindow');
``````

### Assigning default value while creating migration file

Default migration generator does not handle default values (column modifiers are supported but do not include `default` or `null`), but you could create your own generator.

You can also manually update the migration file prior to running `rake db:migrate` by adding the options to `add_column`:

`add_column :tweet, :retweets_count, :integer, :null => false, :default => 0`

### How store a range from excel into a Range variable?

When you use a `Range` object, you cannot simply use the following syntax:

``````Dim myRange as Range
myRange = Range("A1")
``````

You must use the `set` keyword to assign Range objects:

``````Function getData(currentWorksheet As Worksheet, dataStartRow As Integer, dataEndRow As Integer, DataStartCol As Integer, dataEndCol As Integer)

Dim dataTable As Range
Set dataTable = currentWorksheet.Range(currentWorksheet.Cells(dataStartRow, DataStartCol), currentWorksheet.Cells(dataEndRow, dataEndCol))

Set getData = dataTable

End Function

Sub main()
Dim test As Range

Set test = getData(ActiveSheet, 1, 3, 2, 5)
test.select

End Sub
``````

Note that every time a range is declared I use the `Set` keyword.

You can also allow your `getData` function to return a `Range` object instead of a `Variant` although this is unrelated to the problem you are having.

### How to check if a string starts with "_" in PHP?

``````function starts_with(\$s, \$prefix){
// returns a bool
return strpos(\$s, \$prefix) === 0;
}

starts_with(\$variable, "_");
``````

### Pretty print in MongoDB shell as default

Got to the question but could not figure out how to print it from externally-loaded mongo. So:

This works is for console: and is prefered in console, but does not work in external mongo-loaded javascript:

``````db.quizes.find().pretty()
``````

This works in external mongo-loaded javscript:

``````db.quizes.find().forEach(printjson)
``````

### Is there a way to run Python on Android?

This one embed directly the Python interpretter in your app apk.

### How to fire an event on class change using jQuery?

Use `trigger` to fire your own event. When ever you change class add trigger with name

JS Fiddle DEMO

``````\$("#main").on('click', function () {
});

\$('#chld').on('cssFontSet', function () {

});
``````

Learn jQuery: Simple and easy jQuery tutorials blog

### Better/Faster to Loop through set or list?

For simplicity's sake: `newList = list(set(oldList))`

But there are better options out there if you'd like to get speed/ordering/optimization instead: http://www.peterbe.com/plog/uniqifiers-benchmark

### How to retrieve the hash for the current commit in Git?

I needed something a little more different: display the full sha1 of the commit, but append an asterisk to the end if the working directory is not clean. Unless I wanted to use multiple commands, none of the options in the previous answers work.

Here is the one liner that does:
`git describe --always --abbrev=0 --match "NOT A TAG" --dirty="*"`
Result: `f5366ccb21588c0d7a5f7d9fa1d3f85e9f9d1ffe*`

Explanation: describes (using annotated tags) the current commit, but only with tags containing "NOT A TAG". Since tags cannot have spaces, this never matches a tag and since we want to show a result `--always`, the command falls back displaying the full (`--abbrev=0`) sha1 of the commit and it appends an asterisk if the working directory is `--dirty`.

If you don't want to append the asterisk, this works like all the other commands in the previous answers:
`git describe --always --abbrev=0 --match "NOT A TAG"`
Result: `f5366ccb21588c0d7a5f7d9fa1d3f85e9f9d1ffe`

### Visual Studio 2015 is very slow

I also had this issue with Visual Studio 2015, tried everything I could read about but in the end all that was left was a clean install. I used Microsofts tool `VisualStudioUninstaller` to get rid of every component.

https://github.com/Microsoft/VisualStudioUninstaller

Usage:

1. Extract TotalUninstaller.zip
2. Open an administrator command prompt.
3. Execute Setup.ForcedUninstall.exe
4. Type 'Y' to uninstall.

After reinstall everything worked normally again. I did not experience lag in every project but one was causing enough pain so I really had no choice.

Read about another command that you can also try but I know `VisualStudioUninstaller` works, at least it did for me.

``````D:\vs_ultimate.exe /uninstall /force
``````

Where D: is the location of your installation media (mounted iso, etc).

### How to get rid of underline for Link component of React Router?

I see you're using inline styles. `textDecoration: 'none'` is used in child, where in fact it should be used inside `<Link>` as such:

``````<Link to="first" style={{ textDecoration: 'none' }}>
``````

`<Link>` will essentially return a standard `<a>` tag, which is why we apply `textDecoration` rule there.

I hope that helps

### Find Nth occurrence of a character in a string

There is a minor bug in previous solution.

Here is some updated code:

``````s.TakeWhile(c => (n -= (c == t ? 1 : 0)) > 0).Count();
``````

If you look at Twitter's own container-app.html demo on GitHub, you'll get some ideas on using borders with their grid.

For example, here's the extracted part of the building blocks to their 940-pixel wide 16-column grid system:

``````.row {
zoom: 1;
margin-left: -20px;
}

.row > [class*="span"] {
display: inline;
float: left;
margin-left: 20px;
}

.span4 {
width: 220px;
}
``````

To allow for borders on specific elements, they added embedded CSS to the page that reduces matching classes by enough amount to account for the border(s).

For example, to allow for the left border on the sidebar, they added this CSS in the `<head>` after the the main `<link href="../bootstrap.css" rel="stylesheet">`.

``````.content .span4 {
margin-left: 0;
border-left: 1px solid #eee;
}
``````

You'll see they've reduced `padding-left` by `1px` to allow for the addition of the new left border. Since this rule appears later in the source order, it overrides any previous or external declarations.

I'd argue this isn't exactly the most robust or elegant approach, but it illustrates the most basic example.

### How to parse data in JSON format?

``````json_string = """
{
"pk": 1,
"fa": "cc.ee",
"fb": {
"fc": "",
"fd_id": "12345"
}
}"""

import json
if data["fa"] == "cc.ee":
data["fb"]["new_key"] = "cc.ee was present!"

print json.dumps(data)
``````

The output for the above code will be:

``````{"pk": 1, "fb": {"new_key": "cc.ee was present!", "fd_id": "12345",
"fc": ""}, "fa": "cc.ee"}
``````

Note that you can set the ident argument of dump to print it like so (for example,when using print json.dumps(data , indent=4)):

``````{
"pk": 1,
"fb": {
"new_key": "cc.ee was present!",
"fd_id": "12345",
"fc": ""
},
"fa": "cc.ee"
}
``````

### How to disable SSL certificate checking with Spring RestTemplate?

For the sake of other developers who finds this question and need another solution that fits not only for unit-tests:

I've found this on a blog (not my solution! Credit to the blog's owner).

``````TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;

SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
.build();

SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);

CloseableHttpClient httpClient = HttpClients.custom()
.setSSLSocketFactory(csf)
.build();

HttpComponentsClientHttpRequestFactory requestFactory =
new HttpComponentsClientHttpRequestFactory();

requestFactory.setHttpClient(httpClient);

RestTemplate restTemplate = new RestTemplate(requestFactory);
``````

### MySql server startup error 'The server quit without updating PID file '

This error can occur when trying to start msql after it was improperly shutdown.

1. Take a look at the mysql error log file. If it mentions something like "Check that you do not already have another mysqld process using the same data or log files.", then you need to properly shutdown that process.

2. See what process mysql is running on, use this command: `lsof -i:3306`

Your output should look like this:

``````COMMAND  PID    USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME
mysqld  4249 username   17u  IPv4 0x7843d9d130469c0b      0t0  TCP localhost:mysql (LISTEN)
``````
1. Terminate the process running mysql: `kill -15 4249`

Kill -15 sends a siganl to the process to free up any resources it is locking and terminate the process after.

1. Now mysql should startup with no problems: `mysql.server start`

### install cx_oracle for python

This just worked for me on Ubuntu 16:

Download ('instantclient-basic-linux.x64-12.2.0.1.0.zip' and 'instantclient-sdk-linux.x64-12.2.0.1.0.zip') from Oracle web site and then do following script (you can do piece by piece and I did as a ROOT):

``````apt-get install -y python-dev build-essential libaio1
mkdir -p /opt/ora/
cd /opt/ora/

## Now put 2 ZIP files:
# ('instantclient-basic-linux.x64-12.2.0.1.0.zip' and 'instantclient-sdk-linux.x64-12.2.0.1.0.zip')
# into /opt/ora/ and unzip them -> both will be unzipped into 1 directory: /opt/ora/instantclient_12_2

rm -rf /etc/profile.d/oracle.sh
echo "export ORACLE_HOME=/opt/ora/instantclient_12_2"  >> /etc/profile.d/oracle.sh
echo "export LD_LIBRARY_PATH=\$LD_LIBRARY_PATH:\$ORACLE_HOME"  >> /etc/profile.d/oracle.sh
chmod 777 /etc/profile.d/oracle.sh
source /etc/profile.d/oracle.sh
env | grep -i ora  # This will check current ENVIRONMENT settings for Oracle

rm -rf /etc/ld.so.conf.d/oracle.conf
echo "/opt/ora/instantclient_12_2" >> /etc/ld.so.conf.d/oracle.conf
ldconfig
cd \$ORACLE_HOME
ls -lrth libclntsh*   # This will show which version of 'libclntsh' you have... --> needed for following line:

ln -s libclntsh.so.12.1 libclntsh.so

pip install cx_Oracle   # Maybe not needed but I did it anyway (only pip install cx_Oracle without above steps did not work for me...)
``````

### How to export data from Excel spreadsheet to Sql Server 2008 table

In SQL Server 2016 the wizard is a separate app. (Important: Excel wizard is only available in the 32-bit version of the wizard!). Use the MSDN page for instructions:

``````On the Start menu, point to All Programs, point toMicrosoft SQL Server , and then click Import and Export Data.
â€”orâ€”
In SQL Server Data Tools (SSDT), right-click the SSIS Packages folder, and then click SSIS Import and Export Wizard.
â€”orâ€”
In SQL Server Data Tools (SSDT), on the Project menu, click SSIS Import and Export Wizard.
â€”orâ€”
In SQL Server Management Studio, connect to the Database Engine server type, expand Databases, right-click a database, point to Tasks, and then click Import Data or Export data.
â€”orâ€”
In a command prompt window, run DTSWizard.exe, located in C:\Program Files\Microsoft SQL Server\100\DTS\Binn.
``````

After that it should be pretty much the same (possibly with minor variations in the UI) as in @marc_s's answer.

### Return content with IHttpActionResult for non-OK response

I had the same problem. I want to create custom result for my api controllers, to call them like `return Ok("some text");`

Then i did this: 1) Create custom result type with singletone

``````public sealed class EmptyResult : IHttpActionResult
{
{
return Task.FromResult(new HttpResponseMessage(System.Net.HttpStatusCode.NoContent) { Content = new StringContent("Empty result") });
}
}
``````

2) Create custom controller with new method:

``````public class CustomApiController : ApiController
{
public IHttpActionResult EmptyResult()
{
return new EmptyResult();
}
}
``````

And then i can call them in my controllers, like this:

``````public IHttpActionResult SomeMethod()
{
return EmptyResult();
}
``````

### How to catch a specific SqlException error?

If you want list of error messages met in Sql server, you can see with

``````SELECT *
FROM master.dbo.sysmessages
``````

### Bootstrap modal in React.js

The quickest fix would be to explicitly use the jQuery \$ from the global context (which has been extended with your \$.modal() because you referenced that in your script tag when you did ):

``````  window.\$('#scheduleentry-modal').modal('show') // to show
window.\$('#scheduleentry-modal').modal('hide') // to hide
``````

so this is how you can about it on react

``````import React, { Component } from 'react';

export default Modal extends Component {
componentDidMount() {
window.\$('#Modal').modal('show');
}

handleClose() {
window.\$('#Modal').modal('hide');
}

render() {
<
id = 'ModalCenter'
tabIndex = '-1'
role = 'dialog'
aria - labelledby = 'ModalCenterTitle'
data - backdrop = 'static'
aria - hidden = 'true' >
<
div className = 'modal-dialog modal-dialog-centered'
role = 'document' >
<
div className = 'modal-content' >
<
button
type = 'button'
className = 'btn btn-secondary'
onClick = {
this.handleClose
} >
Close <
/button> < /
div > <
/div> < /
div >
}
}

``````

### CSS - How to Style a Selected Radio Buttons Label?

If you really want to put the checkboxes inside the label, try adding an extra span tag, eg.

HTML

``````<div class="radio-toolbar">
</div>
``````

CSS

``````.radio-toolbar input[type="radio"]:checked ~ * {
background:pink !important;
}
``````

That will set the backgrounds for all siblings of the selected radio button.

### How to select clear table contents without destroying the table?

I reworked Doug Glancy's solution to avoid rows deletion, which can lead to #Ref issue in formulae.

``````Sub ListReset(lst As ListObject)
'clears a listObject while leaving row 1 empty, with formulae
With lst
If .ShowAutoFilter Then .AutoFilter.ShowAllData
On Error Resume Next
With .DataBodyRange
.Offset(1).Rows.Clear
.Rows(1).SpecialCells(xlCellTypeConstants).ClearContents
End With
On Error GoTo 0
.Resize .Range.Rows("1:2")
End With
End Sub
``````

### How to write a confusion matrix in Python?

In a general sense, you're going to need to change your probability array. Instead of having one number for each instance and classifying based on whether or not it is greater than 0.5, you're going to need a list of scores (one for each class), then take the largest of the scores as the class that was chosen (a.k.a. argmax).

You could use a dictionary to hold the probabilities for each classification:

``````prob_arr = [{classification_id: probability}, ...]
``````

Choosing a classification would be something like:

``````for instance_scores in prob_arr :
predicted_classes = [cls for (cls, score) in instance_scores.iteritems() if score = max(instance_scores.values())]
``````

This handles the case where two classes have the same scores. You can get one score, by choosing the first one in that list, but how you handle that depends on what you're classifying.

Once you have your list of predicted classes and a list of expected classes you can use code like Torsten Marek's to create the confusion array and calculate the accuracy.

### compression and decompression of string data in java

If you ever need to transfer the zipped content via network or store it as text, you have to use Base64 encoder(such as apache commons codec Base64) to convert the byte array to a Base64 String, and decode the string back to byte array at remote client. Found an example at Use Zip Stream and Base64 Encoder to Compress Large String Data!

### Adding value labels on a matplotlib bar chart

Building off the above (great!) answer, we can also make a horizontal bar plot with just a few adjustments:

``````# Bring some raw data.
frequencies = [6, -16, 75, 160, 244, 260, 145, 73, 16, 4, 1]

freq_series = pd.Series(frequencies)

y_labels = [108300.0, 110540.0, 112780.0, 115020.0, 117260.0, 119500.0,
121740.0, 123980.0, 126220.0, 128460.0, 130700.0]

# Plot the figure.
plt.figure(figsize=(12, 8))
ax = freq_series.plot(kind='barh')
ax.set_title('Amount Frequency')
ax.set_xlabel('Frequency')
ax.set_ylabel('Amount (\$)')
ax.set_yticklabels(y_labels)
ax.set_xlim(-40, 300) # expand xlim to make labels easier to read

rects = ax.patches

# For each bar: Place a label
for rect in rects:
# Get X and Y placement of label from rect.
x_value = rect.get_width()
y_value = rect.get_y() + rect.get_height() / 2

# Number of points between bar and label. Change to your liking.
space = 5
# Vertical alignment for positive values
ha = 'left'

# If value of bar is negative: Place label left of bar
if x_value < 0:
# Invert space to place label to the left
space *= -1
# Horizontally align label at right
ha = 'right'

# Use X value as label and format number with one decimal place
label = "{:.1f}".format(x_value)

# Create annotation
plt.annotate(
label,                      # Use `label` as label
(x_value, y_value),         # Place label at end of the bar
xytext=(space, 0),          # Horizontally shift label by `space`
textcoords="offset points", # Interpret `xytext` as offset in points
va='center',                # Vertically center label
ha=ha)                      # Horizontally align label differently for
# positive and negative values.

plt.savefig("image.png")
``````

### How to amend older Git commit?

I prepared my commit that I wanted to amend with an older one and was surprised to see that rebase -i complained that I have uncommitted changes. But I didn't want to make my changes again specifying edit option of the older commit. So the solution was pretty easy and straightforward:

2. `git rebase -i <commit you want to amend>^` - notice the `^` so you see the said commit in the text editor
3. you will get sometihng like this:

``````pick 8c83e24 use substitution instead of separate subsystems file to avoid jgroups.xml and jgroups-e2.xml going out of sync
pick 799ce28 generate ec2 configuration out of subsystems-ha.xml and subsystems-full-ha.xml to avoid discrepancies
pick e23d23a fix indentation of jgroups.xml
``````
4. now to combine e23d23a with 8c83e24 you can change line order and use squash like this:

``````pick 8c83e24 use substitution instead of separate subsystems file to avoid jgroups.xml and jgroups-e2.xml going out of sync
squash e23d23a fix indentation of jgroups.xml
pick 799ce28 generate ec2 configuration out of subsystems-ha.xml and subsystems-full-ha.xml to avoid discrepancies
``````
5. write and exit the file, you will be present with an editor to merge the commit messages. Do so and save/exit the text document

6. You are done, your commits are amended

credit goes to: http://git-scm.com/book/en/Git-Tools-Rewriting-History There's also other useful demonstrated git magic.

### How to get input text value from inside td

``````var values = {};
\$('td input').each(function(){
values[\$(this).attr('name')] = \$(this).val();
}
``````

Haven't tested, but that should do it...

### Android Preventing Double Click On A Button

Only 2 step , and you can use it everywhere in your application.

Step1. create a singleton to manager [avoiding multiple click]

``````package com.im.av.mediator;

import android.os.SystemClock;

import java.util.HashMap;

/**
* Created by ShuHeng on 16/6/1.
*/
public class ClickManager {

public volatile static ClickManager mInstance =null;

public static ClickManager getInstance(){
if (mInstance == null) {
synchronized(ClickManager.class) {
if (mInstance == null) {
mInstance = new ClickManager();
}
}
}
return mInstance;
}
public boolean isClickable1s(Integer key){
if(keyLong==null){
return true;
}else{
if (SystemClock.elapsedRealtime() - keyLong.longValue() < 1000){
return false;
}else{
return true;
}
}
}
}
``````

Step2. add one line to avoid multiple click.

``````@Override
public void onClick(View v) {
// TODO Auto-generated method stub
int id = v.getId();
if (id == R.id.iv_back) {
if(!ClickManager.getInstance().isClickable1s(R.id.iv_back))return;
//do something
} else if (id == R.id.iv_light) {
if(!ClickManager.getInstance().isClickable1s(R.id.iv_light))return;
//do something
} else if (id == R.id.iv_camerarotate) {
if(!ClickManager.getInstance().isClickable1s(R.id.iv_camerarotate))return;
//do something
} else if (id == R.id.btn_delete_last_clip) {
if(!ClickManager.getInstance().isClickable1s(R.id.btn_delete_last_clip))return;
//do something

} else if (id == R.id.iv_ok) {
if(!ClickManager.getInstance().isClickable1s(R.id.iv_ok))return;
//do something
}
}
``````

### I just discovered why all ASP.Net websites are slow, and I am trying to work out what to do about it

Marking a controller's session state as readonly or disabled will solve the problem.

You can decorate a controller with the following attribute to mark it read-only:

``````[SessionState(System.Web.SessionState.SessionStateBehavior.ReadOnly)]
``````

the System.Web.SessionState.SessionStateBehavior enum has the following values:

• Default
• Disabled
• Required

### docker error: /var/run/docker.sock: no such file or directory

The first /var/run/docker.sock refers to the same path in your boot2docker virtual machine. Correcly write for windows /var/run/docker.sock

### How to check command line parameter in ".bat" file?

Actually, all the other answers have flaws. The most reliable way is:

``````IF "%~1"=="-b" (GOTO SPECIFIC) ELSE (GOTO UNKNOWN)
``````

Detailed Explanation:

Using `"%1"=="-b"` will flat out crash if passing argument with spaces and quotes. This is the least reliable method.

``````IF "%1"=="-b" (GOTO SPECIFIC) ELSE (GOTO UNKNOWN)

C:\> run.bat "a b"

b""=="-b" was unexpected at this time.
``````

Using `[%1]==[-b]` is better because it will not crash with spaces and quotes, but it will not match if the argument is surrounded by quotes.

``````IF [%1]==[-b] (GOTO SPECIFIC) ELSE (GOTO UNKNOWN)

C:\> run.bat "-b"

(does not match, and jumps to UNKNOWN instead of SPECIFIC)
``````

Using `"%~1"=="-b"` is the most reliable. `%~1` will strip off surrounding quotes if they exist. So it works with and without quotes, and also with no args.

``````IF "%~1"=="-b" (GOTO SPECIFIC) ELSE (GOTO UNKNOWN)

C:\> run.bat
C:\> run.bat -b
C:\> run.bat "-b"
C:\> run.bat "a b"

(all of the above tests work correctly)
``````

### Calculate the number of business days between two dates?

Here is an helper function I wrote for that task.
it also returns the count of weekends via the `out` parameter.
if you wish you can customize the "weekend" days in run time for countries that use different weekend days or to include holidays trough the `weekendDays[]` optional parameter :

``````public static int GetNetworkDays(DateTime startDate, DateTime endDate,out int totalWeekenDays, DayOfWeek[] weekendDays = null)
{
if (startDate >= endDate)
{
throw new Exception("start date can not be greater then or equel to end date");
}

DayOfWeek[] weekends = new DayOfWeek[] { DayOfWeek.Sunday, DayOfWeek.Saturday };
if (weekendDays != null)
{
weekends = weekendDays;
}

var totaldays = (endDate - startDate).TotalDays + 1; // add one to include the first day to
var counter = 0;
var workdaysCounter = 0;
var weekendsCounter = 0;

for (int i = 0; i < totaldays; i++)
{

{
weekendsCounter++;
}
else
{
workdaysCounter++;
}

counter++;
}

totalWeekenDays = weekendsCounter;
return workdaysCounter;
}
``````

### How can I reorder a list?

You can do it like this

``````mylist = ['a', 'b', 'c', 'd', 'e']
myorder = [3, 2, 0, 1, 4]
mylist = [mylist[i] for i in myorder]
print(mylist)         # prints: ['d', 'c', 'a', 'b', 'e']
``````

### CFLAGS vs CPPFLAGS

The implicit make rule for compiling a C program is

``````%.o:%.c
\$(CC) \$(CPPFLAGS) \$(CFLAGS) -c -o \$@ \$<
``````

where the `\$()` syntax expands the variables. As both `CPPFLAGS` and `CFLAGS` are used in the compiler call, which you use to define include paths is a matter of personal taste. For instance if `foo.c` is a file in the current directory

``````make foo.o CPPFLAGS="-I/usr/include"
make foo.o CFLAGS="-I/usr/include"
``````

will both call your compiler in exactly the same way, namely

``````gcc -I/usr/include -c -o foo.o foo.c
``````

The difference between the two comes into play when you have multiple languages which need the same include path, for instance if you have `bar.cpp` then try

``````make bar.o CPPFLAGS="-I/usr/include"
make bar.o CFLAGS="-I/usr/include"
``````

then the compilations will be

``````g++ -I/usr/include -c -o bar.o bar.cpp
g++ -c -o bar.o bar.cpp
``````

as the C++ implicit rule also uses the `CPPFLAGS` variable.

This difference gives you a good guide for which to use - if you want the flag to be used for all languages put it in `CPPFLAGS`, if it's for a specific language put it in `CFLAGS`, `CXXFLAGS` etc. Examples of the latter type include standard compliance or warning flags - you wouldn't want to pass `-std=c99` to your C++ compiler!

You might then end up with something like this in your makefile

``````CPPFLAGS=-I/usr/include
CFLAGS=-std=c99
CXXFLAGS=-Weffc++
``````

### how to draw directed graphs using networkx in python?

You need to use a directed graph instead of a graph, i.e.

``````G = nx.DiGraph()
``````

Then, create a list of the edge colors you want to use and pass those to `nx.draw` (as shown by @Marius).

Putting this all together, I get the image below. Still not quite the other picture you show (I don't know where your edge weights are coming from), but much closer! If you want more control of how your output graph looks (e.g. get arrowheads that look like arrows), I'd check out NetworkX with Graphviz.

### Changing the selected option of an HTML Select element

#### Vanilla JavaScript

Using plain old JavaScript:

_x000D_
_x000D_
``````var val = "Fish";_x000D_
var sel = document.getElementById('sel');_x000D_
document.getElementById('btn').onclick = function() {_x000D_
var opts = sel.options;_x000D_
for (var opt, j = 0; opt = opts[j]; j++) {_x000D_
if (opt.value == val) {_x000D_
sel.selectedIndex = j;_x000D_
break;_x000D_
}_x000D_
}_x000D_
}``````
_x000D_
``````<select id="sel">_x000D_
<option>Cat</option>_x000D_
<option>Dog</option>_x000D_
<option>Fish</option>_x000D_
</select>_x000D_
<button id="btn">Select Fish</button>``````
_x000D_
_x000D_
_x000D_

#### jQuery

But if you really want to use jQuery:

``````var val = 'Fish';
\$('#btn').on('click', function() {
\$('#sel').val(val);
});
``````

_x000D_
_x000D_
``````var val = 'Fish';_x000D_
\$('#btn').on('click', function() {_x000D_
\$('#sel').val(val);_x000D_
});``````
_x000D_
``````<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<select id="sel">_x000D_
<option>Cat</option>_x000D_
<option>Dog</option>_x000D_
<option>Fish</option>_x000D_
</select>_x000D_
<button id="btn">Select Fish</button>``````
_x000D_
_x000D_
_x000D_

#### jQuery - Using Value Attributes

In case your options have value attributes which differ from their text content and you want to select via text content:

``````<select id="sel">
<option value="1">Cat</option>
<option value="2">Dog</option>
<option value="3">Fish</option>
</select>
<script>
var val = 'Fish';
\$('#sel option:contains(' + val + ')').prop({selected: true});
</script>
``````

#### Demo

But if you do have the above set up and want to select by value using jQuery, you can do as before:

``````var val = 3;
\$('#sel').val(val);
``````

#### Modern DOM

For the browsers that support `document.querySelector` and the `HTMLOptionElement::selected` property, this is a more succinct way of accomplishing this task:

``````var val = 3;
document.querySelector('#sel [value="' + val + '"]').selected = true;
``````

#### Knockout.js

``````<select data-bind="value: val">
<option value="1">Cat</option>
<option value="2">Dog</option>
<option value="3">Fish</option>
</select>
<script>
var viewModel = {
val: ko.observable()
};
ko.applyBindings(viewModel);
viewModel.val(3);
</script>
``````

#### Polymer

``````<template id="template" is="dom-bind">
<select value="{{ val }}">
<option value="1">Cat</option>
<option value="2">Dog</option>
<option value="3">Fish</option>
</select>
</template>
<script>
template.val = 3;
</script>
``````

#### Angular 2

Note: this has not been updated for the final stable release.

``````<app id="app">
<select [value]="val">
<option value="1">Cat</option>
<option value="2">Dog</option>
<option value="3">Fish</option>
</select>
</app>
<script>
var App = ng.Component({selector: 'app'})
.View({template: app.innerHTML})
.Class({constructor:  function() {}});

ng.bootstrap(App).then(function(app) {
app._hostComponent.instance.val = 3;
});
</script>
``````

#### Vue 2

``````<div id="app">
<select v-model="val">
<option value="1">Cat</option>
<option value="2">Dog</option>
<option value="3">Fish</option>
</select>
</div>
<script>
var app = new Vue({
el: '#app',
data: {
val: null,
},
mounted: function() {
this.val = 3;
}
});
</script>
``````

### HTML SELECT - Change selected option by VALUE using JavaScript

If you are using jQuery:

``````\$('#sel').val('bike');
``````

### illegal use of break statement; javascript

I have a function `next()` which will maybe inspire you.

``````function queue(target) {
var array = Array.prototype;

var queueing = [];

target.queue = queue;
target.queued = queued;

return target;

function queued(action) {
return function () {
var self = this;
var args = arguments;

queue(function (next) {
action.apply(self, array.concat.apply(next, args));
});
};
}

function queue(action) {
if (!action) {
return;
}

queueing.push(action);

if (queueing.length === 1) {
next();
}
}

function next() {
queueing[0](function (err) {
if (err) {
throw err;
}

queueing = queueing.slice(1);

if (queueing.length) {
next();
}
});
}
}
``````

### How to write multiple conditions in Makefile.am with "else if"

``````ifeq (\$(CHIPSET),8960)
BLD_ENV_BUILD_ID="8960"
else ifeq (\$(CHIPSET),8930)
BLD_ENV_BUILD_ID="8930"
else ifeq (\$(CHIPSET),8064)
BLD_ENV_BUILD_ID="8064"
else ifeq (\$(CHIPSET), 9x15)
BLD_ENV_BUILD_ID="9615"
else
BLD_ENV_BUILD_ID=
endif
``````

### ggplot combining two plots from different data.frames

The only working solution for me, was to define the data object in the geom_line instead of the base object, ggplot.

Like this:

``````ggplot() +
geom_line(data=Data1, aes(x=A, y=B), color='green') +
geom_line(data=Data2, aes(x=C, y=D), color='red')
``````

``````ggplot(data=Data1, aes(x=A, y=B), color='green') +
geom_line() +
geom_line(data=Data2, aes(x=C, y=D), color='red')
``````

### Getting a link to go to a specific section on another page

I tried the above answer - using `page.html#ID_name` it gave me a 404 page doesn't exist error.

Then instead of using `.html`, I simply put a slash `/` before the `#` and that worked fine. So my example on the sending page between the link tags looks like:

``````<a href= "http://my website.com/target-page/#El_Chorro">El Chorro</a>
``````

Just use `/` instead of `.html`.

### C# DateTime.ParseExact

It's probably the same problem with cultures as presented in this related SO-thread: Why can't DateTime.ParseExact() parse "9/1/2009" using "M/d/yyyy"

You already specified the culture, so try escaping the slashes.

### How to convert int to char with leading zeros?

Not very elegant, but I add a set value with the same number of leading zeroes I desire to the numeric I want to convert, and use RIGHT function.

Example:

``````SELECT RIGHT(CONVERT(CHAR(7),1000000 + @number2),6)
``````

Result: '000867'

### remove legend title in ggplot

For `Error: 'opts' is deprecated`. Use `theme()` instead. (Defunct; last used in version 0.9.1)' I replaced `opts(title = "Boxplot - Candidate's Tweet Scores")` with `labs(title = "Boxplot - Candidate's Tweet Scores")`. It worked!

### How do I return JSON without using a template in Django?

I think the issue has gotten confused regarding what you want. I imagine you're not actually trying to put the HTML in the JSON response, but rather want to alternatively return either HTML or JSON.

First, you need to understand the core difference between the two. HTML is a presentational format. It deals more with how to display data than the data itself. JSON is the opposite. It's pure data -- basically a JavaScript representation of some Python (in this case) dataset you have. It serves as merely an interchange layer, allowing you to move data from one area of your app (the view) to another area of your app (your JavaScript) which normally don't have access to each other.

With that in mind, you don't "render" JSON, and there's no templates involved. You merely convert whatever data is in play (most likely pretty much what you're passing as the context to your template) to JSON. Which can be done via either Django's JSON library (simplejson), if it's freeform data, or its serialization framework, if it's a queryset.

simplejson

``````from django.utils import simplejson

some_data_to_dump = {
'some_var_1': 'foo',
'some_var_2': 'bar',
}

data = simplejson.dumps(some_data_to_dump)
``````

Serialization

``````from django.core import serializers

foos = Foo.objects.all()

data = serializers.serialize('json', foos)
``````

Either way, you then pass that data into the response:

``````return HttpResponse(data, content_type='application/json')
``````

 In Django 1.6 and earlier, the code to return response was

``````return HttpResponse(data, mimetype='application/json')
``````

[EDIT]: simplejson was remove from django, you can use:

``````import json

json.dumps({"foo": "bar"})
``````

Or you can use the `django.core.serializers` as described above.

### How to match a line not containing a word

This should work:

``````/^((?!PART).)*\$/
``````

If you only wanted to exclude it from the beginning of the line (I know you don't, but just FYI), you could use this:

``````/^(?!PART)/
``````

#### Edit (by request): Why this pattern works

The `(?!...)` syntax is a negative lookahead, which I've always found tough to explain. Basically, it means "whatever follows this point must not match the regular expression `/PART/`." The site I've linked explains this far better than I can, but I'll try to break this down:

``````^         #Start matching from the beginning of the string.
(?!PART)  #This position must not be followed by the string "PART".
.         #Matches any character except line breaks (it will include those in single-line mode).
\$         #Match all the way until the end of the string.
``````

The `((?!xxx).)*` idiom is probably hardest to understand. As we saw, `(?!PART)` looks at the string ahead and says that whatever comes next can't match the subpattern `/PART/`. So what we're doing with `((?!xxx).)*` is going through the string letter by letter and applying the rule to all of them. Each character can be anything, but if you take that character and the next few characters after it, you'd better not get the word PART.

The `^` and `\$` anchors are there to demand that the rule be applied to the entire string, from beginning to end. Without those anchors, any piece of the string that didn't begin with PART would be a match. Even PART itself would have matches in it, because (for example) the letter A isn't followed by the exact string PART.

Since we do have `^` and `\$`, if PART were anywhere in the string, one of the characters would match `(?=PART).` and the overall match would fail. Hope that's clear enough to be helpful.

### How to add external library in IntelliJ IDEA?

• Copy jar to libs directory in the app (you can create the directory it if not there)
• Refresh project so libs show up in the structure (right click on project top level, refresh/synchronize)
• Expand libs and right click on the jar

Done

### JSF rendered multiple combined conditions

Assuming that "a" and "b" are bean properties

``````rendered="#{bean.a==12 and (bean.b==13 or bean.b==15)}"
``````

You may look at JSF EL operators

# With `React hook - useRef`

``````

const MyComponent = ({myRef}) => {
const handleClick = () => alert('hello world')
myRef.current.handleClick = handleClick
return (<button onClick={handleClick}>Original Button</button>)
}

MyComponent.defaultProps = {
myRef: {current: {}}
}

const MyParentComponent = () => {
const myRef = React.useRef({})
return (
<>
<MyComponent
myRef={myRef}
/>
<button onClick={myRef.current.handleClick}>
</button>
</>
)
}
``````

Good Luck...

### How to give Jenkins more heap space when itÂ´s started as a service under Windows?

If you are using Jenkins templates you could have additional VM settings defined in it and this might conflicting with your system VM settings

example your tempalate may have references such as these

`````` <mavenOpts>-Xms512m -Xmx1024m -Xss1024k -XX:MaxPermSize=1024m -Dmaven.test.failure.ignore=false</mavenOpts>
``````

Ensure to align these template entries with the VM setting of your system

### Programmatically change UITextField Keyboard type

This is the `UIKeyboardTypes` for Swift 3:

``````public enum UIKeyboardType : Int {

case `default` // Default type for the current input method.
case asciiCapable // Displays a keyboard which can enter ASCII characters
case numbersAndPunctuation // Numbers and assorted punctuation.
case URL // A type optimized for URL entry (shows . / .com prominently).
case numberPad // A number pad with locale-appropriate digits (0-9, ?-?, ?-?, etc.). Suitable for PIN entry.
case phonePad // A phone pad (1-9, *, 0, #, with letters under the numbers).
case namePhonePad // A type optimized for entering a person's name or phone number.
case emailAddress // A type optimized for multiple email address entry (shows space @ . prominently).

@available(iOS 4.1, *)

@available(iOS 5.0, *)

@available(iOS 7.0, *)
case webSearch // A default keyboard type with URL-oriented addition (shows space . prominently).

@available(iOS 10.0, *)
case asciiCapableNumberPad // A number pad (0-9) that will always be ASCII digits.

public static var alphabet: UIKeyboardType { get } // Deprecated
}
``````

This is an example to use a keyboard type from the list:

``````textField.keyboardType = .numberPad
``````

### Constantly print Subprocess output while process is running

To print subprocess' output line-by-line as soon as its stdout buffer is flushed in Python 3:

``````from subprocess import Popen, PIPE, CalledProcessError

with Popen(cmd, stdout=PIPE, bufsize=1, universal_newlines=True) as p:
for line in p.stdout:
print(line, end='') # process line here

if p.returncode != 0:
raise CalledProcessError(p.returncode, p.args)
``````

Notice: you do not need `p.poll()` -- the loop ends when eof is reached. And you do not need `iter(p.stdout.readline, '')` -- the read-ahead bug is fixed in Python 3.

### How to insert a line break before an element using CSS

Instead of manually adding a line break somehow, you can do implement `border-bottom: 1px solid #ff0000` which will take the element's border and only render `border-<side>` of whichever side you specify.

### Fastest Way of Inserting in Entity Framework

TL;DR I know it is an old post, but I have implemented a solution starting from one of those proposed by extending it and solving some problems of this; moreover I have also read the other solutions presented and compared to these it seems to me to propose a solution that is much more suited to the requests formulated in the original question.

In this solution I extend Slauma's approach which I would say is perfect for the case proposed in the original question, and that is to use Entity Framework and Transaction Scope for an expensive write operation on the db.

In Slauma's solution - which incidentally was a draft and was only used to get an idea of ??the speed of EF with a strategy to implement bulk-insert - there were problems due to:

1. the timeout of the transaction (by default 1 minute extendable via code to max 10 minutes);
2. the duplication of the first block of data with a width equal to the size of the commit used at the end of the transaction (this problem is quite weird and circumvented by means of a workaround).

I also extended the case study presented by Slauma by reporting an example that includes the contextual insertion of several dependent entities.

The performances that I have been able to verify have been of 10K rec/min inserting in the db a block of 200K wide records approximately 1KB each. The speed was constant, there was no degradation in performance and the test took about 20 minutes to run successfully.

The solution in detail

the method that presides over the bulk-insert operation inserted in an example repository class:

``````abstract class SomeRepository {

protected MyDbContext myDbContextRef;

public void ImportData<TChild, TFather>(List<TChild> entities, TFather entityFather)
where TChild : class, IEntityChild
where TFather : class, IEntityFather
{

using (var scope = MyDbContext.CreateTransactionScope())
{

MyDbContext context = null;
try
{
context = new MyDbContext(myDbContextRef.ConnectionString);

context.Configuration.AutoDetectChangesEnabled = false;

entityFather.BulkInsertResult = false;
context.SaveChanges();

int count = 0;

//avoids an issue with recreating context: EF duplicates the first commit block of data at the end of transaction!!
context = MyDbContext.AddToContext<TChild>(context, null, 0, 1, true);

foreach (var entityToInsert in entities)
{
++count;
entityToInsert.EntityFatherRefId = fileEntity.Id;
context = MyDbContext.AddToContext<TChild>(context, entityToInsert, count, 100, true);
}

entityFather.BulkInsertResult = true;
context.Entry<TFather>(fileEntity).State = EntityState.Modified;

context.SaveChanges();
}
finally
{
if (context != null)
context.Dispose();
}

scope.Complete();
}

}

}
``````

interfaces used for example purposes only:

``````public interface IEntityChild {

//some properties ...

int EntityFatherRefId { get; set; }

}

public interface IEntityFather {

int Id { get; set; }
bool BulkInsertResult { get; set; }
}
``````

db context where I implemented the various elements of the solution as static methods:

``````public class MyDbContext : DbContext
{

public string ConnectionString { get; set; }

public MyDbContext(string nameOrConnectionString)
: base(nameOrConnectionString)
{
Database.SetInitializer<MyDbContext>(null);
ConnectionString = Database.Connection.ConnectionString;
}

/// <summary>
/// Creates a TransactionScope raising timeout transaction to 30 minutes
/// </summary>
/// <param name="_isolationLevel"></param>
/// <param name="timeout"></param>
/// <remarks>
/// It is possible to set isolation-level and timeout to different values. Pay close attention managing these 2 transactions working parameters.
/// <para>Default TransactionScope values for isolation-level and timeout are the following:</para>
/// <para>Default isolation-level is "Serializable"</para>
/// <para>Default timeout ranges between 1 minute (default value if not specified a timeout) to max 10 minute (if not changed by code or updating max-timeout machine.config value)</para>
/// </remarks>
public static TransactionScope CreateTransactionScope(IsolationLevel _isolationLevel = IsolationLevel.Serializable, TimeSpan? timeout = null)
{
SetTransactionManagerField("_cachedMaxTimeout", true);
SetTransactionManagerField("_maximumTimeout", timeout ?? TimeSpan.FromMinutes(30));

var transactionOptions = new TransactionOptions();
transactionOptions.IsolationLevel = _isolationLevel;
transactionOptions.Timeout = TransactionManager.MaximumTimeout;
return new TransactionScope(TransactionScopeOption.Required, transactionOptions);
}

private static void SetTransactionManagerField(string fieldName, object value)
{
typeof(TransactionManager).GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Static).SetValue(null, value);
}

/// <summary>
/// Adds a generic entity to a given context allowing commit on large block of data and improving performance to support db bulk-insert operations based on Entity Framework
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="context"></param>
/// <param name="entity"></param>
/// <param name="count"></param>
/// <param name="commitCount">defines the block of data size</param>
/// <param name="recreateContext"></param>
/// <returns></returns>
public static MyDbContext AddToContext<T>(MyDbContext context, T entity, int count, int commitCount, bool recreateContext) where T : class
{
if (entity != null)

if (count % commitCount == 0)
{
context.SaveChanges();
if (recreateContext)
{
var contextConnectionString = context.ConnectionString;
context.Dispose();
context = new MyDbContext(contextConnectionString);
context.Configuration.AutoDetectChangesEnabled = false;
}
}

return context;
}
}
``````

### MySQL check if a table exists without throwing an exception

Why you make it so hard to understand?

``````function table_exist(\$table){
\$pTableExist = mysql_query("show tables like '".\$table."'");
if (\$rTableExist = mysql_fetch_array(\$pTableExist)) {
return "Yes";
}else{
return "No";
}
}
``````

### Angular update object in object array

Another approach could be:

``````let myList = [{id:'aaa1', name: 'aaa'}, {id:'bbb2', name: 'bbb'}, {id:'ccc3', name: 'ccc'}];
let itemUpdated = {id: 'aaa1', name: 'Another approach'};

myList.find(item => item.id == itemUpdated.id).name = itemUpdated.name;
``````

### Sound alarm when code finishes

This one seems to work on both Windows and Linux* (from this question):

``````def beep():
print("\a")

beep()
``````

In Windows, can put at the end:

``````import winsound
winsound.Beep(500, 1000)

where 500 is the frequency in Herz
1000 is the duration in miliseconds
``````

To work on Linux, you may need to do the following (from QO's comment):

• in a terminal, type 'cd /etc/modprobe.d' then 'gksudo gedit blacklist.conf'
• comment the line that says 'blacklist pcspkr', then reboot
• check also that the terminal preferences has the 'Terminal Bell' checked.

### concatenate two strings

You need to use the string concatenation operator `+`

``````String both = name + "-" + dest;
``````

### Why does DEBUG=False setting make my django Static Files Access fail?

Although it's not safest, but you can change in the source code. navigate to `Python/2.7/site-packages/django/conf/urls/static.py`

Then edit like following:

``````if settings.DEBUG or (prefix and '://' in prefix):
``````

So then if `settings.debug==False` it won't effect on the code, also after running try `python manage.py runserver --runserver` to run static files.

NOTE: Information should only be used for testing only

### Disable scrolling on `<input type=number>`

``````\$(document).on("wheel", "input[type=number]", function (e) {
\$(this).blur();
});
``````

### How to prevent custom views from losing state across screen orientation changes

To augment other answers - if you have multiple custom compound views with the same ID and they are all being restored with the state of the last view on a configuration change, all you need to do is tell the view to only dispatch save/restore events to itself by overriding a couple of methods.

``````class MyCompoundView : ViewGroup {

...

override fun dispatchSaveInstanceState(container: SparseArray<Parcelable>) {
dispatchFreezeSelfOnly(container)
}

override fun dispatchRestoreInstanceState(container: SparseArray<Parcelable>) {
dispatchThawSelfOnly(container)
}
}
``````

For an explanation of what is happening and why this works, see this blog post. Basically your compound view's children's view IDs are shared by each compound view and state restoration gets confused. By only dispatching state for the compound view itself, we prevent their children from getting mixed messages from other compound views.

### What are the retransmission rules for TCP?

There's no fixed time for retransmission. Simple implementations estimate the RTT (round-trip-time) and if no ACK to send data has been received in 2x that time then they re-send.

They then double the wait-time and re-send once more if again there is no reply. Rinse. Repeat.

More sophisticated systems make better estimates of how long it should take for the ACK as well as guesses about exactly which data has been lost.

The bottom-line is that there is no hard-and-fast rule about exactly when to retransmit. It's up to the implementation. All retransmissions are triggered solely by the sender based on lack of response from the receiver.

TCP never drops data so no, there is no way to indicate a server should forget about some segment.

### How do I get the HTTP status code with jQuery?

I encapsulate the jQuery Ajax to a method:

``````var http_util = function (type, url, params, success_handler, error_handler, base_url) {

if(base_url) {
url = base_url + url;
}

var success = arguments[3]?arguments[3]:function(){};
var error = arguments[4]?arguments[4]:function(){};

\$.ajax({
type: type,
url: url,
dataType: 'json',
data: params,
success: function (data, textStatus, xhr) {

if(textStatus === 'success'){
success(xhr.code, data);   // there returns the status code
}
},
error: function (xhr, error_text, statusText) {

error(xhr.code, xhr);  // there returns the status code
}
})

}
``````

Usage:

``````http_util('get', 'http://localhost:8000/user/list/', null, function (status_code, data) {
console(status_code, data)
}, function(status_code, err){
console(status_code, err)
})
``````

### How to decode Unicode escape sequences like "\u00ed" to proper UTF-8 encoded characters?

``````print_r(json_decode('{"t":"\u00ed"}')); // -> stdClass Object ( [t] => Ã­ )
``````

### When is del useful in Python?

To add a few points to above answers: `del x`

Definition of `x` indicates `r -> o` (a reference `r` pointing to an object `o`) but `del x` changes `r` rather than `o`. It is an operation on the reference (pointer) to object rather than the object associated with `x`. Distinguishing between `r` and `o` is key here.

• It removes it from `locals()`.
• Removes it from `globals()` if `x` belongs there.
• Removes it from the stack frame (removes the reference physically from it, but the object itself resides in object pool and not in the stack frame).
• Removes it from the current scope. It is very useful to limit the span of definition of a local variable, which otherwise can cause problems.
• It is more about declaration of the name rather than definition of content.
• It affects where `x` belongs to, not where `x` points to. The only physical change in memory is this. For example if `x` is in a dictionary or list, it (as a reference) is removed from there(and not necessarily from the object pool). In this example, the dictionary it belongs is the stack frame (`locals()`), which overlaps with `globals()`.

### Codeigniter how to create PDF

I have used mpdf in my project. In Codeigniter-3, putted mpdf files under application/third_party and then used in this way:

`````` /**
* This function is used to display data in PDF file.
* function is using mpdf api to generate pdf.
* @param number \$id : This is unique id of table.
*/
function generatePDF(\$id){
//\$mpdf=new mPDF();
\$mpdf = new mPDF('utf-8', 'Letter', 0, '', 0, 0, 7, 0, 0, 0);

\$checkRecords =  \$this->user_model->getCheckInfo(\$id);
foreach (\$checkRecords as \$key => \$value) {
\$data['info'] = \$value;
\$mpdf->WriteHTML(\$filename);
}

\$mpdf->Output(); //output pdf document.
//\$content = \$mpdf->Output('', 'S'); //get pdf document content's as variable.

}
``````

### How to rebase local branch onto remote master

Step 1:

``````git fetch origin
``````

Step 2:

``````git rebase origin/master
``````

Step 3:(Fix if any conflicts)

``````git add .
``````

Step 4:

``````git rebase --continue
``````

Step 5:

``````git push --force
``````

### Change the Arrow buttons in Slick slider

Easy solution:

``````\$('.slick-slider').slick({
arrows: true,
prevArrow:"<img class='a-left control-c prev slick-prev' src='YOUR LEFT ARROW IMAGE URL'>",
nextArrow:"<img class='a-right control-c next slick-next' src='YOUR RIGHT ARROW IMAGE URL'>"
});
``````

Image URLs can be local or cdn-type stuff (web icons, etc.).

Example CSS (adjust as needed here, this is just an example of what's possible):

``````.control-c {
width: 30px;
height: 30px;
}
``````

This worked well for me!

### PyLint "Unable to import" error - how to set PYTHONPATH?

Maybe by manually appending the dir inside the PYTHONPATH?

``````sys.path.append(dirname)
``````

### Using JavaScript to display a Blob

I guess you had an error in the inline code of your image. Try this :

_x000D_
_x000D_
``````var image = document.createElement('img');_x000D_
_x000D_
_x000D_
image.width=100;_x000D_
image.height=100;_x000D_
image.alt="here should be some image";_x000D_
_x000D_
document.body.appendChild(image);``````
_x000D_
_x000D_
_x000D_

### The import android.support cannot be resolved

I followed the instructions above by Gene in Android Studio 1.5.1 but it added this to my build.gradle file:

``````compile 'platforms:android:android-support-v4:23.1.1'
``````

so I changed it to:

``````compile 'com.android.support:support-v4:23.1.1'
``````

And it started working.

### Android M - check runtime permission - how to determine if the user checked "Never ask again"?

You can use

``````shouldShowRequestPermissionRationale()
``````

inside

``````onRequestPermissionsResult()
``````

See the example below:

Check if it has permission when the user clicks the button:

``````@Override
public void onClick(View v) {
if (v.getId() == R.id.appCompatBtn_changeProfileCoverPhoto) {
if (Build.VERSION.SDK_INT < 23) { // API < 23 don't need to ask permission
navigateTo(MainActivity.class); // Navigate to activity to change photos
} else {
if (ContextCompat.checkSelfPermission(SettingsActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
// Permission is not granted yet. Ask for permission...
requestWriteExternalPermission();
} else {
// Permission is already granted, good to go :)
navigateTo(MainActivity.class);
}
}
}
}
``````

When the user answer the permission dialog box we will go to onRequestPermissionResult:

``````@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);

if (requestCode == WRITE_EXTERNAL_PERMISSION_REQUEST_CODE) {
// Case 1. Permission is granted.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(SettingsActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
// Before navigating, I still check one more time the permission for good practice.
navigateTo(MainActivity.class);
}
} else { // Case 2. Permission was refused
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
// Case 2.1. shouldShowRequest... returns true because the
// permission was denied before. If it is the first time the app is running we will
// end up in this part of the code. Because he need to deny at least once to get
// to onRequestPermissionsResult.
Snackbar snackbar = Snackbar.make(findViewById(R.id.relLayout_container), R.string.you_must_verify_permissions_to_send_media, Snackbar.LENGTH_LONG);
snackbar.setAction("VERIFY", new View.OnClickListener() {
@Override
public void onClick(View v) {
ActivityCompat.requestPermissions(SettingsActivity.this
, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}
, WRITE_EXTERNAL_PERMISSION_REQUEST_CODE);
}
});
snackbar.show();
} else {
// Case 2.2. Permission was already denied and the user checked "Never ask again".
// Navigate user to settings if he choose to allow this time.
builder.setMessage(R.string.instructions_to_turn_on_storage_permission)
@Override
public void onClick(DialogInterface dialog, int which) {
Intent settingsIntent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getPackageName(), null);
settingsIntent.setData(uri);
startActivityForResult(settingsIntent, 7);
}
})
.setNegativeButton(getString(R.string.not_now), null);
Dialog dialog = builder.create();
dialog.show();
}
}
}

}
``````

### Errno 13 Permission denied Python

If you have this problem in Windows 10, and you know you have premisions on folder (You could write before but it just started to print exception PermissionError recently).. You will need to install Windows updates... I hope someone will help this info.

### How to set max_connections in MySQL Programmatically

You can set max connections using:

`set global max_connections = '1 < your number > 100000';`

This will set your number of mysql connection unti (Requires `SUPER` privileges).

### How to install and run Typescript locally in npm?

`tsc` requires a config file or .ts(x) files to compile.

To solve both of your issues, create a file called `tsconfig.json` with the following contents:

``````{
"compilerOptions": {
"outFile": "../../built/local/tsc.js"
},
"exclude": [
"node_modules"
]
}
``````

Also, modify your npm run with this

``````tsc --config /path/to/a/tsconfig.json
``````

### How to upload a file from Windows machine to Linux machine using command lines via PuTTy?

• Open command prompt and follow steps mentioned below
• cd path/from/where/file/istobe/copied
• ftp (serverip or name)
• cd path/where/file/istobe/copied
• pwd (to check current path)
• mput (directory name which is to be copied)

This should work.

### How can I properly use a PDO object for a parameterized SELECT query

Method 1:USE PDO query method

``````\$stmt = \$db->query('SELECT id FROM Employee where name ="'.\$name.'"');
\$results = \$stmt->fetchAll(PDO::FETCH_ASSOC);
``````

Getting Row Count

``````\$stmt = \$db->query('SELECT id FROM Employee where name ="'.\$name.'"');
\$row_count = \$stmt->rowCount();
echo \$row_count.' rows selected';
``````

Method 2: Statements With Parameters

``````\$stmt = \$db->prepare("SELECT id FROM Employee WHERE name=?");
\$stmt->execute(array(\$name));
\$rows = \$stmt->fetchAll(PDO::FETCH_ASSOC);
``````

Method 3:Bind parameters

``````\$stmt = \$db->prepare("SELECT id FROM Employee WHERE name=?");
\$stmt->bindValue(1, \$name, PDO::PARAM_STR);
\$stmt->execute();
\$rows = \$stmt->fetchAll(PDO::FETCH_ASSOC);

**bind with named parameters**
\$stmt = \$db->prepare("SELECT id FROM Employee WHERE name=:name");
\$stmt->bindValue(':name', \$name, PDO::PARAM_STR);
\$stmt->execute();
\$rows = \$stmt->fetchAll(PDO::FETCH_ASSOC);

or
\$stmt = \$db->prepare("SELECT id FROM Employee WHERE name=:name");
\$stmt->execute(array(':name' => \$name));
\$rows = \$stmt->fetchAll(PDO::FETCH_ASSOC);
``````

Want to know more look at this link

### How to run functions in parallel?

If you are a windows user and using python 3, then this post will help you to do parallel programming in python.when you run a usual multiprocessing library's pool programming, you will get an error regarding the main function in your program. This is because the fact that windows has no fork() functionality. The below post is giving a solution to the mentioned problem .

http://python.6.x6.nabble.com/Multiprocessing-Pool-woes-td5047050.html

Since I was using the python 3, I changed the program a little like this:

``````from types import FunctionType
import marshal

def _applicable(*args, **kwargs):
name = kwargs['__pw_name']
gbls = globals() #gbls = marshal.loads(kwargs['__pw_gbls'])
func = FunctionType(code, gbls, name, defs, clsr)
func.fdct = fdct
del kwargs['__pw_name']
del kwargs['__pw_code']
del kwargs['__pw_defs']
del kwargs['__pw_clsr']
del kwargs['__pw_fdct']
return func(*args, **kwargs)

def make_applicable(f, *args, **kwargs):
if not isinstance(f, FunctionType): raise ValueError('argument must be a function')
kwargs['__pw_name'] = f.__name__  # edited
kwargs['__pw_code'] = marshal.dumps(f.__code__)   # edited
kwargs['__pw_defs'] = marshal.dumps(f.__defaults__)  # edited
kwargs['__pw_clsr'] = marshal.dumps(f.__closure__)  # edited
kwargs['__pw_fdct'] = marshal.dumps(f.__dict__)   # edited
return _applicable, args, kwargs

def _mappable(x):
x,name,code,defs,clsr,fdct = x
gbls = globals() #gbls = marshal.loads(gbls)
func = FunctionType(code, gbls, name, defs, clsr)
func.fdct = fdct
return func(x)

def make_mappable(f, iterable):
if not isinstance(f, FunctionType): raise ValueError('argument must be a function')
name = f.__name__    # edited
code = marshal.dumps(f.__code__)   # edited
defs = marshal.dumps(f.__defaults__)  # edited
clsr = marshal.dumps(f.__closure__)  # edited
fdct = marshal.dumps(f.__dict__)  # edited
return _mappable, ((i,name,code,defs,clsr,fdct) for i in iterable)
``````

After this function , the above problem code is also changed a little like this:

``````from multiprocessing import Pool
from poolable import make_applicable, make_mappable

def cube(x):
return x**3

if __name__ == "__main__":
pool    = Pool(processes=2)
results = [pool.apply_async(*make_applicable(cube,x)) for x in range(1,7)]
print([result.get(timeout=10) for result in results])
``````

And I got the output as :

``````[1, 8, 27, 64, 125, 216]
``````

I am thinking that this post may be useful for some of the windows users.

### Sort an ArrayList based on an object field

You can use the Bean Comparator to sort on any property in your custom class.

### Python csv string to array

Simple - the csv module works with lists, too:

``````>>> a=["1,2,3","4,5,6"]  # or a = "1,2,3\n4,5,6".split('\n')
>>> import csv
>>> list(x)
[['1', '2', '3'], ['4', '5', '6']]
``````

### Data binding in React

With introduction of React hooks the state management (including forms state) became very simple and, in my opinion, way more understandable and predictable comparing with magic of other frameworks. For example:

``````const MyComponent = () => {
const [value, setValue] = React.useState('some initial value');
return <input value={value} onChange={e => setValue(e.target.value)} />;
}
``````

This one-way flow makes it trivial to understand how the data is updated and when rendering happens. Simple but powerful to do any complex stuff in predictable and clear way. In this case, do "two-way" form state binding.

The example uses the primitive string value. Complex state management, eg. objects, arrays, nested data, can be managed this way too, but it is easier with help of libraries, like Hookstate (Disclaimer: I am the author of this library). Here is the example of complex state management.

When a form grows, there is an issue with rendering performance: form state is changed (so rerendering is needed) on every keystroke on any form field. This issue is also addressed by Hookstate. Here is the example of the form with 5000 fields: the state is updated on every keystore and there is no performance lag at all.

### Android - set TextView TextStyle programmatically?

This worked for me

``````textview.setTypeface(textview.getTypeface(), Typeface.BOLD);
``````

or

``````textview.setTypeface(Typeface.DEFAULT_BOLD);
``````

### What is __init__.py for?

`__init__.py` will treat the directory it is in as a loadable module.

For people who prefer reading code, I put Two-Bit Alchemist's comment here.

``````\$ find /tmp/mydir/
/tmp/mydir/
/tmp/mydir//spam
/tmp/mydir//spam/__init__.py
/tmp/mydir//spam/module.py
\$ cd ~
\$ python
>>> import sys
>>> sys.path.insert(0, '/tmp/mydir')
>>> from spam import module
>>> module.myfun(3)
9
>>> exit()
\$
\$ rm /tmp/mydir/spam/__init__.py*
\$
\$ python
>>> import sys
>>> sys.path.insert(0, '/tmp/mydir')
>>> from spam import module
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named spam
>>>
``````

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

I believe the simplest method would be to use Python:

``````python -m webbrowser "http://www.example.com/"
``````

### How to detect the character encoding of a text file?

Use `StreamReader` and direct it to detect the encoding for you:

``````using (var reader = new System.IO.StreamReader(path, true))
{
}
``````

And use Code Page Identifiers https://msdn.microsoft.com/en-us/library/windows/desktop/dd317756(v=vs.85).aspx in order to switch logic depending on it.

### Get Row Index on Asp.net Rowcommand event

``````GridViewRow gvr = (GridViewRow)((ImageButton)e.CommandSource).NamingContainer;

int RowIndex = gvr.RowIndex;
``````

### Installing a dependency with Bower from URL and specify version

If you use bower.json file to specify your dependencies:

``````{
"dependencies": {
...
"photo-swipe": "[email protected]:dimsemenov/PhotoSwipe.git#v3.0.x",

#bower 1.4 (tested with that version) can read repositorios with uri format

"photo-swipe": "git://github.com/dimsemenov/PhotoSwipe.git#v3.0.x",

}
}
``````

Just remember bower also searches for released versions and tags so you can point to almost everything, and can interprate basic query patterns like previous example. that will fetch latest minor update of version 3.0 (tested from bower 1.3.5)

Update, as the question description also mention using only a URL and no mention of a github repository.

Another example is to execute this command using the desired url, like:

``````bower install gmap3MarkerWithLabel=http://google-maps-utility-library-v3.googlecode.com/svn/tags/markerwithlabel/1.0/src/markerwithlabel.js -S
``````

that command downloads your js library puts in {your destination path}/gmap3MarkerWithLabel/index.js and automatically creates an entry in your bower.json file called gmap3MarkerWithLabel: "..." After that, you can only execute `bower update gmap3MarkerWithLabel` if needed.

Funny thing if you do the process backwars (add manually the entry in bower.json, an then bower install entryName) it doesn't work, you get a

### Alternate table with new not null Column in existing table in SQL

There are two ways to add the NOT NULL Columns to the table :

1. ALTER the table by adding the column with NULL constraint. Fill the column with some data. Ex: column can be updated with ''

2. ALTER the table by adding the column with NOT NULL constraint by giving DEFAULT values. ALTER table TableName ADD NewColumn DataType NOT NULL DEFAULT ''

### Unsupported method: BaseConfig.getApplicationIdSuffix()

You can do this by changing the gradle file.

`````` build.gradle > change
dependencies {
}
``````

### How do I disable Git Credential Manager for Windows?

If you notice the credential manager UI popping up when you use a JetBrains IDE (such as IntelliJ IDEA, PhpStorm, WebStorm, PyCharm, Rider, RubyMine, Android Studio, or Goland), do this:

1. In your IDE, go to File | Settings | Version Control | Git.

2. Disable Use credential helper:

3. Don't forget to press Save.

### How to check if an alert exists using WebDriver?

This code will check whether the alert is present or not.

``````public static void isAlertPresent(){
try{
}
}
}
``````

### How to use refs in React with Typescript

One way (which I've been doing) is to setup manually :

``````refs: {
[string: string]: any;
stepInput:any;
}
``````

then you can even wrap this up in a nicer getter function (e.g. here):

``````stepInput = (): HTMLInputElement => ReactDOM.findDOMNode(this.refs.stepInput);
``````

### How to add Date Picker Bootstrap 3 on MVC 5 project using the Razor engine?

Checkout Shield UI's Date Picker for MVC. A powerful component that you can integrate with a few lines like:

``````@(Html.ShieldDatePicker()
.Name("datepicker"))
``````

### Convert JSON to DataTable

Here is another seamless approach to convert JSON to Datatable using Cinchoo ETL - an open source library

Sample below shows how to convert

``````string json = @"[
]";

{
var dt = r.AsDataTable();
}
``````

Hope it helps.

### How to add months to a date in JavaScript?

Corrected as of 25.06.2019:

``````var newDate = new Date(date.setMonth(date.getMonth()+8));
``````

Old From here:

``````var jan312009 = new Date(2009, 0, 31);
var eightMonthsFromJan312009  = jan312009.setMonth(jan312009.getMonth()+8);
``````

### Combining two Series into a DataFrame in pandas

Not sure I fully understand your question, but is this what you want to do?

``````pd.DataFrame(data=dict(s1=s1, s2=s2), index=s1.index)
``````

(`index=s1.index` is not even necessary here)

### How can I quickly delete a line in VIM starting at the cursor position?

You might also be interested in C, it will also delete the end of line like D, but additionally it will put you in Insert mode at the cursor location.

### How to retrieve JSON Data Array from ExtJS Store

As suggested above I tried below one with fail.

``````store.proxy.reader.jsonData
``````

But below one worked for me

``````store.proxy.reader.rawData
``````

### Merging two CSV files using Python

When I'm working with `csv` files, I often use the pandas library. It makes things like this very easy. For example:

``````import pandas as pd

b = b.dropna(axis=1)
merged = a.merge(b, on='title')
merged.to_csv("output.csv", index=False)
``````

Some explanation follows. First, we read in the csv files:

``````>>> a = pd.read_csv("filea.csv")
>>> a
title  stage    jan    feb
0   darn  3.001  0.421  0.532
1     ok  2.829  1.036  0.751
2  three  1.115  1.146  2.921
>>> b
title    mar    apr    may       jun  Unnamed: 5
0   darn  0.631  1.321  0.951    1.7510         NaN
1     ok  1.001  0.247  2.456    0.3216         NaN
2  three  0.285  1.283  0.924  956.0000         NaN
``````

and we see there's an extra column of data (note that the first line of `fileb.csv` -- `title,mar,apr,may,jun,` -- has an extra comma at the end). We can get rid of that easily enough:

``````>>> b = b.dropna(axis=1)
>>> b
title    mar    apr    may       jun
0   darn  0.631  1.321  0.951    1.7510
1     ok  1.001  0.247  2.456    0.3216
2  three  0.285  1.283  0.924  956.0000
``````

Now we can merge `a` and `b` on the title column:

``````>>> merged = a.merge(b, on='title')
>>> merged
title  stage    jan    feb    mar    apr    may       jun
0   darn  3.001  0.421  0.532  0.631  1.321  0.951    1.7510
1     ok  2.829  1.036  0.751  1.001  0.247  2.456    0.3216
2  three  1.115  1.146  2.921  0.285  1.283  0.924  956.0000
``````

and finally write this out:

``````>>> merged.to_csv("output.csv", index=False)
``````

producing:

``````title,stage,jan,feb,mar,apr,may,jun
darn,3.001,0.421,0.532,0.631,1.321,0.951,1.751
ok,2.829,1.036,0.751,1.001,0.247,2.456,0.3216
three,1.115,1.146,2.921,0.285,1.283,0.924,956.0
``````

### Reset/remove CSS styles for element only

Any chance you're looking for the !important rule? It doesn't undo all declarations but it provides a way to override them.

"When an !important rule is used on a style declaration, this declaration overrides any other declaration made in the CSS, wherever it is in the declaration list. Although, !important has nothing to do with specificity."

https://developer.mozilla.org/en-US/docs/CSS/Specificity#The_!important_exception

### What is the coolest thing you can do in <10 lines of simple code? Help me inspire beginners!

``````import sys
for y in range(80):
for x in range(80):
c = complex(x-40.0,y-40.0) / 20.0
z = 0.0
for i in range(100):
z = z*z+c
sys.stdout.write('#' if abs(z) < 2.0 else ' ')
sys.stdout.write('\n')
``````

### Skip the headers when editing a csv file using Python

Doing `row=1` won't change anything, because you'll just overwrite that with the results of the loop.

You want to do `next(reader)` to skip one row.

### Changing capitalization of filenames in Git

File names under OS X are not case sensitive (by default). This is more of an OS problem than a Git problem. If you remove and readd the file, you should get what you want, or rename it to something else and then rename it back.

### Initialize/reset struct to zero/null

I believe you can just assign the empty set (`{}`) to your variable.

``````struct x instance;

for(i = 0; i < n; i++) {
instance = {};
/* Do Calculations */
}
``````

### Update multiple tables in SQL Server using INNER JOIN

You can update with a join if you only affect one table like this:

``````UPDATE table1
SET table1.name = table2.name
FROM table1, table2
WHERE table1.id = table2.id
AND table2.foobar ='stuff'
``````

But you are trying to affect multiple tables with an update statement that joins on multiple tables. That is not possible.

However, updating two tables in one statement is actually possible but will need to create a View using a UNION that contains both the tables you want to update. You can then update the View which will then update the underlying tables.

SQL JOINS

But this is a really hacky parlor trick, use the transaction and multiple updates, it's much more intuitive.

### Python Set Comprehension

``````primes = {x for x in range(2, 101) if all(x%y for y in range(2, min(x, 11)))}
``````

I simplified the test a bit - `if all(x%y` instead of `if not any(not x%y`

I also limited y's range; there is no point in testing for divisors > sqrt(x). So max(x) == 100 implies max(y) == 10. For x <= 10, y must also be < x.

``````pairs = {(x, x+2) for x in primes if x+2 in primes}
``````

Instead of generating pairs of primes and testing them, get one and see if the corresponding higher prime exists.

### How to correctly link php-fpm and Nginx Docker containers?

For anyone else getting

Nginx 403 error: directory index of [folder] is forbidden

when using `index.php` while `index.html` works perfectly and having included `index.php` in the index in the server block of their site config in `sites-enabled`

``````server {
listen 80;

# this path MUST be exactly as docker-compose php volumes
root /usr/share/nginx/html;

index index.php

...
}
``````

Make sure your nginx.conf file at `/etc/nginx/nginx.conf` actually loads your site config in the `http` block...

``````http {

...

include /etc/nginx/conf.d/*.conf;

include /etc/nginx/sites-enabled/*;
}
``````

### Difference between __getattr__ vs __getattribute__

Lets see some simple examples of both `__getattr__` and `__getattribute__` magic methods.

#### `__getattr__`

Python will call `__getattr__` method whenever you request an attribute that hasn't already been defined. In the following example my class Count has no `__getattr__` method. Now in main when I try to access both `obj1.mymin` and `obj1.mymax` attributes everything works fine. But when I try to access `obj1.mycurrent` attribute -- Python gives me `AttributeError: 'Count' object has no attribute 'mycurrent'`

``````class Count():
def __init__(self,mymin,mymax):
self.mymin=mymin
self.mymax=mymax

obj1 = Count(1,10)
print(obj1.mymin)
print(obj1.mymax)
print(obj1.mycurrent)  --> AttributeError: 'Count' object has no attribute 'mycurrent'
``````

Now my class Count has `__getattr__` method. Now when I try to access `obj1.mycurrent` attribute -- python returns me whatever I have implemented in my `__getattr__` method. In my example whenever I try to call an attribute which doesn't exist, python creates that attribute and set it to integer value 0.

``````class Count:
def __init__(self,mymin,mymax):
self.mymin=mymin
self.mymax=mymax

def __getattr__(self, item):
self.__dict__[item]=0
return 0

obj1 = Count(1,10)
print(obj1.mymin)
print(obj1.mymax)
print(obj1.mycurrent1)
``````

#### `__getattribute__`

Now lets see the `__getattribute__` method. If you have `__getattribute__` method in your class, python invokes this method for every attribute regardless whether it exists or not. So why we need `__getattribute__` method? One good reason is that you can prevent access to attributes and make them more secure as shown in the following example.

Whenever someone try to access my attributes that starts with substring 'cur' python raises `AttributeError` exception. Otherwise it returns that attribute.

``````class Count:

def __init__(self,mymin,mymax):
self.mymin=mymin
self.mymax=mymax
self.current=None

def __getattribute__(self, item):
if item.startswith('cur'):
raise AttributeError
return object.__getattribute__(self,item)
# or you can use ---return super().__getattribute__(item)

obj1 = Count(1,10)
print(obj1.mymin)
print(obj1.mymax)
print(obj1.current)
``````

Important: In order to avoid infinite recursion in `__getattribute__` method, its implementation should always call the base class method with the same name to access any attributes it needs. For example: `object.__getattribute__(self, name)` or `super().__getattribute__(item)` and not `self.__dict__[item]`

#### IMPORTANT

If your class contain both getattr and getattribute magic methods then `__getattribute__` is called first. But if `__getattribute__` raises `AttributeError` exception then the exception will be ignored and `__getattr__` method will be invoked. See the following example:

``````class Count(object):

def __init__(self,mymin,mymax):
self.mymin=mymin
self.mymax=mymax
self.current=None

def __getattr__(self, item):
self.__dict__[item]=0
return 0

def __getattribute__(self, item):
if item.startswith('cur'):
raise AttributeError
return object.__getattribute__(self,item)
# or you can use ---return super().__getattribute__(item)
# note this class subclass object

obj1 = Count(1,10)
print(obj1.mymin)
print(obj1.mymax)
print(obj1.current)
``````

If still you are facing checkout for proxy setting, for me it was the proxy setting which were missing and was not able to make the request as direct http/https are blocked. So i configured the proxy from my organization while making the request.

``````npm install https-proxy-agent
or
npm install http-proxy-agent

const httpsProxyAgent = require('https-proxy-agent');
const agent = new httpsProxyAgent("http://yourorganzation.proxy.url:8080");
const options = {
port: 443,
path: '/',
method: 'GET',
agent: agent
};
``````

### Socket.IO - how do I get a list of connected sockets/clients?

Socket.io 1.4.4

Sample code for you.

``````function get_clients_by_room(roomId, namespace) {
io.of(namespace || "/").in(roomId).clients(function (error, clients) {
if (error) { throw error; }
console.log(io.sockets.sockets[clients[0]]); //socket detail
return clients;
});
}
``````

I think will help someone this code block.

### How to use Selenium with Python?

There are a lot of sources for selenium - here is good one for simple use Selenium, and here is a example snippet too Selenium Examples

You can find a lot of good sources to use selenium, it's not too hard to get it set up and start using it.

### Changing specific text's color using NSMutableAttributedString in Swift

Based on the answers before I created a string extension

``````extension String {

func highlightWordsIn(highlightedWords: String, attributes: [[NSAttributedStringKey: Any]]) -> NSMutableAttributedString {
let range = (self as NSString).range(of: highlightedWords)
let result = NSMutableAttributedString(string: self)

for attribute in attributes {
}

return result
}
}
``````

You can pass the attributes for the text to the method

Call like this

``````  let attributes = [[NSAttributedStringKey.foregroundColor:UIColor.red], [NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 17)]]
myLabel.attributedText = "This is a text".highlightWordsIn(highlightedWords: "is a text", attributes: attributes)
``````

### How to get the wsdl file from a webservice's URL

To download the wsdl from a url using Developer Command Prompt for Visual Studio, run it in Administrator mode and enter the following command:

`````` svcutil /t:metadata http://[your-service-url-here]
``````

### Comparing two collections for equality irrespective of the order of items in them

If you use Shouldly, you can use ShouldAllBe with Contains.

``````collection1 = {1, 2, 3, 4};
collection2 = {2, 4, 1, 3};

collection1.ShouldAllBe(item=>collection2.Contains(item)); // true
``````

And finally, you can write an extension.

``````public static class ShouldlyIEnumerableExtensions
{
public static void ShouldEquivalentTo<T>(this IEnumerable<T> list, IEnumerable<T> equivalent)
{
list.ShouldAllBe(l => equivalent.Contains(l));
}
}
``````

UPDATE

A optional parameter exists on ShouldBe method.

``````collection1.ShouldBe(collection2, ignoreOrder: true); // true
``````

### WPF: Grid with column/row margin/padding?

Use a `Border` control outside the cell control and define the padding for that:

``````    <Grid>
<Grid.Resources >
<Style TargetType="Border" >
</Style>
</Grid.Resources>

<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>

<Border Grid.Row="0" Grid.Column="0">
<YourGridControls/>
</Border>
<Border Grid.Row="1" Grid.Column="0">
<YourGridControls/>
</Border>

</Grid>
``````

Source:

### Javascript Thousand Separator / string format

You can use the following function:

_x000D_
_x000D_
``````function format(number, decimals = 2, decimalSeparator = '.', thousandsSeparator = ',') {_x000D_
const roundedNumber = number.toFixed(decimals);_x000D_
let integerPart = '',_x000D_
fractionalPart = '';_x000D_
if (decimals == 0) {_x000D_
integerPart = roundedNumber;_x000D_
decimalSeparator = '';_x000D_
} else {_x000D_
let numberParts = roundedNumber.split('.');_x000D_
integerPart = numberParts[0];_x000D_
fractionalPart = numberParts[1];_x000D_
}_x000D_
integerPart = integerPart.replace(/(\d)(?=(\d{3})+(?!\d))/g, `\$1\${thousandsSeparator}`);_x000D_
return `\${integerPart}\${decimalSeparator}\${fractionalPart}`;_x000D_
}_x000D_
_x000D_
// Use Example_x000D_
_x000D_
let min = 1556454.0001;_x000D_
let max = 15556982.9999;_x000D_
_x000D_
console.time('number format');_x000D_
for (let i = 0; i < 15; i++) {_x000D_
let randomNumber = Math.random() * (max - min) + min;_x000D_
let formated = format(randomNumber, 4, ',', '.'); // formated number_x000D_
_x000D_
console.log('number: ', randomNumber, '; formated: ', formated);_x000D_
}_x000D_
console.timeEnd('number format');``````
_x000D_
_x000D_
_x000D_

### jQuery Screen Resolution Height Adjustment

Here is an example on how to center an object vertically with jQuery:

``````var div= \$('#div_SomeDivYouWantToAdjust');
div.css("top", (\$(window).height() - div.height())/2  + 'px');
``````

But you could easily change that to whatever your needs are.

### Find the day of a week

This should do the trick

``````df = data.frame(date=c("2012-02-01", "2012-02-01", "2012-02-02"))
dow <- function(x) format(as.Date(x), "%A")
df\$day <- dow(df\$date)
df

#Returns:
date       day
1 2012-02-01 Wednesday
2 2012-02-01 Wednesday
3 2012-02-02  Thursday
``````

### How do I do logging in C# without using 3rd party libraries?

I used to write my own error logging until I discovered ELMAH. I've never been able to get the emailing part down quite as perfectly as ELMAH does.

### Signing a Windows EXE file

The ASP's magazine ASPects has a detailed description on how to sign code (You have to be a member to read the article). You can download it through http://www.asp-shareware.org/

Here's link to a description how you can make your own test certificate.

This might also be interesting.

### What does "make oldconfig" do exactly in the Linux kernel makefile?

Summary

As mentioned by Ignacio, it updates your `.config` for you after you update the kernel source, e.g. with `git pull`.

It tries to keep your existing options.

Having a script for that is helpful because:

• new options may have been added, or old ones removed

• the kernel's Kconfig configuration format has options that:

• imply one another via `select`
• depend on another via `depends`

Those option relationships make manual config resolution even harder.

Let's modify .config manually to understand how it resolves configurations

First generate a default configuration with:

``````make defconfig
``````

Now edit the generated `.config` file manually to emulate a kernel update and run:

``````make oldconfig
``````

to see what happens. Some conclusions:

1. Lines of type:

``````# CONFIG_XXX is not set
``````

are not mere comments, but actually indicate that the parameter is not set.

For example, if we remove the line:

``````# CONFIG_DEBUG_INFO is not set
``````

and run `make oldconfig`, it will ask us:

``````Compile the kernel with debug info (DEBUG_INFO) [N/y/?] (NEW)
``````

When it is over, the `.config` file will be updated.

If you change any character of the line, e.g. to `# CONFIG_DEBUG_INFO`, it does not count.

2. Lines of type:

``````# CONFIG_XXX is not set
``````

are always used for the negation of a property, although:

``````CONFIG_XXX=n
``````

is also understood as the negation.

For example, if you remove `# CONFIG_DEBUG_INFO is not set` and answer:

``````Compile the kernel with debug info (DEBUG_INFO) [N/y/?] (NEW)
``````

with `N`, then the output file contains:

``````# CONFIG_DEBUG_INFO is not set
``````

and not:

``````CONFIG_DEBUG_INFO=n
``````

Also, if we manually modify the line to:

``````CONFIG_DEBUG_INFO=n
``````

and run `make oldconfig`, then the line gets modified to:

``````# CONFIG_DEBUG_INFO is not set
``````

without `oldconfig` asking us.

3. Configs whose dependencies are not met, do not appear on the `.config`. All others do.

For example, set:

``````CONFIG_DEBUG_INFO=y
``````

and run `make oldconfig`. It will now ask us for: `DEBUG_INFO_REDUCED`, `DEBUG_INFO_SPLIT`, etc. configs.

Those properties did not appear on the `defconfig` before.

If we look under `lib/Kconfig.debug` where they are defined, we see that they depend on `DEBUG_INFO`:

``````config DEBUG_INFO_REDUCED
bool "Reduce debugging information"
depends on DEBUG_INFO
``````

So when `DEBUG_INFO` was off, they did not show up at all.

4. Configs which are `selected` by turned on configs are automatically set without asking the user.

For example, if `CONFIG_X86=y` and we remove the line:

``````CONFIG_ARCH_MIGHT_HAVE_PC_PARPORT=y
``````

and run `make oldconfig`, the line gets recreated without asking us, unlike `DEBUG_INFO`.

This happens because `arch/x86/Kconfig` contains:

``````config X86
def_bool y
[...]
select ARCH_MIGHT_HAVE_PC_PARPORT
``````

5. Configs whose constraints are not met are asked for.

For example, `defconfig` had set:

``````CONFIG_64BIT=y
CONFIG_RCU_FANOUT=64
``````

If we edit:

``````CONFIG_64BIT=n
``````

and run `make oldconfig`, it will ask us:

``````Tree-based hierarchical RCU fanout value (RCU_FANOUT) [32] (NEW)
``````

This is because `RCU_FANOUT` is defined at `init/Kconfig` as:

``````config RCU_FANOUT
int "Tree-based hierarchical RCU fanout value"
range 2 64 if 64BIT
range 2 32 if !64BIT
``````

Therefore, without `64BIT`, the maximum value is `32`, but we had `64` set on the `.config`, which would make it inconsistent.

Bonuses

`make olddefconfig` sets every option to their default value without asking interactively. It gets run automatically on `make` to ensure that the `.config` is consistent in case you've modified it manually like we did. See also: https://serverfault.com/questions/116299/automatically-answer-defaults-when-doing-make-oldconfig-on-a-kernel-tree

`make alldefconfig` is like `make olddefconfig`, but it also accepts a config fragment to merge. This target is used by the `merge_config.sh` script: https://stackoverflow.com/a/39440863/895245

And if you want to automate the `.config` modification, that is not too simple: How do you non-interactively turn on features in a Linux kernel .config file?

### cat, grep and cut - translated to python

You need a loop over the lines of a file, you need to learn about string methods

``````with open(filename,'r') as f:
# python can do regexes, but this is for s fixed string only
if "something" in line:
idx1 = line.find('"')
idx2 = line.find('"', idx1+1)
field = line[idx1+1:idx2-1]
print(field)
``````

and you need a method to pass the filename to your python program and while you are at it, maybe also the string to search for...

For the future, try to ask more focused questions if you can,

### Split a string into array in Perl

Having `\$line` as it is now, you can simply split the string based on at least one whitespace separator

``````my @answer = split(' ', \$line); # creates an @answer array
``````

then

``````print("@answer\n");               # print array on one line
``````

or

``````print("\$_\n") for (@answer);      # print each element on one line
``````

I prefer using `()` for `split`, `print` and `for`.

### Is there a WebSocket client implemented for Python?

web2py has comet_messaging.py, which uses Tornado for websockets look at an example here: http://vimeo.com/18399381 and here vimeo . com / 18232653

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

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

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

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

And finally a mini-fiddle to see it directly in action: http://jsfiddle.net/LnU9t/

Edit: Here is a plain jQuery solution which will also clear the input field if an escape keystroke is detected: http://jsfiddle.net/3GLwE/

### How to remove gaps between subplots in matplotlib?

The problem is the use of `aspect='equal'`, which prevents the subplots from stretching to an arbitrary aspect ratio and filling up all the empty space.

Normally, this would work:

``````import matplotlib.pyplot as plt

ax = [plt.subplot(2,2,i+1) for i in range(4)]

for a in ax:
a.set_xticklabels([])
a.set_yticklabels([])

``````

The result is this:

However, with `aspect='equal'`, as in the following code:

``````import matplotlib.pyplot as plt

ax = [plt.subplot(2,2,i+1) for i in range(4)]

for a in ax:
a.set_xticklabels([])
a.set_yticklabels([])
a.set_aspect('equal')

``````

This is what we get:

The difference in this second case is that you've forced the x- and y-axes to have the same number of units/pixel. Since the axes go from 0 to 1 by default (i.e., before you plot anything), using `aspect='equal'` forces each axis to be a square. Since the figure is not a square, pyplot adds in extra spacing between the axes horizontally.

To get around this problem, you can set your figure to have the correct aspect ratio. We're going to use the object-oriented pyplot interface here, which I consider to be superior in general:

``````import matplotlib.pyplot as plt

fig = plt.figure(figsize=(8,8)) # Notice the equal aspect ratio
ax = [fig.add_subplot(2,2,i+1) for i in range(4)]

for a in ax:
a.set_xticklabels([])
a.set_yticklabels([])
a.set_aspect('equal')

``````

Here's the result:

### CSS background-image - What is the correct usage?

1) putting quotes is a good habit

2) it can be relative path for example:

``````background-image: url('images/slides/background.jpg');
``````

will look for images folder in the folder from which css is loaded. So if images are in another folder or out of the CSS folder tree you should use absolute path or relative to the root path (starting with /)

3) you should use complete declaration for background-image to make it behave consistently across standards compliant browsers like:

``````background:blue url('/images/clouds.jpg') no-repeat scroll left center;
``````

### Apply formula to the entire column

You may fill the column by double-clicking on the bottom right hand corner of the cell which you want to copy from (the point on the box that you would otherwise drag) and it will be applied to whole column.

NB: This doesn't work if you have the filter applied, nor if there is already something already in the cells below.

### Paste in insert mode?

While in insert mode, you can use `Ctrl-R {register}`, where register can be:

• `+` for the clipboard,
• `*` for the X clipboard (last selected text in X),
• `"` for the unnamed register (last delete or yank in Vim),
• or a number of others (see `:h registers`).

`Ctrl-R {register}` inserts the text as if it were typed.

`Ctrl-R Ctrl-O {register}` inserts the text with the original indentation.

`Ctrl-R Ctrl-P {register}` inserts the text and auto-indents it.

`Ctrl-O` can be used to run any normal mode command before returning to insert mode, so
`Ctrl-O "+p` can also be used, for example.

For more information, view the documentation with `:h i_ctrl-r`

### Understanding implicit in Scala

I had the exact same question as you had and I think I should share how I started to understand it by a few really simple examples (note that it only covers the common use cases).

There are two common use cases in Scala using `implicit`.

• Using it on a variable
• Using it on a function

Examples are as follows

Using it on a variable. As you can see, if the `implicit` keyword is used in the last parameter list, then the closest variable will be used.

``````// Here I define a class and initiated an instance of this class
case class Person(val name: String)
val charles: Person = Person("Charles")

// Here I define a function
def greeting(words: String)(implicit person: Person) = person match {
case Person(name: String) if name != "" => s"\$name, \$words"
case _ => "\$words"
}

greeting("Good morning") // Charles, Good moring

val charles: Person = Person("")
greeting("Good morning") // Good moring
``````

Using it on a function. As you can see, if the `implicit` is used on the function, then the closest type conversion method will be used.

``````val num = 10 // num: Int (of course)

// Here I define a implicit function
implicit def intToString(num: Int) = s"\$num -- I am a String now!"

val num = 10 // num: Int (of course). Nothing happens yet.. Compiler believes you want 10 to be an Int

// Util...
val num: String = 10 // Compiler trust you first, and it thinks you have `implicitly` told it that you had a way to covert the type from Int to String, which the function `intToString` can do!
// So num is now actually "10 -- I am a String now!"
// console will print this -> val num: String = 10 -- I am a String now!
``````

Hope this can help.

### How are zlib, gzip and zip related? What do they have in common and how are they different?

ZIP is a file format used for storing an arbitrary number of files and folders together with lossless compression. It makes no strict assumptions about the compression methods used, but is most frequently used with DEFLATE.

Gzip is both a compression algorithm based on DEFLATE but less encumbered with potential patents et al, and a file format for storing a single compressed file. It supports compressing an arbitrary number of files and folders when combined with tar. The resulting file has an extension of `.tgz` or `.tar.gz` and is commonly called a tarball.

zlib is a library of functions encapsulating DEFLATE in its most common LZ77 incarnation.

### JUNIT testing void methods

You can learn something called "mocking". You can use this, for example, to check if: - a function was called - a function was called x times - a function was called at least x times - a function was called with a specific set of parameters. In your case, for example, you can use mocking to check that method3 was called once with whatever you pass as arg1 and arg2.

### JRE 1.7 - java version - returns: java/lang/NoClassDefFoundError: java/lang/Object

In window 10 there is already a path present in env as `C:\>ProgramData\Oracle\Java\javapath` that holds symlinks to the executables.

When I install a new version and remove that from my environment variable, my all project start showing it.

I am using eclipse oxygen in window 10

To resolve it:-

1. I just remove path `C:\>ProgramData\Oracle\Java\javapath` from environment variable and added new env as JAVA_HOME and %JAVA_HOME%/bin in path

2. I reinstall the jdk with admin privileges (delete the previous JRE folder)

3. Open your eclipse project > right click > Goto Proprieties> In Libraries > Now remove JRE System Library > Click on Add Library > select "JRE System Library" > Click on Next > Select "Workspace default JRE(jre1.8.x_xxx)" > finish

### Mongoose: Get full list of users

Same can be done with async await and arrow function

``````server.get('/usersList', async (req, res) => {

const users = await User.find({});

const userMap = {};
users.forEach((user) => {
userMap[user._id] = user;
});

res.send(userMap);

});
``````

### The matching wildcard is strict, but no declaration can be found for element 'tx:annotation-driven'

I'm learning from udemy. I followed every step that my instructor show me to do. In spring mvc crud section while setting up the devlopment environment i had the same error for:

``````<mvc:annotation-driven/> and <tx:annotation-driven transaction-manager="myTransactionManager" />
``````

then i just replaced

``````    http://www.springframework.org/schema/mvc/spring-mvc.xsd
``````

with

``````    http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
``````

and

``````    http://www.springframework.org/schema/tx/spring-tx.xsd
``````

with

``````    http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
``````

actually i visited these two sites http://www.springframework.org/schema/mvc/ and http://www.springframework.org/schema/tx/ and just added the latest version of spring-mvc and spring-tx i.e, spring-mvc-4.2.xsd and spring-tx-4.2.xsd

So, i suggest to try this. Hope this helps. Thank you.

### Curl not recognized as an internal or external command, operable program or batch file

I was looking for the download process of Curl and every where they said copy curl.exe file in System32 but they haven't provided the direct link but after digging little more I Got it. so here it is enjoy, find curl.exe easily in bin folder just

unzip it and then go to bin folder there you get exe file

### Git diff says subproject is dirty

Originally, there were no config options to make "`git diff --ignore-submodules`" and "`git status --ignore-submodules`" the global default (but see also Setting git default flags on commands). An alternative is to set a default `ignore` config option on each individual submodule you want to ignore (for both `git diff` and `git status`), either in the `.git/config` file (local only) or `.gitmodules` (will be versioned by git). For example:

``````[submodule "foobar"]
url = [email protected]:foo/bar.git
ignore = untracked
``````

`ignore = untracked` to ignore just untracked files, `ignore = dirty` to also ignore modified files, and `ignore = all` to ignore also commits. There's apparently no way to wildcard it for all submodules.

### Does JavaScript guarantee object property order?

From the JSON standard:

An object is an unordered collection of zero or more name/value pairs, where a name is a string and a value is a string, number, boolean, null, object, or array.

(emphasis mine).

So, no you can't guarantee the order.

### Eclipse projects not showing up after placing project files in workspace/projects

I have tried many of the option suggested but at last importing project in new workspace solved my problem.

I think there is some problem in metadata files in old workspace.

### Trying to detect browser close event

Following script will give message on Chrome and IE:

``````<script>

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

Chrome

IE

on Firefox you will get generic message

Mechanism is synchronous so no server calls to delay will work, you still can prepare a mechanism like modal window that is shown if user decides to stay on page, but no way to prevent him from leaving.

Response to question in comment

F5 will fire event again, so will Atl+F4.

### Displaying Image in Java

Running your code shows an image for me, after adjusting the path. Can you verify that your image path is correct, try absolute path for instance?

### FCM getting MismatchSenderId

I wasted days on this.

In my case, I followed this blog to use Postman and get the mismatchsenderid error. Previously, I was getting `messaging/mismatched-credential`, and people reported that their client app used multiple projects.

However, for me, I have one-to-one, a web app and a project. BUT, I host all apps via `ng serve` on default port 4200. So regardless of what project / app pair I was developing on, I would always get the same token from my client web app using `AngularFireMessaging.requestToken` - this token was always the token created on my first ever run of a firebase app in development.

As a work around, I start different apps / projects on different ports and get proper tokens for respective projects.

### Private vs Protected - Visibility Good-Practice Concern

I read an article a while ago that talked about locking down every class as much as possible. Make everything final and private unless you have an immediate need to expose some data or functionality to the outside world. It's always easy to expand the scope to be more permissible later on, but not the other way around. First consider making as many things as possible `final` which will make choosing between `private` and `protected` much easier.

1. Make all classes final unless you need to subclass them right away.
2. Make all methods final unless you need to subclass and override them right away.
3. Make all method parameters final unless you need to change them within the body of the method, which is kinda awkward most of the times anyways.

Now if you're left with a final class, then make everything private unless something is absolutely needed by the world - make that public.

If you're left with a class that does have subclass(es), then carefully examine every property and method. First consider if you even want to expose that property/method to subclasses. If you do, then consider whether a subclass can wreak havoc on your object if it messed up the property value or method implementation in the process of overriding. If it's possible, and you want to protect your class' property/method even from subclasses (sounds ironic, I know), then make it private. Otherwise make it protected.

Disclaimer: I don't program much in Java :)

### Write objects into file with Node.js

If you're geting `[object object]` then use `JSON.stringify`

`fs.writeFile('./data.json', JSON.stringify(obj) , 'utf-8');`

It worked for me.

### Pretty-print an entire Pandas Series / DataFrame

#### Scripts

Nobody has proposed this simple plain-text solution:

``````from pprint import pprint

pprint(s.to_dict())
``````

which produces results like the following:

``````{'% Diabetes': 0.06365372374283895,
'% Obesity': 0.06365372374283895,
'% Bachelors': 0.0,
'% Poverty': 0.09548058561425843,
'% Driving Deaths': 1.1775938892425206,
'% Excessive Drinking': 0.06365372374283895}
``````

#### Jupyter Notebooks

Additionally, when using Jupyter notebooks, this is a great solution.

Note: `pd.Series()` has no `.to_html()` so it must be converted to `pd.DataFrame()`

``````from IPython.display import display, HTML

display(HTML(s.to_frame().to_html()))
``````

which produces results like the following:

### How to force Hibernate to return dates as java.util.Date instead of Timestamp?

I ran into a problem with this as well as my JUnit assertEquals were failing comparing Dates to Hibernate emitted 'java.util.Date' types (which as described in the question are really Timestamps). It turns out that by changing the mapping to 'date' rather than 'java.util.Date' Hibernate generates java.util.Date members. I am using an XML mapping file with Hibernate version 4.1.12.

This version emits 'java.util.Timestamp':

``````<property name="date" column="DAY" type="java.util.Date" unique-key="KONSTRAINT_DATE_IDX" unique="false" not-null="true" />
``````

This version emits 'java.util.Date':

``````<property name="date" column="DAY" type="date" unique-key="KONSTRAINT_DATE_IDX" unique="false" not-null="true" />
``````

Note, however, if Hibernate is used to generate the DDL, then these will generate different SQL types (Date for 'date' and Timestamp for 'java.util.Date').

### Convert textbox text to integer

``````int num = int.Parse(textBox.Text);
``````

try this. It worked for me