# Programs & Examples On #Getdistance

### Function to calculate distance between two coordinates

I have written a similar equation before - tested it and also got 1.6 km.

Your google maps was showing the DRIVING distance.

Your function is calculating as the crow flies (straight line distance).

``````alert(calcCrow(59.3293371,13.4877472,59.3225525,13.4619422).toFixed(1));

//This function takes in latitude and longitude of two location and returns the distance between them as the crow flies (in km)
function calcCrow(lat1, lon1, lat2, lon2)
{
var R = 6371; // km
var dLat = toRad(lat2-lat1);
var dLon = toRad(lon2-lon1);
var lat1 = toRad(lat1);
var lat2 = toRad(lat2);

var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;
return d;
}

// Converts numeric degrees to radians
{
return Value * Math.PI / 180;
}
``````

### Android-java- How to sort a list of objects by a certain value within the object

"Android-java" is here by no means different than "normal java", so yes `Collections.sort()` would be a good approach.

### AngularJS ui router passing data between states without URL

The params object is included in \$stateParams, but won't be part of the url.

1) In the route configuration:

``````\$stateProvider.state('edit_user', {
url: '/users/:user_id/edit',
templateUrl: 'views/editUser.html',
controller: 'editUserCtrl',
params: {
paramOne: { objectProperty: "defaultValueOne" },  //default value
paramTwo: "defaultValueTwo"
}
});
``````

2) In the controller:

``````.controller('editUserCtrl', function (\$stateParams, \$scope) {
\$scope.paramOne = \$stateParams.paramOne;
\$scope.paramTwo = \$stateParams.paramTwo;
});
``````

3A) Changing the State from a controller

``````\$state.go("edit_user", {
user_id: 1,
paramOne: { objectProperty: "test_not_default1" },
paramTwo: "from controller"
});
``````

3B) Changing the State in html

``````<div ui-sref="edit_user({ user_id: 3, paramOne: { objectProperty: 'from_html1' }, paramTwo: 'fromhtml2' })"></div>
``````

Example Plunker

### Taking the record with the max date

If `date` and `col_date` are the same columns you should simply do:

``````SELECT A, MAX(date) FROM t GROUP BY A
``````

Why not use:

``````WITH x AS ( SELECT A, MAX(col_date) m FROM TABLENAME )
SELECT A, date FROM TABLENAME t JOIN x ON x.A = t.A AND x.m = t.col_date
``````

Otherwise:

``````SELECT A, FIRST_VALUE(date) KEEP(dense_rank FIRST ORDER BY col_date DESC)
FROM TABLENAME
GROUP BY A
``````

### When should I use cross apply over inner join?

While most queries which employ CROSS APPLY can be rewritten using an INNER JOIN, CROSS APPLY can yield better execution plan and better performance, since it can limit the set being joined yet before the join occurs.

Stolen from Here

### conversion from string to json object android

Using Kotlin

``````    val data = "{\"ApiInfo\":{\"description\":\"userDetails\",\"status\":\"success\"},\"userDetails\":{\"Name\":\"somename\",\"userName\":\"value\"},\"pendingPushDetails\":[]}\n"

try {
val jsonObject = JSONObject(data)
val infoObj = jsonObject.getJSONObject("ApiInfo")
} catch (e: Exception) {
}
``````

### Can't connect to local MySQL server through socket homebrew

Since I spent quite some time trying to solve this and always came back to this page when looking for this error, I'll leave my solution here hoping that somebody saves the time I've lost. Although in my case I am using mariadb rather than MySql, you might still be able to adapt this solution to your needs.

#### My problem

is the same, but my setup is a bit different (mariadb instead of mysql):

Installed mariadb with homebrew

``````\$ brew install mariadb
``````

Started the daemon

``````\$ brew services start mariadb
``````

Tried to connect and got the above mentioned error

``````\$ mysql -uroot
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)
``````

#### My solution

find out which `my.cnf` files are used by `mysql` (as suggested in this comment):

``````\$ mysql --verbose --help | grep my.cnf
/usr/local/etc/my.cnf ~/.my.cnf
order of preference, my.cnf, \$MYSQL_TCP_PORT,
``````

check where the Unix socket file is running (almost as described here):

``````\$ netstat -ln | grep mariadb
``````

(you might want to `grep mysql` instead of mariadb)

Add the socket file you found to `~/.my.cnf` (create the file if necessary)(assuming `~/.my.cnf` was listed when running the `mysql --verbose ...`-command from above):

``````[client]
``````

``````\$ brew services restart mariadb
``````

After this I could run mysql and got:

``````\$ mysql -uroot
ERROR 1698 (28000): Access denied for user 'root'@'localhost'
``````

So I run the command with superuser privileges instead and after entering my password I got:

``````\$ sudo mysql -uroot
``````

Notes:

1. I'm not quite sure about the groups where you have to add the socket, first I had it [client-server] but then I figured [client] should be enough. So I changed it and it still works.

2. When running `mariadb_config | grep socket` I get: `--socket [/tmp/mysql.sock]` which is a bit confusing since it seems that `/usr/local/mariadb/data/mariadb.sock` is the actual place (at least on my machine)

3. I wonder where I can configure the `/usr/local/mariadb/data/mariadb.sock` to actually be `/tmp/mysql.sock`so I can use the default settings instead of having to edit my `.my.cnf` (but I'm too tired now to figure that out...)

4. At some point I also did things mentioned in other answers before coming up with this.

### CSS image overlay with color and transparency

JSFiddle Demo

HTML:

``````<div class="image-holder">
<img src="http://codemancers.com/img/who-we-are-bg.png" />
</div>
``````

CSS:

``````.image-holder {
display:inline-block;
position: relative;
}
.image-holder:after {
content:'';
top: 0;
left: 0;
z-index: 10;
width: 100%;
height: 100%;
display: block;
position: absolute;
background: blue;
opacity: 0.1;
}
.image-holder:hover:after {
opacity: 0;
}
``````

### Delete newline in Vim

As other answers mentioned, (upper case) `J` and search + replace for `\n` can be used generally to strip newline characters and to concatenate lines.

But in order to get rid of the trailing newline character in the last line, you need to do this in Vim:

``````:set noendofline binary
:w
``````

### Load HTML page dynamically into div with jQuery

I think you are looking for the Jquery Load function. You would just use that function with an onclick function tied to the a tag or a button if you like.

### jQuery.inArray(), how to use it right?

`\$.inArray()` does the EXACT SAME THING as `myarray.indexOf()` and returns the index of the item you are checking the array for the existence of. It's just compatible with earlier versions of IE before IE9. The best choice is probably to use `myarray.includes()` which returns a boolean true/false value. See snippet below for output examples of all 3 methods.

_x000D_
_x000D_
``````// Declare the array and define it's values_x000D_
var myarray = ['Cat', 'Dog', 'Fish'];_x000D_
_x000D_
// Display the return value of each jQuery function _x000D_
// when a radio button is selected_x000D_
_x000D_
// Get the value of the selected radio_x000D_
var selectedItem = \$('input:radio[name=arrayItems]:checked').val();_x000D_
\$('.item').text( selectedItem );_x000D_
_x000D_
// Calculate and display the index of the selected item_x000D_
\$('#indexVal').text( myarray.indexOf(selectedItem) );_x000D_
_x000D_
// Calculate and display the \$.inArray() value for the selected item_x000D_
\$('#inArrVal').text( \$.inArray(selectedItem, myarray) );_x000D_
_x000D_
// Calculate and display the .includes value for the selected item_x000D_
\$('#includeVal').text( myarray.includes(selectedItem) );_x000D_
});``````
_x000D_
``````#results { line-height: 1.8em; }_x000D_
#resultLabels { width: 14em; display: inline-block; margin-left: 10px; float: left; }_x000D_
label { margin-right: 1.5em; }_x000D_
.space { margin-right: 1.5em; }``````
_x000D_
``````<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
Click a radio button to display the output of_x000D_
&nbsp;<code>\$.inArray()</code>_x000D_
&nbsp;vs. <code>myArray.indexOf()</code>_x000D_
&nbsp;vs. <code>myarray.includes()</code>_x000D_
&nbsp;when tested against_x000D_
&nbsp;<code>myarray = ['Cat', 'Dog', 'Fish'];</code><br><br>_x000D_
_x000D_
<label><input type="radio" name="arrayItems" value="Cat"> Cat</label>_x000D_
<label><input type="radio" name="arrayItems" value="Dog"> Dog</label>_x000D_
<label><input type="radio" name="arrayItems" value="Fish"> Fish</label>  _x000D_
<label><input type="radio" name="arrayItems" value="N/A"> ? Not in Array</label>_x000D_
<br><br>_x000D_
_x000D_
<div id="results">_x000D_
<strong>Results:</strong><br>_x000D_
<div id="resultLabels">_x000D_
myarray.indexOf( "<span class="item">item</span>" )<br>_x000D_
\$.inArray( "<span class="item">item</span>", myarray )<br>_x000D_
myarray.includes( "<span class="item">item</span>" )_x000D_
</div>_x000D_
<div id="resultOutputs">_x000D_
<span class="space">=</span><span id="indexVal"></span><br>_x000D_
<span class="space">=</span><span id="inArrVal"></span><br>_x000D_
<span class="space">=</span><span id="includeVal"></span>_x000D_
</div>_x000D_
</div>``````
_x000D_
_x000D_
_x000D_

### Execute raw SQL using Doctrine 2

I found out the answer is probably:

A NativeQuery lets you execute native SQL, mapping the results according to your specifications. Such a specification that describes how an SQL result set is mapped to a Doctrine result is represented by a ResultSetMapping.

Source: Native SQL.

### ExpressJS - throw er Unhandled error event

Simple just check your teminal in Visual Studio Code Because me was running my node app and i hibernate my laptop then next morning i turn my laptop on back to development of software. THen i run the again command nodemon app.js First waas running from night and the second was running my latest command so two command prompts are listening to same ports that's why you are getting this issue. Simple Close one termianl or all terminal then run your node app.js or nodemon app.js

### Difference between core and processor

Intel's picture is helpful, as shown by Tortuga's best answer. Here's a caption for it.

Processor: One semiconductor chip, the CPU (central processing unit) seated in one socket, circa 1950s-2010s. Over time, more functions have been packed onto the CPU chip. Prior to the 1950s releases of single-chip processors, one processor might have spread across multiple chips. In the mid 2010s the system-on-a-chip chips made it slightly more sketchy to equate one processor to one chip, though that's generally what people mean by processor, as in "this computer has an i7 processor" or "this computer system has four processors."

Core: One block of a CPU, executing one instruction at a time. (You'll see people say one instruction per clock cycle, but some CPUs use multiple clock cycles for some instructions.)

### How can I make a button redirect my page to another page?

Just another variation:

``````    <body>
<button name="redirect" onClick="redirect()">

<script type="text/javascript">
function redirect()
{
var url = "http://www.(url).com";
window.location(url);
}
</script>
``````

### How to update an "array of objects" with Firestore?

You can use a transaction (https://firebase.google.com/docs/firestore/manage-data/transactions) to get the array, push onto it and then update the document:

``````    const booking = { some: "data" };
const userRef = this.db.collection("users").doc(userId);

this.db.runTransaction(transaction => {
// This code may get re-run multiple times if there are conflicts.
return transaction.get(userRef).then(doc => {
if (!doc.data().bookings) {
transaction.set({
bookings: [booking]
});
} else {
const bookings = doc.data().bookings;
bookings.push(booking);
transaction.update(userRef, { bookings: bookings });
}
});
}).then(function () {
console.log("Transaction successfully committed!");
}).catch(function (error) {
console.log("Transaction failed: ", error);
});
``````

### PHP header(Location: ...): Force URL change in address bar

As "cfphpflex" suggested you can add `break;` after setting the header. You can also echo something, such as `echo 'test';`.

### mongodb count num of distinct values per field/key

MongoDB has a `distinct` command which returns an array of distinct values for a field; you can check the length of the array for a count.

There is a shell `db.collection.distinct()` helper as well:

``````> db.countries.distinct('country');
[ "Spain", "England", "France", "Australia" ]

> db.countries.distinct('country').length
4
``````

### How do you create an asynchronous method in C#?

One very simple way to make a method asynchronous is to use Task.Yield() method. As MSDN states:

You can use await Task.Yield(); in an asynchronous method to force the method to complete asynchronously.

Insert it at beginning of your method and it will then return immediately to the caller and complete the rest of the method on another thread.

``````private async Task<DateTime> CountToAsync(int num = 1000)
{
for (int i = 0; i < num; i++)
{
Console.WriteLine("#{0}", i);
}
return DateTime.Now;
}
``````

### How can I create keystore from an existing certificate (abc.crt) and abc.key files?

If the keystore is for tomcat then, after creating the keystore with the above answers, you must add a final step to create the "tomcat" alias for the key:

``````keytool -changealias -alias "1" -destalias "tomcat" -keystore keystore-file.jks
``````

You can check the result with:

``````keytool -list -keystore keystore-file.jks -v
``````

# pandas >= 1.1

From pandas 1.1 you have better control over this behavior, NA values are now allowed in the grouper using `dropna=False`:

``````pd.__version__
# '1.1.0.dev0+2004.g8d10bfb6f'

# Example from the docs
df

a    b  c
0  1  2.0  3
1  1  NaN  4
2  2  1.0  3
3  1  2.0  2

# without NA (the default)
df.groupby('b').sum()

a  c
b
1.0  2  3
2.0  2  5
``````
``````# with NA
df.groupby('b', dropna=False).sum()

a  c
b
1.0  2  3
2.0  2  5
NaN  1  4
``````

### Accessing constructor of an anonymous class

If you dont need to pass arguments, then initializer code is enough, but if you need to pass arguments from a contrcutor there is a way to solve most of the cases:

``````Boolean var= new anonymousClass(){
private String myVar; //String for example

@Overriden public Boolean method(int i){
//use myVar and i
}
public String setVar(String var){myVar=var; return this;} //Returns self instane
}.setVar("Hello").method(3);
``````

### How to check if a row exists in MySQL? (i.e. check if an email exists in MySQL)

There are multiple ways to check if a value exists in the database. Let me demonstrate how this can be done properly with PDO and mysqli.

# PDO

PDO is the simpler option. To find out whether a value exists in the database you can use prepared statement and `fetchColumn()`. There is no need to fetch any data so we will only fetch `1` if the value exists.

``````<?php

// Connection code.
\$options = [
\PDO::ATTR_ERRMODE            => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_EMULATE_PREPARES   => false,
];
\$pdo = new \PDO('mysql:host=localhost;port=3306;dbname=test;charset=utf8mb4', 'testuser', 'password', \$options);

// Prepared statement
\$stmt = \$pdo->prepare('SELECT 1 FROM tblUser WHERE email=?');
\$stmt->execute([\$_POST['email']]);
\$exists = \$stmt->fetchColumn(); // either 1 or null

if (\$exists) {
echo 'Email exists in the database.';
} else {
// email doesn't exist yet
}
``````

For more examples see: How to check if email exists in the database?

# MySQLi

As always mysqli is a little more cumbersome and more restricted, but we can follow a similar approach with prepared statement.

``````<?php

// Connection code
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
\$mysqli = new \mysqli('localhost', 'testuser', 'password', 'test');
\$mysqli->set_charset('utf8mb4');

// Prepared statement
\$stmt = \$mysqli->prepare('SELECT 1 FROM tblUser WHERE email=?');
\$stmt->bind_param('s', \$_POST['email']);
\$stmt->execute();
\$exists = (bool) \$stmt->get_result()->fetch_row(); // Get the first row from result and cast to boolean

if (\$exists) {
echo 'Email exists in the database.';
} else {
// email doesn't exist yet
}
``````

Instead of casting the result row(which might not even exist) to boolean, you can also fetch `COUNT(1)` and read the first item from the first row using `fetch_row()[0]`

For more examples see: How to check whether a value exists in a database using mysqli prepared statements

#### Minor remarks

• If someone suggests you to use `mysqli_num_rows()`, don't listen to them. This is a very bad approach and could lead to performance issues if misused.
• Don't use `real_escape_string()`. This is not meant to be used as a protection against SQL injection. If you use prepared statements correctly you don't need to worry about any escaping.
• If you want to check if a row exists in the database before you try to insert a new one, then it is better not to use this approach. It is better to create a unique key in the database and let it throw an exception if a duplicate value exists.

### How to download image from url

Try this it worked for me

Write this in your Controller

``````public class DemoController: Controller

public async Task<FileStreamResult> GetLogoImage(string logoimage)
{
string str = "" ;
var filePath = Server.MapPath("~/App_Data/" + SubfolderName);//If subfolder exist otherwise leave.
// DirectoryInfo dir = new DirectoryInfo(filePath);
string[] filePaths = Directory.GetFiles(@filePath, "*.*");
foreach (var fileTemp in filePaths)
{
str= fileTemp.ToString();
}
return File(new MemoryStream(System.IO.File.ReadAllBytes(str)), System.Web.MimeMapping.GetMimeMapping(str), Path.GetFileName(str));
}
``````

Here is my view

``````<div><a href="/DemoController/GetLogoImage?Type=Logo" target="_blank">Download Logo</a></div>
``````

### Makefile, header dependencies

Martin's solution above works great, but does not handle .o files that reside in subdirectories. Godric points out that the -MT flag takes care of that problem, but it simultaneously prevents the .o file from being written correctly. The following will take care of both of those problems:

``````DEPS := \$(OBJS:.o=.d)

-include \$(DEPS)

%.o: %.c
\$(CC) \$(CFLAGS) -MM -MT \$@ -MF \$(patsubst %.o,%.d,\$@) \$<
\$(CC) \$(CFLAGS) -o \$@ \$<
``````

### Fling gesture detection on grid layout

One of the answers above mentions handling different pixel density but suggests computing the swipe parameters by hand. It is worth noting that you can actually obtain scaled, reasonable values from the system using `ViewConfiguration` class:

``````final ViewConfiguration vc = ViewConfiguration.get(getContext());
final int swipeMinDistance = vc.getScaledPagingTouchSlop();
final int swipeThresholdVelocity = vc.getScaledMinimumFlingVelocity();
final int swipeMaxOffPath = vc.getScaledTouchSlop();
// (there is also vc.getScaledMaximumFlingVelocity() one could check against)
``````

I noticed that using these values causes the "feel" of fling to be more consistent between the application and rest of system.

### Setting selected option in laravel form

You can also try this for limited options:

``````          <select class="form-control required" id="assignedRole">
<option id = "employeeRole" selected ="@if(\$employee->employee_role=='Employee'){'selected'}else{''} @endif">Employee</option>
<option id = "employerRole" selected ="@if(\$employee->employee_role=='Employer'){'selected'}else{''} @endif">Employer</option>
</select>
``````

### How to distinguish between left and right mouse click with jQuery

there is also a way, to do it without JQuery!

check out this:

``````document.addEventListener("mousedown", function(evt) {
switch(evt.buttons) {
case 1: // left mouse
case 2: // right mouse
case 3: // middle mouse <- I didn't tested that, I just got a touchpad
}
});
``````

### UIDevice uniqueIdentifier deprecated - What to do now?

I'm sure Apple have annoyed many people with this change. I develop a bookkeeping app for iOS and have an online service to sync changes made on different devices. The service maintains a database of all devices and the changes that need to be propagated to them. Therefore it's important to know which devices are which. I'm keeping track of devices using the UIDevice uniqueIdentifier and for what it's worth, here are my thoughts.

• Generate a UUID and store in user defaults? No good because this does not persist when the user deletes the app. If they install again later the online service should not create a new device record, that would waste resources on the server and give a list of devices containing the same one two or more times. Users would see more than one "Bob's iPhone" listed if they re-installed the app.

• Generate a UUID and store in the keychain? This was my plan, since it persists even when the app is uninstalled. But when restoring an iTunes backup to a new iOS device, the keychain is transferred if the backup is encrypted. This could lead to two devices containing the same device id if the old and new devices are both in service. These should be listed as two devices in the online service, even if the device name is the same.

• Generate a hash the MAC address and bundle id? This looks like the best solution for what I need. By hashing with the bundle id, the generated device id is not going to enable the device to be tracked across apps and I get a unique ID for the app+device combination.

It's interesting to note that Apple's own documentation refers to validating Mac App Store receipts by computing a hash of the system MAC address plus the bundle id and version. So this seems allowable by policy, whether it passes through app review I don't yet know.

### Difference between mkdir() and mkdirs() in java for java.io.File

`mkdirs()` will create the specified directory path in its entirety where `mkdir()` will only create the bottom most directory, failing if it can't find the parent directory of the directory it is trying to create.

In other words `mkdir()` is like `mkdir` and `mkdirs()` is like `mkdir -p`.

For example, imagine we have an empty `/tmp` directory. The following code

``````new File("/tmp/one/two/three").mkdirs();
``````

would create the following directories:

• `/tmp/one`
• `/tmp/one/two`
• `/tmp/one/two/three`

Where this code:

``````new File("/tmp/one/two/three").mkdir();
``````

would not create any directories - as it wouldn't find `/tmp/one/two` - and would return `false`.

### Command to find information about CPUs on a UNIX machine

The nproc command shows the number of processing units available:
\$ nproc

Sample outputs: 4

lscpu gathers CPU architecture information form /proc/cpuinfon in human-read-able format:
\$ lscpu

Sample outputs:

Architecture: x86_64
CPU op-mode(s): 32-bit, 64-bit
Byte Order: Little Endian
CPU(s): 8
On-line CPU(s) list: 0-7
Thread(s) per core: 1
Core(s) per socket: 4
CPU socket(s): 2
NUMA node(s): 1
Vendor ID: GenuineIntel
CPU family: 6
Model: 15
Stepping: 7
CPU MHz: 1866.669
BogoMIPS: 3732.83
Virtualization: VT-x
L1d cache: 32K
L1i cache: 32K
L2 cache: 4096K
NUMA node0 CPU(s): 0-7

### Repeat a task with a time delay?

I think the new hotness is to use a ScheduledThreadPoolExecutor. Like so:

``````private final ScheduledThreadPoolExecutor executor_ =
this.executor_.scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
update();
}
}, 0L, kPeriod, kTimeUnit);
``````

### Angular 2 ngfor first, last, index loop

Here is how its done in Angular 6

``````<li *ngFor="let user of userObservable ; first as isFirst">
<span *ngIf="isFirst">default</span>
</li>
``````

Note the change from `let first = first` to `first as isFirst`

### Modify XML existing content in C#

Well, If you want to update a node in XML, the `XmlDocument` is fine - you needn't use `XmlTextWriter`.

``````XmlDocument doc = new XmlDocument();
XmlNode root = doc.DocumentElement;
XmlNode myNode = root.SelectSingleNode("descendant::books");
myNode.Value = "blabla";
doc.Save("D:\\build.xml");
``````

### Artificially create a connection timeout error

If you want to use an active connection you can also use http://httpbin.org/delay/#, where # is the time you want their server to wait before sending a response. As long as your timeout is shorter than the delay ... should simulate the effect. I've successfully used it with the python requests package.

You may want to modify your request if you're sending anything sensitive - no idea what happens to the data sent to them.

### convert array into DataFrame in Python

You can add parameter columns or use `dict` with key which is converted to column name:

``````np.random.seed(123)
e = np.random.normal(size=10)
dataframe=pd.DataFrame(e, columns=['a'])
print (dataframe)
a
0 -1.085631
1  0.997345
2  0.282978
3 -1.506295
4 -0.578600
5  1.651437
6 -2.426679
7 -0.428913
8  1.265936
9 -0.866740

e_dataframe=pd.DataFrame({'a':e})
print (e_dataframe)
a
0 -1.085631
1  0.997345
2  0.282978
3 -1.506295
4 -0.578600
5  1.651437
6 -2.426679
7 -0.428913
8  1.265936
9 -0.866740
``````

### cURL POST command line on WINDOWS RESTful service

We can use below Curl command in Windows Command prompt to send the request. Use the Curl command below, replace single quote with double quotes, remove quotes where they are not there in below format and use the `^` symbol.

``````curl http://localhost:7101/module/url ^
-d @D:/request.xml ^
-H "Content-Type: text/xml" ^
-H "SOAPAction: process" ^
-H "Authorization: Basic xyz" ^
-X POST
``````

### How can I initialize a MySQL database with schema in a Docker container?

Below is the Dockerfile I used successfully to install xampp, create a MariaDB with scheme and pre populated with the info used on local server(usrs,pics orders,etc..)

``````FROM ubuntu:14.04

COPY Ecommerce.sql /root

RUN apt-get update \
&& apt-get install wget -yq \
&& apt-get install nano \
&& wget https://www.apachefriends.org/xampp-files/7.1.11/xampp-linux-x64-7.1.11-0-installer.run \
&& mv xampp-linux-x64-7.1.11-0-installer.run /opt/ \
&& cd /opt/ \
&& chmod +x xampp-linux-x64-7.1.11-0-installer.run \
&& printf 'y\n\y\n\r\n\y\n\r\n' | ./xampp-linux-x64-7.1.11-0-installer.run \
&& cd /opt/lampp/bin \
&& /opt/lampp/lampp start \
&& sleep 5s \

&& ./mysql -uroot -e "CREATE DATABASE Ecommerce" \
&& ./mysql -uroot -D Ecommerce < /root/Ecommerce.sql \
&& cd / \
&& /opt/lampp/lampp reload \
&& mkdir opt/lampp/htdocs/Ecommerce

COPY /Ecommerce /opt/lampp/htdocs/Ecommerce

EXPOSE 80
``````

### Error handling in Bash

Use a trap!

``````tempfiles=( )
cleanup() {
rm -f "\${tempfiles[@]}"
}
trap cleanup 0

error() {
local parent_lineno="\$1"
local message="\$2"
local code="\${3:-1}"
if [[ -n "\$message" ]] ; then
echo "Error on or near line \${parent_lineno}: \${message}; exiting with status \${code}"
else
echo "Error on or near line \${parent_lineno}; exiting with status \${code}"
fi
exit "\${code}"
}
trap 'error \${LINENO}' ERR
``````

...then, whenever you create a temporary file:

``````temp_foo="\$(mktemp -t foobar.XXXXXX)"
tempfiles+=( "\$temp_foo" )
``````

and `\$temp_foo` will be deleted on exit, and the current line number will be printed. (`set -e` will likewise give you exit-on-error behavior, though it comes with serious caveats and weakens code's predictability and portability).

You can either let the trap call `error` for you (in which case it uses the default exit code of 1 and no message) or call it yourself and provide explicit values; for instance:

``````error \${LINENO} "the foobar failed" 2
``````

will exit with status 2, and give an explicit message.

### Git fatal: protocol 'https' is not supported

There is something fishy going on. Probably a github bug that is not consistent (A/B testing?)

I am on windows10, using firefox. I have just copied a checkout URL and got an extra character. But only the first time. A second time it wasn't there. I had to look at my history file to see it!

here is my history:

``````git clone --recursive https://github.com/amzeratul/halley-template
git clone --recursive http://github.com/amzeratul/halley-template
git clone --recursive github.com/amzeratul/halley-template
git clone --recursive https://github.com/amzeratul/halley-template
``````

the history command doesn't show the extra char. Just like it wasn't rendered when i was copy-pasting it into the terminal. You can see how i tried to remove the 's' and then the entire protocol? I was only triggered to investigate further when the backspace key moved one less character than i was expecting!

I saved my shell history file onto a machine with an hex editor and:

``````00000000  xx xx xx xx xx xx xx 0a  67 69 74 20 63 6c 6f 6e  |xxxxxxx.git clon|
00000010  65 20 2d 2d 72 65 63 75  72 73 69 76 65 20 c2 96  |e --recursive ..|
00000020  68 74 74 70 73 3a 2f 2f  67 69 74 68 75 62 2e 63  |https://github.c|
00000030  6f 6d 2f 61 6d 7a 65 72  61 74 75 6c 2f 68 61 6c  |om/amzeratul/hal|
00000040  6c 65 79 2d 74 65 6d 70  6c 61 74 65 0a 67 69 74  |ley-template.git|
00000050  20 2d 2d 68 65 6c 70 0a  67 69 74 20 75 70 64 61  | --help.git upda|
00000060  74 65 2d 67 69 74 2d 66  6f 72 2d 77 69 6e 64 6f  |te-git-for-windo|
00000070  77 73 0a 67 69 74 20 63  6c 6f 6e 65 20 2d 2d 72  |ws.git clone --r|
00000080  65 63 75 72 73 69 76 65  20 c2 96 68 74 74 70 73  |ecursive ..https|
00000090  3a 2f 2f 67 69 74 68 75  62 2e 63 6f 6d 2f 61 6d  |://github.com/am|
000000a0  7a 65 72 61 74 75 6c 2f  68 61 6c 6c 65 79 2d 74  |zeratul/halley-t|
000000b0  65 6d 70 6c 61 74 65 0a  63 75 72 6c 20 2d 2d 76  |emplate.curl --v|
000000c0  65 72 73 69 6f 6e 0a 63  64 20 63 6f 64 65 0a 67  |ersion.cd code.g|
000000d0  69 74 20 63 6c 6f 6e 65  20 2d 2d 72 65 63 75 72  |it clone --recur|
000000e0  73 69 76 65 20 c2 96 68  74 74 70 73 3a 2f 2f 67  |sive ..https://g|
000000f0  69 74 68 75 62 2e 63 6f  6d 2f 61 6d 7a 65 72 61  |ithub.com/amzera|
00000100  74 75 6c 2f 68 61 6c 6c  65 79 2d 74 65 6d 70 6c  |tul/halley-templ|
00000110  61 74 65 0a 67 69 74 20  63 6c 6f 6e 65 20 2d 2d  |ate.git clone --|
00000120  72 65 63 75 72 73 69 76  65 20 c2 96 68 74 74 70  |recursive ..http|
00000130  3a 2f 2f 67 69 74 68 75  62 2e 63 6f 6d 2f 61 6d  |://github.com/am|
00000140  7a 65 72 61 74 75 6c 2f  68 61 6c 6c 65 79 2d 74  |zeratul/halley-t|
00000150  65 6d 70 6c 61 74 65 0a  67 69 74 20 63 6c 6f 6e  |emplate.git clon|
00000160  65 20 2d 2d 72 65 63 75  72 73 69 76 65 20 67 69  |e --recursive gi|
00000170  74 68 75 62 2e 63 6f 6d  2f 61 6d 7a 65 72 61 74  |thub.com/amzerat|
00000180  75 6c 2f 68 61 6c 6c 65  79 2d 74 65 6d 70 6c 61  |ul/halley-templa|
00000190  74 65 0a 67 69 74 20 63  6c 6f 6e 65 20 2d 2d 72  |te.git clone --r|
000001a0  65 63 75 72 73 69 76 65  20 68 74 74 70 73 3a 2f  |ecursive https:/|
000001b0  2f 67 69 74 68 75 62 2e  63 6f 6d 2f 61 6d 7a 65  |/github.com/amze|
000001c0  72 61 74 75 6c 2f 68 61  6c 6c 65 79 2d 74 65 6d  |ratul/halley-tem|
000001d0  70 6c 61 74 65 0a                                 |plate.|
000001d6
``````

There i a `c2 96` char inserted before the url. No idea what that is. Is it not extended ASCII (where it would be `Â–`) and it was hidden from almost every place i pasted while it was on the clipboard. The closest i've found with this hex value would be https://www.fileformat.info/info/unicode/char/c298/index.htm but i didn't see the utf prefix anywhere (again, might have been lost)

This all might be misleading as I lost the page/clipboard and am working exclusively from the saved shell history file, which might very well be missing data from the original bug/malicious injection.

### PHP DOMDocument loadHTML not encoding UTF-8 correctly

Make sure the real source file is saved as UTF-8 (You may even want to try the non-recommended BOM Chars with UTF-8 to make sure).

Also in case of HTML, make sure you have declared the correct encoding using `meta` tags:

``````<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
``````

If it's a CMS (as you've tagged your question with Joomla) you may need to configure appropriate settings for the encoding.

### How to set a ripple effect on textview or imageview on Android?

http://wiki.workassis.com/category/android/android-xml/

``````<TextView
.
.
android:background="?attr/selectableItemBackgroundBorderless"
android:clickable="true"
/>

<ImageView
.
.
.
android:background="?attr/selectableItemBackgroundBorderless"
android:clickable="true"
/>
``````

### Recursive Fibonacci

Why not use iterative algorithm?

``````int fib(int n)
{
int a = 1, b = 1;
for (int i = 3; i <= n; i++) {
int c = a + b;
a = b;
b = c;
}
return b;
}
``````

### How to read Data from Excel sheet in selenium webdriver

``````package com.test.utitlity;

import java.io.IOException;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class readExcel extends globalVariables {

/**
* @param args
* @throws IOException
*/
public static void readExcel(int rowcounter) throws IOException{

XSSFWorkbook srcBook = new XSSFWorkbook("./prop.xlsx");
XSSFSheet sourceSheet = srcBook.getSheetAt(0);
int rownum=rowcounter;
XSSFRow sourceRow = sourceSheet.getRow(rownum);
XSSFCell cell1=sourceRow.getCell(0);
XSSFCell cell2=sourceRow.getCell(1);
XSSFCell cell3=sourceRow.getCell(2);
System.out.println(cell1);
System.out.println(cell2);
System.out.println(cell3);

}

}
``````

### Is there a combination of "LIKE" and "IN" in SQL?

I was also wondering for something like that. I just tested using a combination of `SUBSTRING` and `IN` and it is an effective solution for this kind of problem. Try the below query :

``````Select * from TB_YOUR T1 Where SUBSTRING(T1.Something, 1,3) IN ('bla', 'foo', 'batz')
``````

### Serializing enums with Jackson

Use @JsonCreator annotation, create method getType(), is serialize with toString or object working

``````{"ATIVO"}
``````

or

``````{"type": "ATIVO", "descricao": "Ativo"}
``````

...

``````import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.JsonNodeType;

@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public enum SituacaoUsuario {

ATIVO("Ativo"),
PENDENTE_VALIDACAO("Pendente de Validação"),
INATIVO("Inativo"),
/**
* Usuarios cadastrados pelos clientes que não possuem acesso a aplicacao,
* caso venham a se cadastrar este status deve ser alterado
*/

private SituacaoUsuario(String descricao) {
this.descricao = descricao;
}

private String descricao;

public String getDescricao() {
return descricao;
}

// TODO - Adicionar metodos dinamicamente
public String getType() {
return this.toString();
}

public String getPropertieKey() {
StringBuilder sb = new StringBuilder("enum.");
sb.append(this.getClass().getName()).append(".");
sb.append(toString());
return sb.toString().toLowerCase();
}

@JsonCreator
public static SituacaoUsuario fromObject(JsonNode node) {
String type = null;
if (node.getNodeType().equals(JsonNodeType.STRING)) {
type = node.asText();
} else {
if (!node.has("type")) {
throw new IllegalArgumentException();
}
type = node.get("type").asText();
}
return valueOf(type);
}

}
``````

### What does request.getParameter return?

Both `if (one.length() > 0) {}` and `if (!"".equals(one)) {}` will check against an empty foo parameter, and an empty parameter is what you'd get if the the form is submitted with no value in the `foo` text field.

If there's any chance you can use the Expression Language to handle the parameter, you could access it with `empty param.foo` in an expression.

``````<c:if test='\${not empty param.foo}'>
</c:if>
``````

### Difference between MEAN.js and MEAN.io

First of all, MEAN is an acronym for MongoDB, Express, Angular and Node.js.

It generically identifies the combined used of these technologies in a "stack". There is no such a thing as "The MEAN framework".

Lior Kesos at Linnovate took advantage of this confusion. He bought the domain MEAN.io and put some code at https://github.com/linnovate/mean

They luckily received a lot of publicity, and theree are more and more articles and video about MEAN. When you Google "mean framework", mean.io is the first in the list.

Unfortunately the code at https://github.com/linnovate/mean seems poorly engineered.

In February I fell in the trap myself. The site mean.io had a catchy design and the Github repo had 1000+ stars. The idea of questioning the quality did not even pass through my mind. I started experimenting with it but it did not take too long to stumble upon things that were not working, and puzzling pieces of code.

The commit history was also pretty concerning. They re-engineered the code and directory structure multiple times, and merging the new changes is too time consuming.

The nice things about both mean.io and mean.js code is that they come with Bootstrap integration. They also come with Facebook, Github, Linkedin etc authentication through PassportJs and an example of a model (Article) on the backend on MongoDB that sync with the frontend model with AngularJS.

According to Linnovate's website:

Linnovate is the leading Open Source company in Israel, with the most experienced team in the country, dedicated to the creation of high-end open source solutions. Linnovate is the only company in Israel which gives an A-Z services for enterprises for building and maintaining their next web project.

From the website it looks like that their core skill set is Drupal (a PHP content management system) and only lately they started using Node.js and AngularJS.

Lately I was reading the Mean.js Blog and things became clearer. My understanding is that the main Javascript developer (Amos Haviv) left Linnovate to work on Mean.js leaving MEAN.io project with people that are novice Node.js developers that are slowing understanding how things are supposed to work.

In the future things may change but for now I would avoid to use mean.io. If you are looking for a boilerplate for a quickstart Mean.js seems a better option than mean.io.

### JQuery create a form and add elements to it programmatically

``````var form = \$("<form/>",
{ action:'/myaction' }
);
form.append(
\$("<input>",
{ type:'text',
placeholder:'Keywords',
name:'keyword',
style:'width:65%' }
)
);

form.append(
\$("<input>",
{ type:'submit',
value:'Search',
style:'width:30%' }
)
);

\$("#someDivId").append(form);
``````

### How to find EOF through fscanf?

If you have integers in your file fscanf returns 1 until integer occurs. For example:

``````FILE *in = fopen("./task.in", "r");
int length = 0;
int counter;
int sequence;

for ( int i = 0; i < 10; i++ ) {
counter = fscanf(in, "%d", &sequence);
if ( counter == 1 ) {
length += 1;
}
}
``````

To find out the end of the file with symbols you can use EOF. For example:

``````char symbol;
FILE *in = fopen("./task.in", "r");

for ( ; fscanf(in, "%c", &symbol) != EOF; ) {
printf("%c", symbol);
}
``````

### Tomcat in Intellij Idea Community Edition

I think maven is not installed properly. check with` mvn --v`

or

Please check maven home path in env variables or you have created this project before the installation of maven

### How to access child's state in React?

Just before I go into detail about how you can access the state of a child component, please make sure to read Markus-ipse's answer regarding a better solution to handle this particular scenario.

If you do indeed wish to access the state of a component's children, you can assign a property called `ref` to each child. There are now two ways to implement references: Using `React.createRef()` and callback refs.

# Using `React.createRef()`

This is currently the recommended way to use references as of React 16.3 (See the docs for more info). If you're using an earlier version then see below regarding callback references.

You'll need to create a new reference in the constructor of your parent component and then assign it to a child via the `ref` attribute.

``````class FormEditor extends React.Component {
constructor(props) {
super(props);
this.FieldEditor1 = React.createRef();
}
render() {
return <FieldEditor ref={this.FieldEditor1} />;
}
}
``````

In order to access this kind of ref, you'll need to use:

``````const currentFieldEditor1 = this.FieldEditor1.current;
``````

This will return an instance of the mounted component so you can then use `currentFieldEditor1.state` to access the state.

Just a quick note to say that if you use these references on a DOM node instead of a component (e.g. `<div ref={this.divRef} />`) then `this.divRef.current` will return the underlying DOM element instead of a component instance.

# Callback Refs

This property takes a callback function that is passed a reference to the attached component. This callback is executed immediately after the component is mounted or unmounted.

For example:

``````<FieldEditor
ref={(fieldEditor1) => {this.fieldEditor1 = fieldEditor1;}
{...props}
/>
``````

In these examples the reference is stored on the parent component. To call this component in your code, you can use:

``````this.fieldEditor1
``````

and then use `this.fieldEditor1.state` to get the state.

One thing to note, make sure your child component has rendered before you try to access it ^_^

As above, if you use these references on a DOM node instead of a component (e.g. `<div ref={(divRef) => {this.myDiv = divRef;}} />`) then `this.divRef` will return the underlying DOM element instead of a component instance.

# Further Information

Make sure you read the "Don't Overuse Refs" section that says that you shouldn't use the child's `state` to "make things happen".

Hope this helps ^_^

Edit: Added `React.createRef()` method for creating refs. Removed ES5 code.

### How to get a Static property with Reflection

Or just look at this...

``````Type type = typeof(MyClass); // MyClass is static class with static properties
foreach (var p in type.GetProperties())
{
var v = p.GetValue(null, null); // static classes cannot be instanced, so use null...
}
``````

### Pyspark replace strings in Spark dataframe column

For Spark 1.5 or later, you can use the functions package:

``````from pyspark.sql.functions import *
``````

Quick explanation:

• The function `withColumn` is called to add (or replace, if the name exists) a column to the data frame.
• The function `regexp_replace` will generate a new column by replacing all substrings that match the pattern.

### 401 Unauthorized: Access is denied due to invalid credentials

I faced similar issue.

The folder was shared and Authenticated Users permission was provided, which solved my issue.

### jQuery Force set src attribute for iframe

``````\$(document).ready(function() {
\$('#abc_frame').attr('src',url);
})
``````

### Extracting date from a string in Python

Using Pygrok, you can define abstracted extensions to the Regular Expression syntax.

The custom patterns can be included in your regex in the format `%{PATTERN_NAME}`.

You can also create a label for that pattern, by separating with a colon: `%s{PATTERN_NAME:matched_string}`. If the pattern matches, the value will be returned as part of the resulting dictionary (e.g. `result.get('matched_string')`)

For example:

``````from pygrok import Grok

input_string = 'monkey 2010-07-10 love banana'
date_pattern = '%{YEAR:year}-%{MONTHNUM:month}-%{MONTHDAY:day}'

grok = Grok(date_pattern)
print(grok.match(input_string))
``````

The resulting value will be a dictionary:

`{'month': '07', 'day': '10', 'year': '2010'}`

If the date_pattern does not exist in the input_string, the return value will be `None`. By contrast, if your pattern does not have any labels, it will return an empty dictionary `{}`

References:

### Why can't DateTime.Parse parse UTC date

To correctly parse the string given in the question without changing it, use the following:

``````using System.Globalization;

string dateString = "Tue, 1 Jan 2008 00:00:00 UTC";
DateTime parsedDate = DateTime.ParseExact(dateString, "ddd, d MMM yyyy hh:mm:ss UTC", CultureInfo.CurrentCulture, DateTimeStyles.AssumeUniversal);
``````

This implementation uses a string to specify the exact format of the date string that is being parsed. The DateTimeStyles parameter is used to specify that the given string is a coordinated universal time string.

### WPF TabItem Header Styling

Try this style instead, it modifies the template itself. In there you can change everything you need to transparent:

``````<Style TargetType="{x:Type TabItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TabItem}">
<Grid>
<Border Name="Border" Margin="0,0,0,0" Background="Transparent"
<ContentPresenter x:Name="ContentSite" VerticalAlignment="Center"
HorizontalAlignment="Center"
RecognizesAccessKey="True">
<ContentPresenter.LayoutTransform>
<RotateTransform Angle="270" />
</ContentPresenter.LayoutTransform>
</ContentPresenter>
</Border>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Panel.ZIndex" Value="100" />
<Setter TargetName="Border" Property="Background" Value="Red" />
<Setter TargetName="Border" Property="BorderThickness" Value="1,1,1,0" />
</Trigger>
<Trigger Property="IsEnabled" Value="False">
<Setter TargetName="Border" Property="Background" Value="DarkRed" />
<Setter TargetName="Border" Property="BorderBrush" Value="Black" />
<Setter Property="Foreground" Value="DarkGray" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
``````

### Handling InterruptedException in Java

To me the key thing about this is: an InterruptedException is not anything going wrong, it is the thread doing what you told it to do. Therefore rethrowing it wrapped in a RuntimeException makes zero sense.

In many cases it makes sense to rethrow an exception wrapped in a RuntimeException when you say, I don't know what went wrong here and I can't do anything to fix it, I just want it to get out of the current processing flow and hit whatever application-wide exception handler I have so it can log it. That's not the case with an InterruptedException, it's just the thread responding to having interrupt() called on it, it's throwing the InterruptedException in order to help cancel the thread's processing in a timely way.

So propagate the InterruptedException, or eat it intelligently (meaning at a place where it will have accomplished what it was meant to do) and reset the interrupt flag. Note that the interrupt flag gets cleared when the InterruptedException gets thrown; the assumption the Jdk library developers make is that catching the exception amounts to handling it, so by default the flag is cleared.

So definitely the first way is better, the second posted example in the question is not useful unless you don't expect the thread to actually get interrupted, and interrupting it amounts to an error.

Here's an answer I wrote describing how interrupts work, with an example. You can see in the example code where it is using the InterruptedException to bail out of a while loop in the Runnable's run method.

### Convert timestamp to string

try this

``````SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
String string  = dateFormat.format(new Date());
System.out.println(string);
``````

you can create any format see this

### How do I disable "missing docstring" warnings at a file-level in Pylint?

Edit file "C:\Users\Your User\AppData\Roaming\Code\User\settings.json" and add these `python.linting.pylintArgs` lines at the end as shown below:

``````{
"team.showWelcomeMessage": false,
"python.dataScience.sendSelectionToInteractiveWindow": true,
"git.enableSmartCommit": true,
"powershell.codeFormatting.useCorrectCasing": true,
"files.autoSave": "onWindowChange",
"python.linting.pylintArgs": [
"--errors-only"
],
}
``````

### How to do multiple conditions for single If statement

As Hogan notes above, use an `AND` instead of `&`. See this tutorial for more info.

### MAVEN_HOME, MVN_HOME or M2_HOME

MAVEN_HOME is used for maven 1 and M2_HOME is used to locate maven 2. Having the two different _HOME variables means it is possible to run both on the same machine. And if you check old mvn.cmd scripts they have something like,

``````@REM ----------------------------------------------------------------------------
@REM Maven2 Start Up Batch script
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@REM M2_HOME - location of maven2's installed home dir
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM     e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
``````

See that `@REM M2_HOME - location of maven2's installed home dir`

Anyway usage of this pattern is now deprecated with maven 3.5 as per the documentation.

Based on problems in using M2_HOME related to different Maven versions installed and to simplify things, the usage of M2_HOME has been removed and is not supported any more MNG-5823, MNG-5836, MNG-5607

So now the mvn.cmd look like,

``````@REM -----------------------------------------------------------------------------
@REM Apache Maven Startup Script
@REM
@REM Environment Variable Prerequisites
@REM
@REM   JAVA_HOME          Must point at your Java Development Kit installation.
@REM   MAVEN_BATCH_ECHO  (Optional) Set to 'on' to enable the echoing of the batch commands.
@REM   MAVEN_BATCH_PAUSE (Optional) set to 'on' to wait for a key stroke before ending.
@REM   MAVEN_OPTS        (Optional) Java runtime options used when Maven is executed.
@REM   MAVEN_SKIP_RC     (Optional) Flag to disable loading of mavenrc files.
@REM -----------------------------------------------------------------------------
``````

So what you need is JAVA_HOME to be set correctly. As per the new installation guide (as of 12/29/2017), Just add the maven bin directory path to the PATH variable. It should do the trick.

ex : `export PATH=/opt/apache-maven-3.5.2/bin:\$PATH`

### How to unmount, unrender or remove a component, from itself in a React/Redux/Typescript notification message

In most cases, it is enough just to hide the element, for example in this way:

``````export default class ErrorBoxComponent extends React.Component {
constructor(props) {
super(props);

this.state = {
isHidden: false
}
}

dismiss() {
this.setState({
isHidden: true
})
}

render() {
if (!this.props.error) {
return null;
}

return (
<div data-alert className={ "alert-box error-box " + (this.state.isHidden ? 'DISPLAY-NONE-CLASS' : '') }>
{ this.props.error }
<a href="#" className="close" onClick={ this.dismiss.bind(this) }>&times;</a>
</div>
);
}
}
``````

Or you may render/rerender/not render via parent component like this

``````export default class ParentComponent extends React.Component {
constructor(props) {
super(props);

this.state = {
isErrorShown: true
}
}

dismiss() {
this.setState({
isErrorShown: false
})
}

showError() {
if (this.state.isErrorShown) {
return <ErrorBox
error={ this.state.error }
dismiss={ this.dismiss.bind(this) }
/>
}

return null;
}

render() {

return (
<div>
{ this.showError() }
</div>
);
}
}

export default class ErrorBoxComponent extends React.Component {
dismiss() {
this.props.dismiss();
}

render() {
if (!this.props.error) {
return null;
}

return (
{ this.props.error }
<a href="#" className="close" onClick={ this.dismiss.bind(this) }>&times;</a>
</div>
);
}
}
``````

Finally, there is a way to remove html node, but i really dont know is it a good idea. Maybe someone who knows React from internal will say something about this.

``````export default class ErrorBoxComponent extends React.Component {
dismiss() {
this.el.remove();
}

render() {
if (!this.props.error) {
return null;
}

return (
<div data-alert className="alert-box error-box" ref={ (el) => { this.el = el} }>
{ this.props.error }
<a href="#" className="close" onClick={ this.dismiss.bind(this) }>&times;</a>
</div>
);
}
}
``````

### commandButton/commandLink/ajax action/listener method not invoked or input value not set/updated

I would mention one more thing that concerns Primefaces's `p:commandButton`!

When you use a `p:commandButton` for the action that needs to be done on the server, you can not use `type="button"` because that is for Push buttons which are used to execute custom javascript without causing an ajax/non-ajax request to the server.

For this purpose, you can dispense the `type` attribute (default value is `"submit"`) or you can explicitly use `type="submit"`.

Hope this will help someone!

### What is the difference between signed and unsigned int

Sometimes we know in advance that the value stored in a given integer variable will always be positive-when it is being used to only count things, for example. In such a case we can declare the variable to be unsigned, as in, `unsigned int num student;`. With such a declaration, the range of permissible integer values (for a 32-bit compiler) will shift from the range -2147483648 to +2147483647 to range 0 to 4294967295. Thus, declaring an integer as unsigned almost doubles the size of the largest possible value that it can otherwise hold.

### How can I update the current line in a C# Windows Console App?

`\r` is used for these scenarios.
`\r` represents a carriage return which means the cursor returns to the start of the line.
That's why Windows uses `\n\r` as its new line marker.
`\n` moves you down a line, and `\r` returns you to the start of the line.

### How to Change Font Size in drawString Java

Because you can't count on a particular font being available, a good approach is to derive a new font from the current font. This gives you the same family, weight, etc. just larger...

``````Font currentFont = g.getFont();
Font newFont = currentFont.deriveFont(currentFont.getSize() * 1.4F);
g.setFont(newFont);
``````

You can also use TextAttribute.

``````Map<TextAttribute, Object> attributes = new HashMap<>();

attributes.put(TextAttribute.FAMILY, currentFont.getFamily());
attributes.put(TextAttribute.WEIGHT, TextAttribute.WEIGHT_SEMIBOLD);
attributes.put(TextAttribute.SIZE, (int) (currentFont.getSize() * 1.4));
myFont = Font.getFont(attributes);

g.setFont(myFont);
``````

The TextAttribute method often gives one even greater flexibility. For example, you can set the weight to semi-bold, as in the example above.

One last suggestion... Because the resolution of monitors can be different and continues to increase with technology, avoid adding a specific amount (such as getSize()+2 or getSize()+4) and consider multiplying instead. This way, your new font is consistently proportional to the "current" font (getSize() * 1.4), and you won't be editing your code when you get one of those nice 4K monitors.

### "The specified Android SDK Build Tools version (26.0.0) is ignored..."

Update to Android Studio 3.0.1 which treats these as warnings. Android 3.0 was treating such warnings as errors and hence causing the gradle sync operation to fail.

### ValueError: unsupported pickle protocol: 3, python2 pickle can not load the file dumped by python 3 pickle?

Pickle uses different `protocols` to convert your data to a binary stream.

• In python 2 there are 3 different protocols (`0`, `1`, `2`) and the default is `0`.

• In python 3 there are 5 different protocols (`0`, `1`, `2`, `3`, `4`) and the default is `3`.

You must specify in python 3 a protocol lower than `3` in order to be able to load the data in python 2. You can specify the `protocol` parameter when invoking `pickle.dump`.

### How to inspect Javascript Objects

Use `console.dir(object)` and the Firebug plugin

### How to see what privileges are granted to schema of another user

Login into the database. then run the below query

select * from dba_role_privs where grantee = 'SCHEMA_NAME';

All the role granted to the schema will be listed.

Thanks Szilagyi Donat for the answer. This one is taken from same and just where clause added.

### Make a div fill the height of the remaining screen space

Instead of using tables in the markup, you could use CSS tables.

#### Markup

``````<body>
<div>hello </div>
<div>there</div>
</body>
``````

#### (Relevant) CSS

``````body
{
display:table;
width:100%;
}
div
{
display:table-row;
}
div+ div
{
height:100%;
}
``````

Some advantages of this method are:

1) Less markup

2) Markup is more semantic than tables, because this is not tabular data.

3) Browser support is very good: IE8+, All modern browsers and mobile devices (caniuse)

Just for completeness, here are the equivalent Html elements to css properties for the The CSS table model

``````table    { display: table }
tr       { display: table-row }
tbody    { display: table-row-group }
tfoot    { display: table-footer-group }
col      { display: table-column }
colgroup { display: table-column-group }
td, th   { display: table-cell }
caption  { display: table-caption }
``````

### How do I set an absolute include path in PHP?

There is nothing in include/require that prohibits you from using absolute an path. so your example

``````include('/includes/header.php');
``````

should work just fine. Assuming the path and file are corect and have the correct permissions set.
(and thereby allow you to include whatever file you like, in- or outside your document root)

This behaviour is however considered to be a possible security risk. Therefore, the system administrator can set the open_basedir directive.

This directive configures where you can include/require your files from and it might just be your problem.
Some control panels (plesk for example) set this directive to be the same as the document root by default.

as for the `'.'` syntax:

```/home/username/public_html <- absolute path
public_html <- relative path
./public_html <- same as the path above
../username/public_html <- another relative path
```

However, I usually use a slightly different option:

``````require_once(__DIR__ . '/Factories/ViewFactory.php');
``````

With this edition, you specify an absolute path, relative to the file that contains the `require_once()` statement.

### Android on-screen keyboard auto popping up

``````<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".Main"
android:label="@string/app_name"
android:windowSoftInputMode="stateHidden"
>
``````

This works for Android 3.0, 3.1, 3.2, 4.0 - Editor Used to Compile (Eclipse 3.7)

Place the 'windowSoftInputMode="stateHidden"' in your application's manifest XML file for EACH activity that you wish for the software keyboard to remain hidden in. This means the keyboard will not come up automatically and the user will have to 'click' on a text field to bring it up. I searched for almost an hour for something that worked so I thought I would share.

### How to make the background image to fit into the whole page without repeating using plain css?

You can either use JavaScript or CSS3.

JavaScript solution: Use an absolute positioned `<img>` tag and resize it on the page load and whenever the page resizes. Be careful of possible bugs when trying to get the page/window size.

CSS3 solution: Use the CSS3 background-size property. You might use either `100% 100%` or `contain` or `cover`, depending on how you want the image to resize. Of course, this only works on modern browsers.

### Could not load file or assembly '' or one of its dependencies

Check the Web.config/App.config file in your project. See if the version numbers are correct.

``````<bindingRedirect oldVersion="X.X.X.X-X.X.X.X" newVersion="X.X.X.X" />
``````

This worked for me.

### MySQL Join Where Not Exists

There are three possible ways to do that.

1. Option

``````SELECT  lt.* FROM    table_left lt
LEFT JOIN
table_right rt
ON      rt.value = lt.value
WHERE   rt.value IS NULL
``````
2. Option

``````SELECT  lt.* FROM    table_left lt
WHERE   lt.value NOT IN
(
SELECT  value
FROM    table_right rt
)
``````
3. Option

``````SELECT  lt.* FROM    table_left lt
WHERE   NOT EXISTS
(
SELECT  NULL
FROM    table_right rt
WHERE   rt.value = lt.value
)
``````

### Can you target an elements parent element using event.target?

``````var _RemoveBtn = document.getElementsByClassName("remove");
for(var i=0 ;  i<_RemoveBtn.length ; i++){
}
function sample(event){
console.log(event.currentTarget.parentNode);
}
``````

### AWS - Disconnected : No supported authentication methods available (server sent :publickey)

in most cases, got no authentication method error when using the wrong username for logging in. But I do find something else if you still struggle with connection issue and you have tried all the options above.

I created couple Linux VM and try to reproduce such connection issue, one thing I found is, when AWS asked you name your key pair, DO NOT user blank space (" ") and dot (".") in key pair name, even AWS actually allow you to do so.

ex. when I named the key pair as "AWS.FREE.LINUX", connection always be refused. When I named as "AWS_FREE_LINUX", everything works fine.

Hope this will help a little bit.

### "NoClassDefFoundError: Could not initialize class" error

You're missing the necessary class definition; typically caused by required JAR not being in classpath.

From J2SE API:

public class NoClassDefFoundError extends LinkageError

Thrown if the Java Virtual Machine or a ClassLoader instance tries to load in the definition of a class (as part of a normal method call or as part of creating a new instance using the new expression) and no definition of the class could be found.

The searched-for class definition existed when the currently executing class was compiled, but the definition can no longer be found.

### How do I include negative decimal numbers in this regular expression?

Some Regular expression examples:

Positive Integers:

``````^\d+\$
``````

Negative Integers:

``````^-\d+\$
``````

Integer:

``````^-?\d+\$
``````

Positive Number:

``````^\d*\.?\d+\$
``````

Negative Number:

``````^-\d*\.?\d+\$
``````

Positive Number or Negative Number:

``````^-?\d*\.{0,1}\d+\$
``````

Phone number:

``````^\+?[\d\s]{3,}\$
``````

Phone with code:

``````^\+?[\d\s]+\(?[\d\s]{10,}\$
``````

Year 1900-2099:

``````^(19|20)[\d]{2,2}\$
``````

Date (dd mm yyyy, d/m/yyyy, etc.):

``````^([1-9]|0[1-9]|[12][0-9]|3[01])\D([1-9]|0[1-9]|1[012])\D(19[0-9][0-9]|20[0-9][0-9])\$
``````

IP v4:

``````^(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]){3}\$
``````

### Java foreach loop: for (Integer i : list) { ... }

Another way, you can use a pass-through object to capture the last value and then do something with it:

``````List<Integer> list = new ArrayList<Integer>();
Integer lastValue = null;
for (Integer i : list) {
// do stuff
lastValue = i;
}
// do stuff with last value
``````

### What is the difference between UTF-8 and ISO-8859-1?

• ASCII: 7 bits. 128 code points.

• ISO-8859-1: 8 bits. 256 code points.

• UTF-8: 8-32 bits (1-4 bytes). 1,112,064 code points.

Both ISO-8859-1 and UTF-8 are backwards compatible with ASCII, but UTF-8 is not backwards compatible with ISO-8859-1:

``````#!/usr/bin/env python3

c = chr(0xa9)
print(c)
print(c.encode('utf-8'))
print(c.encode('iso-8859-1'))
``````

Output:

``````©
b'\xc2\xa9'
b'\xa9'
``````

### How do I connect to a SQL Server 2008 database using JDBC?

If your having trouble connecting, most likely the problem is that you haven't yet enabled the TCP/IP listener on port 1433. A quick "netstat -an" command will tell you if its listening. By default, SQL server doesn't enable this after installation.

Also, you need to set a password on the "sa" account and also ENABLE the "sa" account (if you plan to use that account to connect with).

Obviously, this also means you need to enable "mixed mode authentication" on your MSSQL node.

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

``````import pandas as pd
df = pd.DataFrame([{'Product': 'Coke', 'Prices': [100,123,101,105,99,94,98]},{'Product': 'Pepsi', 'Prices': [101,104,104,101,99,99,99]}])
print(df)
df = df.assign(Prices=df.Prices.str.split(',')).explode('Prices')
print(df)
``````

Try this in pandas >=0.25 version

### When to use RSpec let()?

The difference between using instances variables and `let()` is that `let()` is lazy-evaluated. This means that `let()` is not evaluated until the method that it defines is run for the first time.

The difference between `before` and `let` is that `let()` gives you a nice way of defining a group of variables in a 'cascading' style. By doing this, the spec looks a little better by simplifying the code.

### How to reverse a 'rails generate'

You can revert your

``````rails g/generate controller/model/migration xxx
``````

output by using:

`````` rails d/destroy controller/model/migration xxx
``````

### Read input stream twice

If you are using an implementation of `InputStream`, you can check the result of `InputStream#markSupported()` that tell you whether or not you can use the method `mark()` / `reset()`.

If you can mark the stream when you read, then call `reset()` to go back to begin.

If you can't you'll have to open a stream again.

Another solution would be to convert InputStream to byte array, then iterate over the array as many time as you need. You can find several solutions in this post Convert InputStream to byte array in Java using 3rd party libs or not. Caution, if the read content is too big you might experience some memory troubles.

Finally, if your need is to read image, then use :

``````BufferedImage image = ImageIO.read(new URL("http://www.example.com/images/toto.jpg"));
``````

Using `ImageIO#read(java.net.URL)` also allows you to use cache.

### Constantly print Subprocess output while process is running

Ok i managed to solve it without threads (any suggestions why using threads would be better are appreciated) by using a snippet from this question Intercepting stdout of a subprocess while it is running

``````def execute(command):
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

# Poll process for new output until finished
while True:
if nextline == '' and process.poll() is not None:
break
sys.stdout.write(nextline)
sys.stdout.flush()

output = process.communicate()[0]
exitCode = process.returncode

if (exitCode == 0):
return output
else:
raise ProcessException(command, exitCode, output)
``````

### How to change Elasticsearch max memory size

If you use windows server, you can change Environment Variable, restart server to apply new Environment Value and start Elastic Service. More detail in Install Elastic in Windows Server

### dropping infinite values from dataframes in pandas?

The above solution will modify the `inf`s that are not in the target columns. To remedy that,

``````lst = [np.inf, -np.inf]
to_replace = {v: lst for v in ['col1', 'col2']}
df.replace(to_replace, np.nan)
``````

### How to convert list data into json in java

``````public static List<Product> getCartList() {

JSONObject responseDetailsJson = new JSONObject();
JSONArray jsonArray = new JSONArray();

List<Product> cartList = new Vector<Product>(cartMap.keySet().size());
for(Product p : cartMap.keySet()) {
JSONObject formDetailsJson = new JSONObject();
formDetailsJson.put("id", "1");
formDetailsJson.put("name", "name1");
}
responseDetailsJson.put("forms", jsonArray);//Here you can see the data in json format

return cartList;

}
``````

you can get the data in the following form

``````{
"forms": [
{ "id": "1", "name": "name1" },
{ "id": "2", "name": "name2" }
]
}
``````

### How to improve a case statement that uses two columns

Just change your syntax ever so slightly:

``````CASE WHEN STATE = 2 AND RetailerProcessType = 1 THEN '"AUTHORISED"'
WHEN STATE = 1 AND RetailerProcessType = 2 THEN '"PENDING"'
WHEN STATE = 2 AND RetailerProcessType = 2 THEN '"AUTHORISED"'
ELSE '"DECLINED"'
END
``````

If you don't put the field expression before the `CASE` statement, you can put pretty much any fields and comparisons in there that you want. It's a more flexible method but has slightly more verbose syntax.

### How to get a list of all valid IP addresses in a local network?

Install nmap,

``````sudo apt-get install nmap
``````

then

``````nmap -sP 192.168.1.*
``````

or more commonly

``````nmap -sn 192.168.1.0/24
``````

will scan the entire .1 to .254 range

This does a simple ping scan in the entire subnet to see which hosts are online.

### Ansible: Store command's stdout in new variable?

There's no need to set a fact.

``````    - shell: cat "hello"
register: cat_contents

- shell: echo "I cat hello"
when: cat_contents.stdout == "hello"
``````

### Deserializing a JSON into a JavaScript object

I think this should help:

Also documentations also prove that you can use require() for json files: https://www.bennadel.com/blog/2908-you-can-use-require-to-load-json-javascript-object-notation-files-in-node-js.htm

``````var jsonfile = require("./path/to/jsonfile.json");
//other things.
``````

### What is 0x10 in decimal?

The simple version is 0x is a prefix denoting a hexadecimal number, source.

So the value you're computing is after the prefix, in this case 10.

But that is not the number 10. The most significant bit `1` denotes the hex value while `0` denotes the units.

So the simple math you would do is

0x10

``````1 * 16 + 0 = 16
``````

Note - you use 16 because hex is base 16.

Another example:

0xF7

``````15 * 16 + 7 = 247
``````

You can get a list of values by searching for a hex table. For instance in this chart notice F corresponds with 15.

### Highlight label if checkbox is checked

You can't do this with CSS alone. Using jQuery you can do

HTML

``````<label id="lab">Checkbox</label>
<input id="check" type="checkbox" />
``````

CSS

``````.highlight{
background:yellow;
}
``````

jQuery

``````\$('#check').click(function(){
\$('#lab').toggleClass('highlight')
})
``````

This will work in all browsers

### React Native: JAVA_HOME is not set and no 'java' command could be found in your PATH

I fixed this issue by installing `jre`, I have `jdk` already installed but `jre` was not installed.

### How to interpret "loss" and "accuracy" for a machine learning model

Just to clarify the Training/Validation/Test data sets: The training set is used to perform the initial training of the model, initializing the weights of the neural network.

The validation set is used after the neural network has been trained. It is used for tuning the network's hyperparameters, and comparing how changes to them affect the predictive accuracy of the model. Whereas the training set can be thought of as being used to build the neural network's gate weights, the validation set allows fine tuning of the parameters or architecture of the neural network model. It's useful as it allows repeatable comparison of these different parameters/architectures against the same data and networks weights, to observe how parameter/architecture changes affect the predictive power of the network.

Then the test set is used only to test the predictive accuracy of the trained neural network on previously unseen data, after training and parameter/architecture selection with the training and validation data sets.

### What does 'const static' mean in C and C++?

That line of code can actually appear in several different contexts and alghough it behaves approximately the same, there are small differences.

# Namespace Scope

``````// foo.h
static const int i = 0;
``````

'`i`' will be visible in every translation unit that includes the header. However, unless you actually use the address of the object (for example. '`&i`'), I'm pretty sure that the compiler will treat '`i`' simply as a type safe `0`. Where two more more translation units take the '`&i`' then the address will be different for each translation unit.

``````// foo.cc
static const int i = 0;
``````

'`i`' has internal linkage, and so cannot be referred to from outside of this translation unit. However, again unless you use its address it will most likely be treated as a type-safe `0`.

One thing worth pointing out, is that the following declaration:

``````const int i1 = 0;
``````

is exactly the same as `static const int i = 0`. A variable in a namespace declared with `const` and not explicitly declared with `extern` is implicitly static. If you think about this, it was the intention of the C++ committee to allow `const` variables to be declared in header files without always needing the `static` keyword to avoid breaking the ODR.

# Class Scope

``````class A {
public:
static const int i = 0;
};
``````

In the above example, the standard explicitly specifies that '`i`' does not need to be defined if its address is not required. In other words if you only use '`i`' as a type-safe 0 then the compiler will not define it. One difference between the class and namespace versions is that the address of '`i`' (if used in two ore more translation units) will be the same for the class member. Where the address is used, you must have a definition for it:

``````// a.h
class A {
public:
static const int i = 0;
};

// a.cc
#include "a.h"
const int A::i;            // Definition so that we can take the address
``````

### str_replace with array

Alternatively to the answer marked as correct, if you have to replace words instead of chars you can do it with this piece of code :

``````\$query = "INSERT INTO my_table VALUES (?, ?, ?, ?);";
\$values = Array("apple", "oranges", "mangos", "papayas");
foreach (array_fill(0, count(\$values), '?') as \$key => \$wildcard) {
\$query = substr_replace(\$query, '"'.\$values[\$key].'"', strpos(\$query, \$wildcard), strlen(\$wildcard));
}
echo \$query;
``````

### How to disable XDebug

Comment extension in php.ini and restart Apache. Here is a simple script (you can assign shortcut to it)

xdebug-toggle.php

``````define('PATH_TO_PHP_INI', 'c:/xampp/php/php.ini');
define('PATH_TO_HTTPD', 'c:/xampp/apache/bin/httpd.exe');
define('REXP_EXTENSION', '(zend_extension\s*=.*?php_xdebug)');

\$s = file_get_contents(PATH_TO_PHP_INI);
\$replaced = preg_replace('/;' . REXP_EXTENSION . '/', '\$1', \$s);
\$isOn = \$replaced != \$s;
if (!\$isOn) {
\$replaced = preg_replace('/' . REXP_EXTENSION . '/', ';\$1', \$s);
}
echo 'xdebug is ' . (\$isOn ? 'ON' : 'OFF') . " now. Restarting apache...\n\n";
file_put_contents(PATH_TO_PHP_INI, \$replaced);

passthru(PATH_TO_HTTPD . ' -k restart');
``````

### Count number of 1's in binary representation

I came here having a great belief that I know beautiful solution for this problem. Code in C:

``````    short numberOfOnes(unsigned int d) {
short count = 0;

for (; (d != 0); d &= (d - 1))
++count;

return count;
}
``````

But after I've taken a little research on this topic (read other answers:)) I found 5 more efficient algorithms. Love SO!

There is even a CPU instruction designed specifically for this task: `popcnt`. (mentioned in this answer)

Description and benchmarking of many algorithms you can find here.

### Python list of dictionaries search

``````def dsearch(lod, **kw):
return filter(lambda i: all((i[k] == v for (k, v) in kw.items())), lod)

lod=[{'a':33, 'b':'test2', 'c':'a.ing333'},
{'a':22, 'b':'ihaha', 'c':'fbgval'},
{'a':33, 'b':'TEst1', 'c':'s.ing123'},
{'a':22, 'b':'ihaha', 'c':'dfdvbfjkv'}]

list(dsearch(lod, a=22))

[{'a': 22, 'b': 'ihaha', 'c': 'fbgval'},
{'a': 22, 'b': 'ihaha', 'c': 'dfdvbfjkv'}]

list(dsearch(lod, a=22, b='ihaha'))

[{'a': 22, 'b': 'ihaha', 'c': 'fbgval'},
{'a': 22, 'b': 'ihaha', 'c': 'dfdvbfjkv'}]

list(dsearch(lod, a=22, c='fbgval'))

[{'a': 22, 'b': 'ihaha', 'c': 'fbgval'}]
``````

### How to use GOOGLEFINANCE(("CURRENCY:EURAUD")) function

You have to use the equal sign in the formula box

``````=GOOGLEFINANCE("GOOG", "price", DATE(2014,1,1), DATE(2014,12,31), "DAILY")
``````

### Python: "TypeError: __str__ returned non-string" but still prints to output?

The problem that you are facing is : TypeError : str returned non-string (type NoneType)

Here you have to understand the str function's working: the str fucntion,although is mostly used to print values but actually is designed to return a string,not to print one. In your class str function is calling the print directly while it is returning nothing ,that explains your error output.Since our formatted string is built, and since our function returns nothing, the None value is used. This was the explaination for your error

You can solve this problem by using the return in str function like: *simply returnig the string value instead of printing it

`````` class Summary(models.Model):
book = models.ForeignKey(Book,on_delete = models.CASCADE)
summary = models.TextField(max_length=600)

def __str__(self):
return self.summary
``````

but if the value you are returning in not of string type then you can do like this to return string value from your str function

*typeconverting the value to string that your str function returns

``````class Summary(models.Model):
book = models.ForeignKey(Book,on_delete = models.CASCADE)
summary = models.TextField(max_length=600)

def __str__(self):
return str(self.summary)
`
``````

### Get index of a key/value pair in a C# dictionary based on the value

In your comment to max's answer, you say that what you really wanted to get is the key in, and not the index of, the KeyValuePair that contains a certain value. You could edit your question to make it more clear.

It is worth pointing out (EricM has touched upon this in his answer) that a value might appear more than once in the dictionary, in which case one would have to think which key he would like to get: e.g. the first that comes up, the last, all of them?

If you are sure that each key has a unique value, you could have another dictionary, with the values from the first acting as keys and the previous keys acting as values. Otherwise, this second dictionary idea (suggested by Jon Skeet) will not work, as you would again have to think which of all the possible keys to use as value in the new dictionary.

If you were asking about the index, though, EricM's answer would be OK. Then you could get the KeyValuePair in question by using:

``````yourDictionary.ElementAt(theIndexYouFound);
``````

provided that you do not add/remove things in `yourDictionary`.

PS: I know it's been almost 7 years now, but what the heck. I thought it best to formulate my answer as addressing the OP, but of course by now one can say it is an answer for just about anyone else but the OP. Fully aware of that, thank you.

### JQuery: 'Uncaught TypeError: Illegal invocation' at ajax request - several elements

I've read in JQuery docs that data can be an array (key value pairs). I get the error if I put:

This is object not an array:

``````var data = {
'mode': 'filter_city',
'id_A': e[e.selectedIndex]
};
``````

You probably want:

``````var data = [{
'mode': 'filter_city',
'id_A': e[e.selectedIndex]
}];
``````

### Deserialize JSON into C# dynamic object?

Simple "string JSON data" to object without any third-party DLL file:

``````WebClient client = new WebClient();

JavaScriptSerializer serializer = new JavaScriptSerializer();
dynamic item = serializer.Deserialize<object>(getString);
string name = item["name"];

//note: JavaScriptSerializer in this namespaces
//System.Web.Script.Serialization.JavaScriptSerializer
``````

Note: You can also using your custom object.

``````Personel item = serializer.Deserialize<Personel>(getString);
``````

# Important

My answer below shows how to embed images using data URIs. This is useful for the web, but will not work reliably for most email clients. For email purposes be sure to read Shadow2531's answer.

Base-64 data is legal in an `img` tag and I believe your question is how to properly insert such an image tag.

You can use an online tool or a few lines of code to generate the base 64 string.

The syntax to source the image from inline data is:

``````<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA
AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot">
``````

http://en.wikipedia.org/wiki/Data_URI_scheme

### Sending POST parameters with Postman doesn't work, but sending GET parameters does

I was having the same problem. To fix it I added the following headers:

``````Content-Type: application/json
``````

I had to manually add the content type even though I also had the type of "json" in the raw post field parameters.

### Get Selected value from Multi-Value Select Boxes by jquery-select2?

I know its late but I think you can try like this

``````\$("#multipledpdwn").on("select2:select select2:unselect", function (e) {

//this returns all the selected item
var items= \$(this).val();

//Gets the last selected item
var lastSelectedItem = e.params.data.id;

})
``````

Hope it may help some one in future.

### how to declare global variable in SQL Server..?

Starting from `SQL Server 2016` a new way for sharing information in session is introduced via the SESSION_CONTEXT and sp_set_session_context.

You can use them as alternative of `CONTEXT_INFO()` which persist only a binary value limited to 128 bytes. Also, the user can rewrite the value anytime and it's not very good to use it for security checks.

The following issues are resolved using the new utils. You can store the data in more user-friendly format:

``````EXEC sp_set_session_context 'language', 'English';
SELECT SESSION_CONTEXT(N'language');
``````

Also, we can mark it as `read-only`:

``````EXEC sp_set_session_context 'user_id', 4, @read_only = 1;
``````

If you try to modify a `read-only` session context you will get something like this:

Msg 15664, Level 16, State 1, Procedure sp_set_session_context, Line 10 Cannot set key 'user_id' in the session context. The key has been set as read_only for this session.

### AngularJS: How do I manually set input to \$valid in controller?

You cannot directly change a form's validity. If all the descendant inputs are valid, the form is valid, if not, then it is not.

What you should do is to set the validity of the input element. Like so;

``````addItem.capabilities.\$setValidity("youAreFat", false);
``````

Now the input (and so the form) is invalid. You can also see which error causes invalidation.

``````addItem.capabilities.errors.youAreFat == true;
``````

### What is the difference between logical data model and conceptual data model?

Logical Database Model

Logical database modeling is required for compiling business requirements and representing the requirements as a model. It is mainly associated with the gathering of business needs rather than the database design. The information that needs to be gathered is about organizational units, business entities, and business processes.

Once the information is compiled, reports and diagrams are made, including these:

ERD–Entity relationship diagram shows the relationship between different categories of data and shows the different categories of data required for the development of a database. Business process diagram–It shows the activities of individuals within the company. It shows how the data moves within the organization based on which application interface can be designed. Feedback documentation by users.

Logical database models basically determine if all the requirements of the business have been gathered. It is reviewed by developers, management, and finally the end users to see if more information needs to be gathered before physical modeling starts.

Physical Database Model Physical database modeling deals with designing the actual database based on the requirements gathered during logical database modeling. All the information gathered is converted into relational models and business models. During physical modeling, objects are defined at a level called a schema level. A schema is considered a group of objects which are related to each other in a database. Tables and columns are made according to the information provided during logical modeling. Primary keys, unique keys, and foreign keys are defined in order to provide constraints. Indexes and snapshots are defined. Data can be summarized, and users are provided with an alternative perspective once the tables have been created.

Physical database modeling depends upon the software already being used in the organization. It is software specific. Physical modeling includes:

Server model diagram–It includes tables and columns and different relationships that exist within a database. Database design documentation. Feedback documentation of users.

Summary:

1.Logical database modeling is mainly for gathering information about business needs and does not involve designing a database; whereas physical database modeling is mainly required for actual designing of the database. 2.Logical database modeling does not include indexes and constraints; the logical database model for an application can be used across various database software and implementations; whereas physical database modeling is software and hardware specific and has indexes and constraints. 3.Logical database modeling includes; ERD, business process diagrams, and user feedback documentation; whereas physical database modeling includes; server model diagram, database design documentation, and user feedback documentation.

Read more: Difference Between Logical and Physical Database Model | Difference Between | Logical vs Physical Database Model http://www.differencebetween.net/technology/software-technology/difference-between-logical-and-physical-database-model/#ixzz3AxPVhTlg

### Map isn't showing on Google Maps JavaScript API v3 when nested in a div tag

FIXED

Give initial height of div and specify height in percentage in your style;

``````#map {
height: 100%;
}

<div id="map" style="clear:both; height:200px;"></div>
``````

### XPath to select element based on childs child value

Almost there. In your predicate, you want a relative path, so change

``````./book[/author/name = 'John']
``````

to either

``````./book[author/name = 'John']
``````

or

``````./book[./author/name = 'John']
``````

and you will match your element. Your current predicate goes back to the root of the document to look for an `author`.

### Fluid or fixed grid system, in responsive design, based on Twitter Bootstrap

Interesting discussion. I was asking myself this question too. The main difference between fluid and fixed is simply that the fixed layout has a fixed width in terms of the whole layout of the website (viewport). If you have a 960px width viewport each colum has a fixed width which will never change.

The fluid layout behaves different. Imagine you have set the width of your main layout to 100% width. Now each column will only be calculated to it's relative size (i.e. 25%) and streches as the browser will be resized. So based on your layout purpose you can select how your layout behaves.

### Inline style to act as :hover in CSS

I'm afraid it can't be done, the pseudo-class selectors can't be set in-line, you'll have to do it on the page or on a stylesheet.

I should mention that technically you should be able to do it according to the CSS spec, but most browsers don't support it

Edit: I just did a quick test with this:

``````<a href="test.html" style="{color: blue; background: white}
:visited {color: green}
:hover {background: yellow}
:visited:hover {color: purple}">Test</a>
``````

And it doesn't work in IE7, IE8 beta 2, Firefox or Chrome. Can anyone else test in any other browsers?

### Taskkill /f doesn't kill a process

I had the same problem and as many others here have said none of the normal Kill commands worked. My problem file was an executable that was being run from a network share by a user on a Remote Desktop Server. With multiple shared users not an easy thing to restart in during a work day. Even when the user logged off the exe was still listed in Task Manager. I sent to the server where the folder was shared and from Computer Management -> Sessions found the user with the session still open from that RDP server even though he was logged off. Right Click -> Close Session and the file lock was released.

Beats me why I couldn't end the taks. The error message I was originally getting when I try and delete the file was "The action can't be completed because the file is open in System"

Hope this helps someone else.

### Java Package Does Not Exist Error

If you are facing this issue while using Kotlin and have

``````kotlin.incremental=true
kapt.incremental.apt=true
``````

in the gradle.properties, then you need to remove this temporarily to fix the build.

After the successful build, you can again add these properties to speed up the build time while using Kotlin.

### IntelliJ inspection gives "Cannot resolve symbol" but still compiles code

check import Maven projects automatically, fixed my issue. I spent two hours figuring out where I am doing wrong. Finally was able to fix it.

### sql server #region

Another option is

if your purpose is analyse your query, Notepad+ has useful automatic wrapper for Sql.

### How to find the parent element using javascript

Use the change event of the select:

``````\$('#my_select').change(function()
{
\$(this).parents('td').css('background', '#000000');
});
``````

### How to allow http content within an iframe on a https site

add `<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">` in head

### Google Spreadsheet, Count IF contains a string

Try using wildcards directly in the COUNTIF function :

``````=(COUNTIF(A2:A51,"=*iPad*")/COUNTA(A2:A51))*1
``````

### In Python, what happens when you import inside of a function?

The very first time you `import goo` from anywhere (inside or outside a function), `goo.py` (or other importable form) is loaded and `sys.modules['goo']` is set to the module object thus built. Any future import within the same run of the program (again, whether inside or outside a function) just look up `sys.modules['goo']` and bind it to barename `goo` in the appropriate scope. The dict lookup and name binding are very fast operations.

Assuming the very first `import` gets totally amortized over the program's run anyway, having the "appropriate scope" be module-level means each use of `goo.this`, `goo.that`, etc, is two dict lookups -- one for `goo` and one for the attribute name. Having it be "function level" pays one extra local-variable setting per run of the function (even faster than the dictionary lookup part!) but saves one dict lookup (exchanging it for a local-variable lookup, blazingly fast) for each `goo.this` (etc) access, basically halving the time such lookups take.

We're talking about a few nanoseconds one way or another, so it's hardly a worthwhile optimization. The one potentially substantial advantage of having the `import` within a function is when that function may well not be needed at all in a given run of the program, e.g., that function deals with errors, anomalies, and rare situations in general; if that's the case, any run that does not need the functionality will not even perform the import (and that's a saving of microseconds, not just nanoseconds), only runs that do need the functionality will pay the (modest but measurable) price.

It's still an optimization that's only worthwhile in pretty extreme situations, and there are many others I would consider before trying to squeeze out microseconds in this way.

### "Too many values to unpack" Exception

This problem looked familiar so I thought I'd see if I could replicate from the limited amount of information.

A quick search turned up an entry in James Bennett's blog here which mentions that when working with the UserProfile to extend the User model a common mistake in settings.py can cause Django to throw this error.

To quote the blog entry:

The value of the setting is not "appname.models.modelname", it's just "appname.modelname". The reason is that Django is not using this to do a direct import; instead, it's using an internal model-loading function which only wants the name of the app and the name of the model. Trying to do things like "appname.models.modelname" or "projectname.appname.models.modelname" in the AUTH_PROFILE_MODULE setting will cause Django to blow up with the dreaded "too many values to unpack" error, so make sure you've put "appname.modelname", and nothing else, in the value of AUTH_PROFILE_MODULE.

If the OP had copied more of the traceback I would expect to see something like the one below which I was able to duplicate by adding "models" to my AUTH_PROFILE_MODULE setting.

``````TemplateSyntaxError at /

Caught an exception while rendering: too many values to unpack

Original Traceback (most recent call last):
File "/home/brandon/Development/DJANGO_VERSIONS/Django-1.0/django/template/debug.py", line 71, in render_node
result = node.render(context)
File "/home/brandon/Development/DJANGO_VERSIONS/Django-1.0/django/template/debug.py", line 87, in render
output = force_unicode(self.filter_expression.resolve(context))
File "/home/brandon/Development/DJANGO_VERSIONS/Django-1.0/django/template/__init__.py", line 535, in resolve
obj = self.var.resolve(context)
File "/home/brandon/Development/DJANGO_VERSIONS/Django-1.0/django/template/__init__.py", line 676, in resolve
value = self._resolve_lookup(context)
File "/home/brandon/Development/DJANGO_VERSIONS/Django-1.0/django/template/__init__.py", line 711, in _resolve_lookup
current = current()
File "/home/brandon/Development/DJANGO_VERSIONS/Django-1.0/django/contrib/auth/models.py", line 291, in get_profile
app_label, model_name = settings.AUTH_PROFILE_MODULE.split('.')
ValueError: too many values to unpack
``````

This I think is one of the few cases where Django still has a bit of import magic that tends to cause confusion when a small error doesn't throw the expected exception.

You can see at the end of the traceback that I posted how using anything other than the form "appname.modelname" for the AUTH_PROFILE_MODULE would cause the line "app_label, model_name = settings.AUTH_PROFILE_MODULE.split('.')" to throw the "too many values to unpack" error.

I'm 99% sure that this was the original problem encountered here.

### How do you overcome the svn 'out of date' error?

Just do svn up into command line or if you are in windows select the svn update option.

• Once this will done, this allow you to make further action like committing and others.

### jquery change class name

So you want to change it WHEN it's clicked...let me go through the whole process. Let's assume that your "External DOM Object" is an input, like a select:

``````<body>
<div>
<select id="test">
<option>Bob</option>
<option>Sam</option>
<option>Sue</option>
<option>Jen</option>
</select>
</div>

<table id="theTable">
<tr><td id="cellToChange">Bob</td><td>Sam</td></tr>
<tr><td>Sue</td><td>Jen</td></tr>
</table>
</body>
``````

Some very basic CSS:

``````?#theTable td {
border:1px solid #555;
}
.activeCell {
background-color:#F00;
}
``````

And set up a jQuery event:

``````function highlightCell(useVal){
\$("#theTable td").removeClass("activeCell")
}

\$("#test").change(function(e){highlightCell(\$(this).val())});
});
``````

Now, whenever you pick something from the select, it will automatically find a cell with the matching text, allowing you to subvert the whole id-based process. Of course, if you wanted to do it that way, you could easily modify the script to use IDs rather than values by saying

``````.filter("#"+useVal)
``````

and make sure to add the ids appropriately. Hope this helps!

### How to prevent a dialog from closing when a button is clicked

If you are using `material design` I would suggest checking out material-dialogs. It fixed several issues for me related to currently open Android bugs (see 78088), but most importantly for this ticket it has an `autoDismiss` flag that can be set when using the `Builder`.

### Use of Finalize/Dispose method in C#

The recommended IDisposable pattern is here. When programming a class that uses IDisposable, generally you should use two patterns:

When implementing a sealed class that doesn't use unmanaged resources, you simply implement a Dispose method as with normal interface implementations:

``````public sealed class A : IDisposable
{
public void Dispose()
{
// get rid of managed resources, call Dispose on member variables...
}
}
``````

When implementing an unsealed class, do it like this:

``````public class B : IDisposable
{
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}

protected virtual void Dispose(bool disposing)
{
if (disposing)
{
// get rid of managed resources
}
// get rid of unmanaged resources
}

// only if you use unmanaged resources directly in B
//~B()
//{
//    Dispose(false);
//}
}
``````

Notice that I haven't declared a finalizer in `B`; you should only implement a finalizer if you have actual unmanaged resources to dispose. The CLR deals with finalizable objects differently to non-finalizable objects, even if `SuppressFinalize` is called.

So, you shouldn't declare a finalizer unless you have to, but you give inheritors of your class a hook to call your `Dispose` and implement a finalizer themselves if they use unmanaged resources directly:

``````public class C : B
{
private IntPtr m_Handle;

protected override void Dispose(bool disposing)
{
if (disposing)
{
// get rid of managed resources
}
ReleaseHandle(m_Handle);

base.Dispose(disposing);
}

~C() {
Dispose(false);
}
}
``````

If you're not using unmanaged resources directly (`SafeHandle` and friends doesn't count, as they declare their own finalizers), then don't implement a finalizer, as the GC deals with finalizable classes differently, even if you later suppress the finalizer. Also note that, even though `B` doesn't have a finalizer, it still calls `SuppressFinalize` to correctly deal with any subclasses that do implement a finalizer.

When a class implements the IDisposable interface, it means that somewhere there are some unmanaged resources that should be got rid of when you've finished using the class. The actual resources are encapsulated within the classes; you don't need to explicitly delete them. Simply calling `Dispose()` or wrapping the class in a `using(...) {}` will make sure any unmanaged resources are got rid of as necessary.

### How do multiple clients connect simultaneously to one port, say 80, on a server?

Important:

I'm sorry to say that the response from "Borealid" is imprecise and somewhat incorrect - firstly there is no relation to statefulness or statelessness to answer this question, and most importantly the definition of the tuple for a socket is incorrect.

First remember below two rules:

1. Primary key of a socket: A socket is identified by `{SRC-IP, SRC-PORT, DEST-IP, DEST-PORT, PROTOCOL}` not by `{SRC-IP, SRC-PORT, DEST-IP, DEST-PORT}` - Protocol is an important part of a socket's definition.

2. OS Process & Socket mapping: A process can be associated with (can open/can listen to) multiple sockets which might be obvious to many readers.

Example 1: Two clients connecting to same server port means: `socket1 {SRC-A, 100, DEST-X,80, TCP}` and `socket2{SRC-B, 100, DEST-X,80, TCP}`. This means host A connects to server X's port 80 and another host B also connects to same server X to the same port 80. Now, how the server handles these two sockets depends on if the server is single threaded or multiple threaded (I'll explain this later). What is important is that one server can listen to multiple sockets simultaneously.

To answer the original question of the post:

Irrespective of stateful or stateless protocols, two clients can connect to same server port because for each client we can assign a different socket (as client IP will definitely differ). Same client can also have two sockets connecting to same server port - since such sockets differ by `SRC-PORT`. With all fairness, "Borealid" essentially mentioned the same correct answer but the reference to state-less/full was kind of unnecessary/confusing.

To answer the second part of the question on how a server knows which socket to answer. First understand that for a single server process that is listening to same port, there could be more than one sockets (may be from same client or from different clients). Now as long as a server knows which request is associated with which socket, it can always respond to appropriate client using the same socket. Thus a server never needs to open another port in its own node than the original one on which client initially tried to connect. If any server allocates different server-ports after a socket is bound, then in my opinion the server is wasting its resource and it must be needing the client to connect again to the new port assigned.

A bit more for completeness:

Example 2: It's a very interesting question: "can two different processes on a server listen to the same port". If you do not consider protocol as one of parameter defining socket then the answer is no. This is so because we can say that in such case, a single client trying to connect to a server-port will not have any mechanism to mention which of the two listening processes the client intends to connect to. This is the same theme asserted by rule (2). However this is WRONG answer because 'protocol' is also a part of the socket definition. Thus two processes in same node can listen to same port only if they are using different protocol. For example two unrelated clients (say one is using TCP and another is using UDP) can connect and communicate to the same server node and to the same port but they must be served by two different server-processes.

Server Types - single & multiple:

When a server's processes listening to a port that means multiple sockets can simultaneously connect and communicate with the same server-process. If a server uses only a single child-process to serve all the sockets then the server is called single-process/threaded and if the server uses many sub-processes to serve each socket by one sub-process then the server is called multi-process/threaded server. Note that irrespective of the server's type a server can/should always uses the same initial socket to respond back (no need to allocate another server-port).

Suggested Books and rest of the two volumes if you can.

A Note on Parent/Child Process (in response to query/comment of 'Ioan Alexandru Cucu')

Wherever I mentioned any concept in relation to two processes say A and B, consider that they are not related by parent child relationship. OS's (especially UNIX) by design allow a child process to inherit all File-descriptors (FD) from parents. Thus all the sockets (in UNIX like OS are also part of FD) that a process A listening to, can be listened by many more processes A1, A2, .. as long as they are related by parent-child relation to A. But an independent process B (i.e. having no parent-child relation to A) cannot listen to same socket. In addition, also note that this rule of disallowing two independent processes to listen to same socket lies on an OS (or its network libraries) and by far it's obeyed by most OS's. However, one can create own OS which can very well violate this restrictions.

### What are the main differences between JWT and OAuth authentication?

OAuth 2.0 defines a protocol, i.e. specifies how tokens are transferred, JWT defines a token format.

OAuth 2.0 and "JWT authentication" have similar appearance when it comes to the (2nd) stage where the Client presents the token to the Resource Server: the token is passed in a header.

But "JWT authentication" is not a standard and does not specify how the Client obtains the token in the first place (the 1st stage). That is where the perceived complexity of OAuth comes from: it also defines various ways in which the Client can obtain an access token from something that is called an Authorization Server.

So the real difference is that JWT is just a token format, OAuth 2.0 is a protocol (that may use a JWT as a token format).

### How to remove all ListBox items?

• VB ListBox2.DataSource = Nothing
• C# ListBox2.DataSource = null;

### Function Pointers in Java

This brings to mind Steve Yegge's Execution in the Kingdom of Nouns. It basically states that Java needs an object for every action, and therefore does not have "verb-only" entities like function pointers.

### How to append one file to another in Linux from the shell?

`cat` can be the easy solution but that become very slow when we concat large files, `find -print` is to rescue you, though you have to use cat once.

``````amey@xps ~/work/python/tmp \$ ls -lhtr
total 969M
-rw-r--r-- 1 amey amey 485M May 24 23:54 bigFile2.txt
-rw-r--r-- 1 amey amey 485M May 24 23:55 bigFile1.txt

amey@xps ~/work/python/tmp \$ time cat bigFile1.txt bigFile2.txt >> out.txt

real    0m3.084s
user    0m0.012s
sys     0m2.308s

amey@xps ~/work/python/tmp \$ time find . -maxdepth 1 -type f -name 'bigFile*' -print0 | xargs -0 cat -- > outFile1

real    0m2.516s
user    0m0.028s
sys     0m2.204s
``````

### Removing object properties with Lodash

To select (or remove) object properties that satisfy a given condition deeply, you can use something like this:

``````function pickByDeep(object, condition, arraysToo=false) {
return _.transform(object, (acc, val, key) => {
if (_.isPlainObject(val) || arraysToo && _.isArray(val)) {
acc[key] = pickByDeep(val, condition, arraysToo);
} else if (condition(val, key, object)) {
acc[key] = val;
}
});
}
``````

https://codepen.io/aercolino/pen/MWgjyjm

### String to object in JS

You need use JSON.parse() for convert String into a Object:

``````var obj = JSON.parse('{ "firstName":"name1", "lastName": "last1" }');
``````

### CSS Selector that applies to elements with two classes

Chain both class selectors (without a space in between):

``````.foo.bar {
/* Styles for element(s) with foo AND bar classes */
}
``````

If you still have to deal with ancient browsers like IE6, be aware that it doesn't read chained class selectors correctly: it'll only read the last class selector (`.bar` in this case) instead, regardless of what other classes you list.

To illustrate how other browsers and IE6 interpret this, consider this CSS:

``````* {
color: black;
}

.foo.bar {
color: red;
}
``````

Output on supported browsers is:

``````<div class="foo">Hello Foo</div>       <!-- Not selected, black text [1] -->
<div class="foo bar">Hello World</div> <!-- Selected, red text [2] -->
<div class="bar">Hello Bar</div>       <!-- Not selected, black text [3] -->
``````

Output on IE6 is:

``````<div class="foo">Hello Foo</div>       <!-- Not selected, black text [1] -->
<div class="foo bar">Hello World</div> <!-- Selected, red text [2] -->
<div class="bar">Hello Bar</div>       <!-- Selected, red text [2] -->
``````

Footnotes:

• Supported browsers:
1. Not selected as this element only has class `foo`.
2. Selected as this element has both classes `foo` and `bar`.
3. Not selected as this element only has class `bar`.

• IE6:
1. Not selected as this element doesn't have class `bar`.
2. Selected as this element has class `bar`, regardless of any other classes listed.

### @property retain, assign, copy, nonatomic in Objective-C

After reading many articles I decided to put all the attributes information together:

1. atomic //default
2. nonatomic
3. strong=retain //default
4. weak= unsafe_unretained
5. retain
6. assign //default
7. unsafe_unretained
8. copy

Below is a link to the detailed article where you can find these attributes.

Many thanks to all the people who give best answers here!!

Variable property attributes or Modifiers in iOS

Here is the Sample Description from Article

1. atomic -Atomic means only one thread access the variable(static type). -Atomic is thread safe. -but it is slow in performance -atomic is default behavior -Atomic accessors in a non garbage collected environment (i.e. when using retain/release/autorelease) will use a lock to ensure that another thread doesn't interfere with the correct setting/getting of the value. -it is not actually a keyword.

Example :

``````@property (retain) NSString *name;

@synthesize name;
``````
1. nonatomic -Nonatomic means multiple thread access the variable(dynamic type). -Nonatomic is thread unsafe. -but it is fast in performance -Nonatomic is NOT default behavior,we need to add nonatomic keyword in property attribute. -it may result in unexpected behavior, when two different process (threads) access the same variable at the same time.

Example:

``````@property (nonatomic, retain) NSString *name;

@synthesize name;
``````

Explain:

If the property "name" was nonatomic, then all threads in above example - A,B, C and D will execute simultaneously producing any unpredictable result. In case of atomic, Either one of A, B or C will execute first but D can still execute in parallel.

1. strong (iOS4 = retain ) -it says "keep this in the heap until I don't point to it anymore" -in other words " I'am the owner, you cannot dealloc this before aim fine with that same as retain" -You use strong only if you need to retain the object. -By default all instance variables and local variables are strong pointers. -We generally use strong for UIViewControllers (UI item's parents) -strong is used with ARC and it basically helps you , by not having to worry about the retain count of an object. ARC automatically releases it for you when you are done with it.Using the keyword strong means that you own the object.

Example:

``````@property (strong, nonatomic) ViewController *viewController;

@synthesize viewController;
``````
1. weak (iOS4 = unsafe_unretained ) -it says "keep this as long as someone else points to it strongly" -the same thing as assign, no retain or release -A "weak" reference is a reference that you do not retain. -We generally use weak for IBOutlets (UIViewController's Childs).This works because the child object only needs to exist as long as the parent object does. -a weak reference is a reference that does not protect the referenced object from collection by a garbage collector. -Weak is essentially assign, a unretained property. Except the when the object is deallocated the weak pointer is automatically set to nil

Example :

``````@property (weak, nonatomic) IBOutlet UIButton *myButton;

@synthesize myButton;
``````

Strong & Weak Explanation, Thanks to BJ Homer:

Imagine our object is a dog, and that the dog wants to run away (be deallocated). Strong pointers are like a leash on the dog. As long as you have the leash attached to the dog, the dog will not run away. If five people attach their leash to one dog, (five strong pointers to one object), then the dog will not run away until all five leashes are detached. Weak pointers, on the other hand, are like little kids pointing at the dog and saying "Look! A dog!" As long as the dog is still on the leash, the little kids can still see the dog, and they'll still point to it. As soon as all the leashes are detached, though, the dog runs away no matter how many little kids are pointing to it. As soon as the last strong pointer (leash) no longer points to an object, the object will be deallocated, and all weak pointers will be zeroed out. When we use weak? The only time you would want to use weak, is if you wanted to avoid retain cycles (e.g. the parent retains the child and the child retains the parent so neither is ever released).

1. retain = strong -it is retained, old value is released and it is assigned -retain specifies the new value should be sent -retain on assignment and the old value sent -release -retain is the same as strong. -apple says if you write retain it will auto converted/work like strong only. -methods like "alloc" include an implicit "retain"

Example:

``````@property (nonatomic, retain) NSString *name;

@synthesize name;
``````
1. assign -assign is the default and simply performs a variable assignment -assign is a property attribute that tells the compiler how to synthesize the property's setter implementation -I would use assign for C primitive properties and weak for weak references to Objective-C objects.

Example:

``````@property (nonatomic, assign) NSString *address;

``````
1. unsafe_unretained

-unsafe_unretained is an ownership qualifier that tells ARC how to insert retain/release calls -unsafe_unretained is the ARC version of assign.

Example:

``````@property (nonatomic, unsafe_unretained) NSString *nickName;

@synthesize nickName;
``````
1. copy -copy is required when the object is mutable. -copy specifies the new value should be sent -copy on assignment and the old value sent -release. -copy is like retain returns an object which you must explicitly release (e.g., in dealloc) in non-garbage collected environments. -if you use copy then you still need to release that in dealloc. -Use this if you need the value of the object as it is at this moment, and you don't want that value to reflect any changes made by other owners of the object. You will need to release the object when you are finished with it because you are retaining the copy.

Example:

``````@property (nonatomic, copy) NSArray *myArray;

@synthesize myArray;
``````

### How to use JavaScript to change div backgroundColor

Adding/changing style of the elements in code is a bad practice. Today you want to change the background color and tomorrow you would like to change background image and after tomorrow you decided that it would be also nice to change the border.

Editing the code every-time only because the design requirements changes is a pain. Also, if your project will grow, changing js files will be even more pain. More code, more pain.

Try to eliminate use of hard coded styles, this will save you time and, if you do it right, you could ask to do the "change-color" task to someone else.

So, instead of changing direct properties of style, you can add/remove CSS classes on nodes. In your specific case, you only need to do this for parent node - "div" and then, style the subnodes through CSS. So no need to apply specific style property to DIV and to H2.

One more recommendation point. Try not to connect nodes hardcoded, but use some semantic to do that. For example: "To add events to all nodes which have class 'content'.

In conclusion, here is the code which I would use for such tasks:

``````//for adding a css class
function onOver(node){
node.className = node.className + ' Hover';
}

//for removing a css class
function onOut(node){
node.className = node.className.replace('Hover','');
}

function connect(node,event,fnc){
fnc(node);
},false);
}else if(node.attachEvent){
node.attachEvent(event,function(){
fnc(node);
});
}
}

// run this one when window is loaded
var divs = document.getElementsByTagName("div");
for(var i=0,div;div =divs[i];i++){
if(div.className.match('content')){
connect(div,'onmouseover',onOver);
connect(div,'onmouseout',onOut);
}
}
``````

And you CSS whould be like this:

``````.content {
background-color: blue;
}

.content.Hover{
background-color: red;
}

.content.Hover h2{
background-color : yellow;
}
``````

### 'Field required a bean of type that could not be found.' error spring restful API using mongodb

This may happen when two beans have same names.

`Module1Beans.java`:

``````@Configuration
public class Module1Beans {
@Bean
Retrofit retrofit = new Retrofit.Builder()
.build();
}
}
``````

`Module2Beans.java`:

``````@Configuration
public class Module2Beans {
@Bean
public GithubAPI retrofitService(){
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://www.github.com/")
.build();
return retrofit.create(GithubAPI.class);
}
}
``````

A bean named `retrofitService` is first created, and it's type is `GoogleAPI`, then covered by a `GithubAPI` becauce they're both created by a `retrofitService()` method. Now when you `@Autowired` a `GoogleAPI` you'll get a message like `Field googleAPI in com.example.GoogleService required a bean of type 'com.example.rest.GoogleAPI' that could not be found.`

### Using switch statement with a range of value in each case?

The closest you can get to that kind of behavior with `switch` statements is

``````switch (num) {
case 1:
case 2:
case 3:
case 4:
case 5:
System.out.println("1 through 5");
break;
case 6:
case 7:
case 8:
case 9:
case 10:
System.out.println("6 through 10");
break;
}
``````

Use `if` statements.

### How to initialize all members of an array to the same value?

If the size of the array is known in advance, one could use a Boost preprocessor C_ARRAY_INITIALIZE macro to do the dirty job for you:

``````#include <boost/preprocessor/repetition/enum.hpp>
#define C_ARRAY_ELEMENT(z, index, name) name[index]
#define C_ARRAY_EXPAND(name,size) BOOST_PP_ENUM(size,C_ARRAY_ELEMENT,name)
#define C_ARRAY_VALUE(z, index, value) value
#define C_ARRAY_INITIALIZE(value,size) BOOST_PP_ENUM(size,C_ARRAY_VALUE,value)
``````

### git ignore vim temporary files

This works on a Mac as noted by Alex Moore-Niemi:

``````set backupdir=\$TMPDIR//
set directory=\$TMPDIR//
``````

Make sure to use `TMPDIR` and not `TEMPDIR`.

### Entity framework left join

For 2 and more left joins (left joining creatorUser and initiatorUser )

``````IQueryable<CreateRequestModel> queryResult = from r in authContext.Requests
join candidateUser in authContext.AuthUsers
on r.CandidateId equals candidateUser.Id
join creatorUser in authContext.AuthUsers
on r.CreatorId equals creatorUser.Id into gj
from x in gj.DefaultIfEmpty()
join initiatorUser in authContext.AuthUsers
on r.InitiatorId equals initiatorUser.Id into init
from x1 in init.DefaultIfEmpty()

select new CreateRequestModel
{
CreatorId = (x == null ? String.Empty : x.UserName),
InitiatorId = (x1 == null ? String.Empty : x1.UserName),
};
``````

### SSH SCP Local file to Remote in Terminal Mac Os X

Watch that your file name doesn't have `:` in them either. I found that I had to `mv blah-07-08-17-02:69.txt no_colons.txt` and then `scp no-colons.txt server:` then don't forget to `mv` back on the server. Just in case this was an issue.

### Connect HTML page with SQL server using javascript

Before The execution of following code, I assume you have created a database and a table (with columns Name (varchar), Age(INT) and Address(varchar)) inside that database. Also please update your SQL Server name , UserID, password, DBname and table name in the code below.

In the code. I have used VBScript and embedded it in HTML. Try it out!

``````<!DOCTYPE html>
<html>
<script type="text/vbscript">
<!--

Sub Submit_onclick()
Dim Connection
Dim ConnString
Dim Recordset

Connection.Open ConnString

dim form1
Set form1 = document.Register

Name1 = form1.Name.value
Age1 = form1.Age.Value

connection.execute("INSERT INTO [*YourTableName*] VALUES ('"&Name1 &"'," &Age1 &",'"&Add1 &"')")

End Sub

//-->
</script>
<body>

<p>
<form name="Register">
<pre>
<font face="Times New Roman" size="3">Please enter the log in credentials:<br>
Name:   <input type="text" name="Name">
Age:        <input type="text" name="Age">
<input type="button" id ="Submit" value="submit" /><font></form>
</p>
</pre>
</body>
</html>
``````

### Rotate an image in image source in html

This might be your script-free solution: http://davidwalsh.name/css-transform-rotate

It's supported in all browsers prefixed and, in IE10-11 and all still-used Firefox versions, unprefixed.

That means that if you don't care for old IEs (the bane of web designers) you can skip the `-ms-` and `-moz-` prefixes to economize space.

However, the Webkit browsers (Chrome, Safari, most mobile navigators) still need `-webkit-`, and there's a still-big cult following of pre-Next Opera and using `-o-` is sensate.

### Using custom std::set comparator

You are using a function where as you should use a functor (a class that overloads the () operator so it can be called like a function).

``````struct lex_compare {
bool operator() (const int64_t& lhs, const int64_t& rhs) const {
stringstream s1, s2;
s1 << lhs;
s2 << rhs;
return s1.str() < s2.str();
}
};
``````

You then use the class name as the type parameter

``````set<int64_t, lex_compare> s;
``````

If you want to avoid the functor boilerplate code you can also use a function pointer (assuming `lex_compare` is a function).

``````set<int64_t, bool(*)(const int64_t& lhs, const int64_t& rhs)> s(&lex_compare);
``````

### can't access mysql from command line mac

Just do the following in your terminal:

`echo \$PATH`

If your given path is not in that string, you have to add it like this: `export PATH=\$PATH:/usr/local/` or `export PATH=\$PATH:/usr/local/mysql/bin`

### calling java methods in javascript code

When it is on server side, use web services - maybe RESTful with JSON.

• create a web service (for example with Tomcat)
• call its URL from JavaScript (for example with JQuery or dojo)

When Java code is in applet you can use JavaScript bridge. The bridge between the Java and JavaScript programming languages, known informally as LiveConnect, is implemented in Java plugin. Formerly Mozilla-specific LiveConnect functionality, such as the ability to call static Java methods, instantiate new Java objects and reference third-party packages from JavaScript, is now available in all browsers.

Below is example from documentation. Look at `methodReturningString`.

Java code:

``````public class MethodInvocation extends Applet {
public void noArgMethod() { ... }
public void someMethod(String arg) { ... }
public void someMethod(int arg) { ... }
public int  methodReturningInt() { return 5; }
public String methodReturningString() { return "Hello"; }
public OtherClass methodReturningObject() { return new OtherClass(); }
}

public class OtherClass {
public void anotherMethod();
}
``````

Web page and JavaScript code:

``````<applet id="app"
archive="examples.jar"
code="MethodInvocation" ...>
</applet>
<script language="javascript">
app.noArgMethod();
app.someMethod("Hello");
app.someMethod(5);
var five = app.methodReturningInt();
var hello = app.methodReturningString();
app.methodReturningObject().anotherMethod();
</script>
``````

### Can't Autowire @Repository annotated interface in Spring Boot

You are scanning the wrong package:

``````@ComponentScan("**org**.pharmacy")
``````

Where as it should be:

``````@ComponentScan("**com**.pharmacy")
``````

Since your package names start with com and not org.

### Get index of a key in json

Its too late, but it may be simple and useful

``````var json = { "key1" : "watevr1", "key2" : "watevr2", "key3" : "watevr3" };
var keytoFind = "key2";
var index = Object.keys(json).indexOf(keytoFind);
``````

### UnsupportedClassVersionError: JVMCFRE003 bad major version in WebSphere AS 7

In this Eclipse Preferences panel you can change the compiler compatibility from 1.7 to 1.6. This solved the similar message I was getting. For Eclipse, it is under: Preferences -> Java -> Compiler: 'Compiler compliance level'

### Pure Javascript listen to input value change

As a basic example...

HTML:

``````<input type="text" name="Thing" value="" />
``````

Script:

``````/* event listener */

/* function */
function doThing(){
alert('Horray! Someone wrote "' + this.value + '"!');
}
``````

Here's a fiddle: http://jsfiddle.net/Niffler/514gg4tk/

### npm start error with create-react-app

Yes you should not install react-scripts globally, it will not work.

I think i didn't use the --save when i first created the project (on another machine), so for me this fixed the problem :

``````npm install --save react react-dom react-scripts
``````

### Cannot find runtime 'node' on PATH - Visual Studio Code and Node.js

I did `which node` on my terminal: `/usr/local/bin/node`

and then i added `"runtimeExecutable": "/usr/local/bin/node"` in my json file.

### Can I Set "android:layout_below" at Runtime Programmatically?

Yes:

``````RelativeLayout.LayoutParams params= new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT);
viewToLayout.setLayoutParams(params);
``````

First, the code creates a new layout params by specifying the height and width. The `addRule` method adds the equivalent of the xml properly `android:layout_below`. Then you just call `View#setLayoutParams` on the view you want to have those params.

### How to encode URL to avoid special characters in Java?

I also spent quite some time with this issue, so that's my solution:

``````String urlString2Decode = "http://www.test.com/äüö/path with blanks/";
String decodedURL = URLDecoder.decode(urlString2Decode, "UTF-8");
URL url = new URL(decodedURL);
URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef());
String decodedURLAsString = uri.toASCIIString();
``````

### How can I set a dynamic model name in AngularJS?

http://jsfiddle.net/DrQ77/

You can simply put javascript expression in `ng-model`.

### Can I perform a DNS lookup (hostname to IP address) using client-side Javascript?

Edit: This question gave me an itch, so I put up a JSONP webservice on Google App Engine that returns the clients ip address. Usage:

``````<script type="application/javascript">
function getip(json){
}
</script>

<script type="application/javascript" src="http://jsonip.appspot.com/?callback=getip"> </script>
``````

Yay, no server proxies needed.

Pure JS can't. If you have a server script under the same domain that prints it out you could send a XMLHttpRequest to read it.

### Parallel foreach with asynchronous lambda

The following is set to work with `IAsyncEnumerable` but can be modified to use `IEnumerable` by just changing the type and removing the "await" on the `foreach`. It's far more appropriate for large sets of data than creating countless parallel tasks and then awaiting them all.

``````    public static async Task ForEachAsyncConcurrent<T>(this IAsyncEnumerable<T> enumerable, Func<T, Task> action, int maxDegreeOfParallelism, int? boundedCapacity = null)
{
ActionBlock<T> block = new ActionBlock<T>(
action,
new ExecutionDataflowBlockOptions
{
MaxDegreeOfParallelism = maxDegreeOfParallelism,
BoundedCapacity = boundedCapacity ?? maxDegreeOfParallelism * 3
});

await foreach (T item in enumerable)
{
await block.SendAsync(item).ConfigureAwait(false);
}

block.Complete();
await block.Completion;
}
``````

### Lock down Microsoft Excel macro

You can check out this new product at http://hivelink.io, it allows you to properly protect your sensitive macros.

The Excel password system is extremely weak - you can crack it in 2 minutes just using a basic HEX editor. I wouldn't recommend relying on this to protect anything.

I wrote an extensive post on this topic here: Protecting Code in an Excel Workbook?

### Create a new workspace in Eclipse

In Window->Preferences->General->Startup and Shutdown->Workspaces, make sure that 'Prompt for Workspace on startup' is checked.

Then close eclipse and reopen.

Then you'll be prompted for a workspace to open. You can create a new workspace from that dialogue.

Or File->Switch Workspace->Other...

### How to check if matching text is found in a string in Lua?

There are 2 options to find matching text; `string.match` or `string.find`.

Both of these perform a regex search on the string to find matches.

#### `string.find()`

``````string.find(subject string, pattern string, optional start position, optional plain flag)
``````

Returns the `startIndex` & `endIndex` of the substring found.

The `plain` flag allows for the pattern to be ignored and intead be interpreted as a literal. Rather than `(tiger)` being interpreted as a regex capture group matching for `tiger`, it instead looks for `(tiger)` within a string.

Going the other way, if you want to regex match but still want literal special characters (such as `.()[]+-` etc.), you can escape them with a percentage; `%(tiger%)`.

You will likely use this in combination with `string.sub`

#### Example

``````str = "This is some text containing the word tiger."
if string.find(str, "tiger") then
print ("The word tiger was found.")
else
print ("The word tiger was not found.")
end
``````

#### `string.match()`

``````string.match(s, pattern, optional index)
``````

Returns the capture groups found.

#### Example

``````str = "This is some text containing the word tiger."
if string.match(str, "tiger") then
print ("The word tiger was found.")
else
print ("The word tiger was not found.")
end
``````

### Master Page Weirdness - "Content controls have to be top-level controls in a content page or a nested master page that references a master page."

You need to add asp content and add content place holder id correspond to the placeholder in master page.

You can read this link for more detail

### How to get start and end of previous month in VB

Just to add something to what @Fionnuala Said, The below functions can be used. These even work for leap years.

``````'If you pass #2016/20/01# you get #2016/31/01#
Public Function GetLastDate(tempDate As Date) As Date
GetLastDate = DateSerial(Year(tempDate), Month(tempDate) + 1, 0)
End Function

'If you pass #2016/20/01# you get 31
Public Function GetLastDay(tempDate As Date) As Integer
GetLastDay = Day(DateSerial(Year(tempDate), Month(tempDate) + 1, 0))
End Function
``````

### Crontab Day of the Week syntax

`0` and `7` both stand for Sunday, you can use the one you want, so writing 0-6 or 1-7 has the same result.

Also, as suggested by @Henrik, it is possible to replace numbers by shortened name of days, such as `MON`, `THU`, etc:

``````0 - Sun      Sunday
1 - Mon      Monday
2 - Tue      Tuesday
3 - Wed      Wednesday
4 - Thu      Thursday
5 - Fri      Friday
6 - Sat      Saturday
7 - Sun      Sunday
``````

Graphically:

`````` +---------- minute (0 - 59)
¦ +-------- hour (0 - 23)
¦ ¦ +------ day of month (1 - 31)
¦ ¦ ¦ +---- month (1 - 12)
¦ ¦ ¦ ¦ +-- day of week (0 - 6 => Sunday - Saturday, or
¦ ¦ ¦ ¦ ¦                1 - 7 => Monday - Sunday)
? ? ? ? ?
* * * * * command to be executed
``````

Finally, if you want to specify day by day, you can separate days with commas, for example `SUN,MON,THU` will exectute the command only on sundays, mondays on thursdays.

You can read further details in Wikipedia's article about Cron.

### Bash tool to get nth line from a file

As a followup to CaffeineConnoisseur's very helpful benchmarking answer... I was curious as to how fast the 'mapfile' method was compared to others (as that wasn't tested), so I tried a quick-and-dirty speed comparison myself as I do have bash 4 handy. Threw in a test of the "tail | head" method (rather than head | tail) mentioned in one of the comments on the top answer while I was at it, as folks are singing its praises. I don't have anything nearly the size of the testfile used; the best I could find on short notice was a 14M pedigree file (long lines that are whitespace-separated, just under 12000 lines).

Short version: mapfile appears faster than the cut method, but slower than everything else, so I'd call it a dud. tail | head, OTOH, looks like it could be the fastest, although with a file this size the difference is not all that substantial compared to sed.

``````\$ time head -11000 [filename] | tail -1
[output redacted]

real    0m0.117s

\$ time cut -f11000 -d\$'\n' [filename]
[output redacted]

real    0m1.081s

\$ time awk 'NR == 11000 {print; exit}' [filename]
[output redacted]

real    0m0.058s

\$ time perl -wnl -e '\$.== 11000 && print && exit;' [filename]
[output redacted]

real    0m0.085s

\$ time sed "11000q;d" [filename]
[output redacted]

real    0m0.031s

\$ time (mapfile -s 11000 -n 1 ary < [filename]; echo \${ary[0]})
[output redacted]

real    0m0.309s

\$ time tail -n+11000 [filename] | head -n1
[output redacted]

real    0m0.028s
``````

Hope this helps!

### session not created: This version of ChromeDriver only supports Chrome version 74 error with ChromeDriver Chrome using Selenium

I had the same problem and solved it by simply downloading a `chromedriver` file for a previous version of chrome. I have found that version 79 of Chrome is compatible with the current version of Selenium.

I then saved it in a specified path, and linked that path to my `webdriver`.

### Want to show/hide div based on dropdown box selection

you have error in your code `unexpected token`.use:

``````  \$('#purpose').on('change', function () {
if (this.value == '1') {
} else {
}

});
``````

Demo

Update: You can narrow down the code using `.toggle()`

`````` \$('#purpose').on('change', function () {
});
``````

### JavaFX and OpenJDK

JavaFX is part of OpenJDK

The JavaFX project itself is open source and is part of the OpenJDK project.

Update Dec 2019

For current information on how to use Open Source JavaFX, visit https://openjfx.io. This includes instructions on using JavaFX as a modular library accessed from an existing JDK (such as an Open JDK installation).

The open source code repository for JavaFX is at https://github.com/openjdk/jfx.

At the source location linked, you can find license files for open JavaFX (currently this license matches the license for OpenJDK: GPL+classpath exception).

The wiki for the project is located at: https://wiki.openjdk.java.net/display/OpenJFX/Main

If you want a quick start to using open JavaFX, the Belsoft Liberica JDK distributions provide pre-built binaries of OpenJDK that (currently) include open JavaFX for a variety of platforms.

For distribution as self-contained applications, Java 14, is scheduled to implement JEP 343: Packaging Tool, which "Supports native packaging formats to give end users a natural installation experience. These formats include msi and exe on Windows, pkg and dmg on macOS, and deb and rpm on Linux.", for deployment of OpenJFX based applications with native installers and no additional platform dependencies (such as a pre-installed JDK).

Older information which may become outdated over time

Building JavaFX from the OpenJDK repository

You can build an open version of OpenJDK (including JavaFX) completely from source which has no dependencies on the Oracle JDK or closed source code.

Update: Using a JavaFX distribution pre-built from OpenJDK sources

As noted in comments to this question and in another answer, the Debian Linux distributions offer a JavaFX binary distibution based upon OpenJDK:

(currently this only works for Java 8 as far as I know).

Differences between Open JDK and Oracle JDK with respect to JavaFX

The following information was provided for Java 8. As of Java 9, VP6 encoding is deprecated for JavaFX and the Oracle WebStart/Browser embedded application deployment technology is also deprecated. So future versions of JavaFX, even if they are distributed by Oracle, will likely not include any technology which is not open source.

Oracle JDK includes some software which is not usable from the OpenJDK. There are two main components which relate to JavaFX.

1. The ON2 VP6 video codec, which is owned by Google and Google has not open sourced.
2. The Oracle WebStart/Browser Embedded application deployment technology.

This means that an open version of JavaFX cannot play VP6 FLV files. This is not a big loss as it is difficult to find VP6 encoders or media encoded in VP6.

Other more common video formats, such as H.264 will playback fine with an open version of JavaFX (as long as you have the appropriate codecs pre-installed on the target machine).

The lack of WebStart/Browser Embedded deployment technology is really something to do with OpenJDK itself rather than JavaFX specifically. This technology can be used to deploy non-JavaFX applications.

It would be great if the OpenSource community developed a deployment technology for Java (and other software) which completely replaced WebStart and Browser Embedded deployment methods, allowing a nice light-weight, low impact user experience for application distribution. I believe there have been some projects started to serve such a goal, but they have not yet reached a high maturity and adoption level.

Personally, I feel that WebStart/Browser Embedded deployments are legacy technology and there are currently better ways to deploy many JavaFX applications (such as self-contained applications).

Update Dec, 2019:

An open source version of WebStart for JDK 11+ has been developed and is available at https://openwebstart.com.

Who needs to create Linux OpenJDK Distributions which include JavaFX

It is up to the people which create packages for Linux distributions based upon OpenJDK (e.g. Redhat, Ubuntu etc) to create RPMs for the JDK and JRE that include JavaFX. Those software distributors, then need to place the generated packages in their standard distribution code repositories (e.g. fedora/red hat network yum repositories). Currently this is not being done, but I would be quite surprised if Java 8 Linux packages did not include JavaFX when Java 8 is released in March 2014.

Update, Dec 2019:

Now that JavaFX has been separated from most binary JDK and JRE distributions (including Oracle's distribution) and is, instead, available as either a stand-alone SDK, set of jmods or as a library dependencies available from the central Maven repository (as outlined as https://openjfx.io), there is less of a need for standard Linux OpenJDK distributions to include JavaFX.

If you want a pre-built JDK which includes JavaFX, consider the Liberica JDK distributions, which are provided for a variety of platforms.

Advice on Deployment for Substantial Applications

I advise using Java's self-contained application deployment mode.

A description of this deployment mode is:

Application is installed on the local drive and runs as a standalone program using a private copy of Java and JavaFX runtimes. The application can be launched in the same way as other native applications for that operating system, for example using a desktop shortcut or menu entry.

You can build a self-contained application either from the Oracle JDK distribution or from an OpenJDK build which includes JavaFX. It currently easier to do so with an Oracle JDK.

As a version of Java is bundled with your application, you don't have to care about what version of Java may have been pre-installed on the machine, what capabilities it has and whether or not it is compatible with your program. Instead, you can test your application against an exact Java runtime version, and distribute that with your application. The user experience for deploying your application will be the same as installing a native application on their machine (e.g. a windows .exe or .msi installed, an OS X .dmg, a linux .rpm or .deb).

Note: The self-contained application feature was only available for Java 8 and 9, and not for Java 10-13. Java 14, via JEP 343: Packaging Tool, is scheduled to again provide support for this feature from OpenJDK distributions.

Update, April 2018: Information on Oracle's current policy towards future developments

### Singular matrix issue with Numpy

As it was already mentioned in previous answers, your matrix cannot be inverted, because its determinant is 0. But if you still want to get inverse matrix, you can use `np.linalg.pinv`, which leverages SVD to approximate initial matrix.

### 'nuget' is not recognized but other nuget commands working

Nuget.exe is placed at `.nuget` folder of your project. It can't be executed directly in Package Manager Console, but is executed by Powershell commands because these commands build custom path for themselves.

My steps to solve are:

Update

NuGet can be easily installed in your project using the following command:

Install-Package NuGet.CommandLine

### How to measure time taken between lines of code in python?

With a help of a small convenience class, you can measure time spent in indented lines like this:

``````with CodeTimer():
line_to_measure()
another_line()
# etc...
``````

Which will show the following after the indented line(s) finishes executing:

``````Code block took: x.xxx ms
``````

UPDATE: You can now get the class with `pip install linetimer` and then `from linetimer import CodeTimer`. See this GitHub project.

The code for above class:

``````import timeit

class CodeTimer:
def __init__(self, name=None):
self.name = " '"  + name + "'" if name else ''

def __enter__(self):
self.start = timeit.default_timer()

def __exit__(self, exc_type, exc_value, traceback):
self.took = (timeit.default_timer() - self.start) * 1000.0
print('Code block' + self.name + ' took: ' + str(self.took) + ' ms')
``````

You could then name the code blocks you want to measure:

``````with CodeTimer('loop 1'):
for i in range(100000):
pass

with CodeTimer('loop 2'):
for i in range(100000):
pass

Code block 'loop 1' took: 4.991 ms
Code block 'loop 2' took: 3.666 ms
``````

And nest them:

``````with CodeTimer('Outer'):
for i in range(100000):
pass

with CodeTimer('Inner'):
for i in range(100000):
pass

for i in range(100000):
pass

Code block 'Inner' took: 2.382 ms
Code block 'Outer' took: 10.466 ms
``````

Regarding `timeit.default_timer()`, it uses the best timer based on OS and Python version, see this answer.

### How to update SQLAlchemy row entry?

#### Examples to clarify the important issue in accepted answer's comments

I didn't understand it until I played around with it myself, so I figured there would be others who were confused as well. Say you are working on the user whose `id == 6` and whose `no_of_logins == 30` when you start.

``````# 1 (bad)
# result: UPDATE user SET no_of_logins = 31 WHERE user.id = 6

# result: UPDATE user SET no_of_logins = 31 WHERE user.id = 6

# result: UPDATE user SET no_of_logins = 31 WHERE user.id = 6

# 4 (ok)
# result: UPDATE user SET no_of_logins = no_of_logins + 1 WHERE user.id = 6

# 5 (ok)
# result: UPDATE user SET no_of_logins = no_of_logins + 1 WHERE user.id = 6
``````

#### The point

By referencing the class instead of the instance, you can get SQLAlchemy to be smarter about incrementing, getting it to happen on the database side instead of the Python side. Doing it within the database is better since it's less vulnerable to data corruption (e.g. two clients attempt to increment at the same time with a net result of only one increment instead of two). I assume it's possible to do the incrementing in Python if you set locks or bump up the isolation level, but why bother if you don't have to?

#### A caveat

If you are going to increment twice via code that produces SQL like `SET no_of_logins = no_of_logins + 1`, then you will need to commit or at least flush in between increments, or else you will only get one increment in total:

``````# 6 (bad)
session.commit()
# result: UPDATE user SET no_of_logins = no_of_logins + 1 WHERE user.id = 6

# 7 (ok)
session.flush()
# result: UPDATE user SET no_of_logins = no_of_logins + 1 WHERE user.id = 6
session.commit()
# result: UPDATE user SET no_of_logins = no_of_logins + 1 WHERE user.id = 6
``````

### how to fix java.lang.IndexOutOfBoundsException

`lstpp` is empty. You cant access the first element of an empty list.

In general, you can check if `size > index`.

In your case, you need to check if `lstpp` is empty. (you can use `!lstpp.isEmpty()`)

### sqlalchemy IS NOT NULL select

In case anyone else is wondering, you can use `is_` to generate `foo IS NULL`:

```>>> from sqlalchemy.sql import column
>>> print column('foo').is_(None)
foo IS NULL
>>> print column('foo').isnot(None)
foo IS NOT NULL
```

### Python conversion between coordinates

Thinking about it in general, I would strongly consider hiding coordinate system behind well-designed abstraction. Quoting Uncle Bob and his book:

``````class Point(object)
def setCartesian(self, x, y)
def setPolar(self, rho, theta)
def getX(self)
def getY(self)
def getRho(self)
def setTheta(self)
``````

With interface like that any user of Point class may choose convenient representation, no explicit conversions will be performed. All this ugly sines, cosines etc. will be hidden in one place. Point class. Only place where you should care which representation is used in computer memory.

### What is the native keyword in Java for?

As SLaks answered, the `native` keyword is for calling native code.

It also used by GWT for implementing javascript methods.

### Undo git update-index --assume-unchanged <file>

To get undo/show dir's/files that are set to assume-unchanged run this:

`git update-index --no-assume-unchanged <file>`

To get a list of dir's/files that are `assume-unchanged` run this:

`git ls-files -v|grep '^h'`

### Gunicorn worker timeout error

If you are using GCP then you have to set workers per instance type.

### how to convert an RGB image to numpy array?

When using the answer from David Poole I get a SystemError with gray scale PNGs and maybe other files. My solution is:

``````import numpy as np
from PIL import Image

img = Image.open( filename )
try:
data = np.asarray( img, dtype='uint8' )
except SystemError:
data = np.asarray( img.getdata(), dtype='uint8' )
``````

Actually img.getdata() would work for all files, but it's slower, so I use it only when the other method fails.

### OR is not supported with CASE Statement in SQL Server

``````select id,phno,case gender
when 'G' then 'M'
when 'L' then 'F'
else
'No gender'
end
as gender
from contacts
``````

### Sending HTML Code Through JSON

Just to expand on @T.J. Crowder's answer.

`json_encode` does well with simple html strings, in my experience however `json_encode` often becomes confused by, (or it becomes quite difficult to properly escape) longer complex nested html mixed with php. Two options to consider if you are in this position are: encoding/decoding the markup first with something like `[base64_encode][1]`/ decode (quite a bit of a performance hit), or (and perhaps preferably) be more selective in what you are passing via json, and generate the necessary markup on the client side instead.

### Tomcat request timeout

This article talks about setting the timeouts on the server level. http://www.coderanch.com/t/364207/Servlets/java/Servlet-Timeout-two-ways

What is causing the application to go into infinite loop? If you are opening connections to other resources, you might want to put timeouts on those connections and sending appropriate response when those time out occurs.

### What's the difference between ".equals" and "=="?

The `equals( )` method and the `==` operator perform two different operations. The `equals( )` method compares the characters inside a `String` object. The `==` operator compares two object references to see whether they refer to the same instance. The following program shows how two different String objects can contain the same characters, but references to these objects will not compare as equal:

``````// equals() vs ==
class EqualsNotEqualTo {
public static void main(String args[]) {
String s1 = "Hello";
String s2 = new String(s1);
System.out.println(s1 + " equals " + s2 + " -> " +
s1.equals(s2));
System.out.println(s1 + " == " + s2 + " -> " + (s1 == s2));
}
}
``````

The variable `s1` refers to the String instance created by `“Hello”`. The object referred to by `s2` is created with `s1` as an initializer. Thus, the contents of the two String objects are identical, but they are distinct objects. This means that `s1` and `s2` do not refer to the same objects and are, therefore, not `==`, as is shown here by the output of the preceding example:

``````Hello equals Hello -> true
Hello == Hello -> false
``````

### what is the difference between json and xml

XML uses a tag structures for presenting items, like `<tag>item</tag>`, so an XML document is a set of tags nested into each other. And JSON syntax looks like a construction from Javascript language, with all stuff like lists and dictionaries:

``````{
'attrib' : 'value',
'array' : [1, 2, 3]
}
``````

So if you use JSON it's really simple to use a JSON strings in many script languages, especially Javascript and Python.

### How to declare and initialize a static const array as a class member?

You are mixing pointers and arrays. If what you want is an array, then use an array:

``````struct test {
static int data[10];        // array, not pointer!
};
int test::data[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
``````

If on the other hand you want a pointer, the simplest solution is to write a helper function in the translation unit that defines the member:

``````struct test {
static int *data;
};
// cpp
static int* generate_data() {            // static here is "internal linkage"
int * p = new int[10];
for ( int i = 0; i < 10; ++i ) p[i] = 10*i;
return p;
}
int *test::data = generate_data();
``````

### How get permission for camera in android.(Specifically Marshmallow)

First check if the user has granted the permission:

``````if (ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA)
== PackageManager.PERMISSION_DENIED)
``````

Then, you could use this to request to the user:

``````ActivityCompat.requestPermissions(activity, new String[] {Manifest.permission.CAMERA}, requestCode);
``````

And in Marshmallow, it will appear in a dialog

### codes for ADD,EDIT,DELETE,SEARCH in vb2010

A good resource start off point would be MSDN as your looking into a microsoft product

### What are native methods in Java and where should they be used?

The method is implemented in "native" code. That is, code that does not run in the JVM. It's typically written in C or C++.

Native methods are usually used to interface with system calls or libraries written in other programming languages.

### Android - Activity vs FragmentActivity?

`FragmentActivity` gives you all of the functionality of `Activity` plus the ability to use Fragments which are very useful in many cases, particularly when working with the ActionBar, which is the best way to use Tabs in Android.

If you are only targeting Honeycomb (v11) or greater devices, then you can use `Activity` and use the native Fragments introduced in v11 without issue. `FragmentActivity` was built specifically as part of the Support Library to back port some of those useful features (such as Fragments) back to older devices.

I should also note that you'll probably find the Backward Compatibility - Implementing Tabs training very helpful going forward.