Programs & Examples On #Module pattern

Popular JavaScript pattern, var Module = (function() { ... })();

How to convert Observable<any> to array[]

You will need to subscribe to your observables:

this.CountryService.GetCountries()
    .subscribe(countries => {
        this.myGridOptions.rowData = countries as CountryData[]
    })

And, in your html, wherever needed, you can pass the async pipe to it.

Pass request headers in a jQuery AJAX GET call

_x000D_
_x000D_
$.ajax({_x000D_
            url: URL,_x000D_
            type: 'GET',_x000D_
            dataType: 'json',_x000D_
            headers: {_x000D_
                'header1': 'value1',_x000D_
                'header2': 'value2'_x000D_
            },_x000D_
            contentType: 'application/json; charset=utf-8',_x000D_
            success: function (result) {_x000D_
               // CallBack(result);_x000D_
            },_x000D_
            error: function (error) {_x000D_
                _x000D_
            }_x000D_
        });
_x000D_
_x000D_
_x000D_

Store output of sed into a variable

To store the third line into a variable, use below syntax:

variable=`echo "$1" | sed '3q;d' urfile`

To store the changed line into a variable, use below syntax: variable=echo 'overflow' | sed -e "s/over/"OVER"/g" output:OVERflow

Date difference in minutes in Python

If you are trying to find the difference between timestamps that are in pandas columns, the the answer is fairly simple. If you need it in days or seconds then

# For difference in days:
df['diff_in_days']=(df['timestamp2'] - df['timestamp1']).dt.days
# For difference in seconds
df['diff_in_seconds']=(df['timestamp2'] - df['timestamp1']).dt.seconds

Now minute is tricky as dt.minute works only on datetime64[ns] dtype. whereas the column generated from subtracting two datetimes has format

AttributeError: 'TimedeltaProperties' object has no attribute 'm8'

So like mentioned by many above to get the actual value of the difference in minute you have to do:

df['diff_in_min']=df['diff_in_seconds']/60

But if just want the difference between the minute parts of the two timestamps then do the following

#convert the timedelta to datetime and then extract minute
df['diff_in_min']=(pd.to_datetime(df['timestamp2']-df['timestamp1'])).dt.minute

You can also read the article https://docs.python.org/3.4/library/datetime.html and see section 8.1.2 you'll see the read only attributes are only seconds,days and milliseconds. And this settles why the minute function doesn't work directly.

Default username password for Tomcat Application Manager

First navigate to below location and open it in a text editor

<TOMCAT_HOME>/conf/tomcat-users.xml

For tomcat 7, Add the following xml code somewhere between <tomcat-users> I find the following solution.

  <role rolename="manager-gui"/>
  <user username="username" password="password" roles="manager-gui"/>

Now restart the tomcat server.

Read remote file with node.js (http.get)

You can do something like this, without using any external libraries.

const fs = require("fs");
const https = require("https");

const file = fs.createWriteStream("data.txt");

https.get("https://www.w3.org/TR/PNG/iso_8859-1.txt", response => {
  var stream = response.pipe(file);

  stream.on("finish", function() {
    console.log("done");
  });
});

JSON array get length

I came here and looking how to get the number of elements inside a JSONArray. From your question i used length() like that:

JSONArray jar = myjson.getJSONArray("_types");
System.out.println(jar.length());

and it worked as expected. On the other hand jar.size();(as proposed in the other answer) is not working for me.

So for future users searching (like me) how to get the size of a JSONArray, length() works just fine.

Handling a timeout error in python sockets

from foo import * 

adds all the names without leading underscores (or only the names defined in the modules __all__ attribute) in foo into your current module.

In the above code with from socket import * you just want to catch timeout as you've pulled timeout into your current namespace.

from socket import * pulls in the definitions of everything inside of socket but doesn't add socket itself.

try:
    # socketstuff
except timeout:
    print 'caught a timeout'

Many people consider import * problematic and try to avoid it. This is because common variable names in 2 or more modules that are imported in this way will clobber one another.

For example, consider the following three python files:

# a.py
def foo():
    print "this is a's foo function"

# b.py
def foo():
    print "this is b's foo function"

# yourcode.py
from a import *
from b import *
foo()

If you run yourcode.py you'll see just the output "this is b's foo function".

For this reason I'd suggest either importing the module and using it or importing specific names from the module:

For example, your code would look like this with explicit imports:

import socket
from socket import AF_INET, SOCK_DGRAM

def main():
    client_socket = socket.socket(AF_INET, SOCK_DGRAM)
    client_socket.settimeout(1)
    server_host = 'localhost'
    server_port = 1234
    while(True):
        client_socket.sendto('Message', (server_host, server_port))
        try:
            reply, server_address_info = client_socket.recvfrom(1024)
            print reply
        except socket.timeout:
            #more code

Just a tiny bit more typing but everything's explicit and it's pretty obvious to the reader where everything comes from.

TNS-12505: TNS:listener does not currently know of SID given in connect descriptor

I've just faced the same problem just after installed Oracle XE 11.2. After reading and consulting a DBA friend, I ran the following command:

C:\>tnsping xe

TNS Ping Utility for 64-bit Windows: Version 11.2.0.2.0 - Production on 11-ENE-2017 14:27:44

Copyright (c) 1997, 2014, Oracle.  All rights reserved.

Used parameter files:
C:\oraclexe\app\oracle\product\11.2.0\server\network\admin\sqlnet.ora


Used TNSNAMES adapter to resolve the alias
Attempting to contact (DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = myLaptop)(PORT = 1521)) (CONNECT_DATA = (SERVER = DEDICATED) (SERVICE_NAME = XE)))

OK (30 msec)

C:\>

As you can see, it takes long time to resolve, so I added an entry to hosts file as follows:

127.0.0.1       localhost

Once done, ran again the same command:

C:\>tnsping xe

TNS Ping Utility for 64-bit Windows: Version 11.2.0.2.0 - Production on 11-ENE-2
017 14:40:29

Copyright (c) 1997, 2014, Oracle.  All rights reserved.

Used parameter files:
C:\oraclexe\app\oracle\product\11.2.0\server\network\admin\sqlnet.ora


Used TNSNAMES adapter to resolve the alias
Attempting to contact (DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = myLaptop)(PORT = 1521)) (CONNECT_DATA = (SERVER = DEDICATED) (SER
VICE_NAME = XE)))
OK (30 msec)

C:\>

As time response radically decreases, I tried my connection on sqldeveloper successfully.

connection succed

Set value to an entire column of a pandas dataframe

Assuming your Data frame is like 'Data' you have to consider if your data is a string or an integer. Both are treated differently. So in this case you need be specific about that.

import pandas as pd

data = [('001','xxx'), ('002','xxx'), ('003','xxx'), ('004','xxx'), ('005','xxx')]

df = pd.DataFrame(data,columns=['issueid', 'industry'])

print("Old DataFrame")
print(df)

df.loc[:,'industry'] = str('yyy')

print("New DataFrame")
print(df)

Now if want to put numbers instead of letters you must create and array

list_of_ones = [1,1,1,1,1]
df.loc[:,'industry'] = list_of_ones
print(df)

Or if you are using Numpy

import numpy as np
n = len(df)
df.loc[:,'industry'] = np.ones(n)
print(df)

How to get last inserted row ID from WordPress database?

Straight after the $wpdb->insert() that does the insert, do this:

$lastid = $wpdb->insert_id;

More information about how to do things the WordPress way can be found in the WordPress codex. The details above were found here on the wpdb class page

Location of the mongodb database on mac

Env: macOS Mojave 10.14.4

Install: homebrew

Location:/usr/local/Cellar/mongodb/4.0.3_1

Note :If update version by brew upgrade mongo,the folder 4.0.4_1 will be removed and replace with the new version folder

VBA for filtering columns

Here's a different approach. The heart of it was created by turning on the Macro Recorder and filtering the columns per your specifications. Then there's a bit of code to copy the results. It will run faster than looping through each row and column:

Sub FilterAndCopy()
Dim LastRow As Long

Sheets("Sheet2").UsedRange.Offset(0).ClearContents
With Worksheets("Sheet1")
    .Range("$A:$E").AutoFilter
    .Range("$A:$E").AutoFilter field:=1, Criteria1:="#N/A"
    .Range("$A:$E").AutoFilter field:=2, Criteria1:="=String1", Operator:=xlOr, Criteria2:="=string2"
    .Range("$A:$E").AutoFilter field:=3, Criteria1:=">0"
    .Range("$A:$E").AutoFilter field:=5, Criteria1:="Number"
    LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
    .Range("A1:A" & LastRow).SpecialCells(xlCellTypeVisible).EntireRow.Copy _
            Destination:=Sheets("Sheet2").Range("A1")
End With
End Sub

As a side note, your code has more loops and counter variables than necessary. You wouldn't need to loop through the columns, just through the rows. You'd then check the various cells of interest in that row, much like you did.

error: RPC failed; curl transfer closed with outstanding read data remaining

Network connection problems.
Maybe due to the persistent connection timeout.
The best way is to change to another network.

Plot yerr/xerr as shaded region rather than error bars

Ignoring the smooth interpolation between points in your example graph (that would require doing some manual interpolation, or just have a higher resolution of your data), you can use pyplot.fill_between():

from matplotlib import pyplot as plt
import numpy as np

x = np.linspace(0, 30, 30)
y = np.sin(x/6*np.pi)
error = np.random.normal(0.1, 0.02, size=y.shape)
y += np.random.normal(0, 0.1, size=y.shape)

plt.plot(x, y, 'k-')
plt.fill_between(x, y-error, y+error)
plt.show()

enter image description here

See also the matplotlib examples.

Python: Maximum recursion depth exceeded

You can increment the stack depth allowed - with this, deeper recursive calls will be possible, like this:

import sys
sys.setrecursionlimit(10000) # 10000 is an example, try with different values

... But I'd advise you to first try to optimize your code, for instance, using iteration instead of recursion.

Simple jQuery, PHP and JSONP example?

To make the server respond with a valid JSONP array, wrap the JSON in brackets () and preprend the callback:

echo $_GET['callback']."([{'fullname' : 'Jeff Hansen'}])";

Using json_encode() will convert a native PHP array into JSON:

$array = array(
    'fullname' => 'Jeff Hansen',
    'address' => 'somewhere no.3'
);
echo $_GET['callback']."(".json_encode($array).")";

Phone validation regex

This regex matches any number with the common format 1-(999)-999-9999 and anything in between. Also, the regex will allow braces or no braces and separations with period, space or dash. "^([01][- .])?(\(\d{3}\)|\d{3})[- .]?\d{3}[- .]\d{4}$"

Code coverage for Jest built on top of Jasmine

I had the same issue and I fixed it as below.

  1. install yarn npm install --save-dev yarn
  2. install jest-cli npm install --save-dev jest-cli
  3. add this to the package.json "jest-coverage": "yarn run jest -- --coverage"

After you write the tests, run the command npm run jest-coverage. This will create a coverage folder in the root directory. /coverage/icov-report/index.html has the HTML view of the code coverage.

Populate a Drop down box from a mySQL table in PHP

After a while of research and disappointments....I was able to make this up

     <?php $conn = new mysqli('hostname', 'username', 'password','dbname') or die ('Cannot connect to db') $result = $conn->query("select * from table");?>

//insert the below code in the body


    <table id="myTable"> <tr class="header"> <th style="width:20%;">Name</th>
    <th style="width:20%;">Email</th>
       <th style="width:10%;">City/ Region</th>
        <th style="width:30%;">Details</th>
  </tr>
  <?php
   while ($row = mysqli_fetch_array($result)) {

               echo "<tr>";
               echo "<td>".$row['username']."</td>";
               echo "<td>".$row['city']."</td>";
                echo "<td>".$row['details']."</td>";
               echo "</tr>";
           }

     ?>
</table>

Trust me it works :)

Run a shell script with an html button

This is how it look like in pure bash

cat /usr/lib/cgi-bin/index.cgi

#!/bin/bash
echo Content-type: text/html
echo ""
## make POST and GET stings
## as bash variables available
if [ ! -z $CONTENT_LENGTH ] && [ "$CONTENT_LENGTH" -gt 0 ] && [ $CONTENT_TYPE != "multipart/form-data" ]; then
read -n $CONTENT_LENGTH POST_STRING <&0
eval `echo "${POST_STRING//;}"|tr '&' ';'`
fi
eval `echo "${QUERY_STRING//;}"|tr '&' ';'`

echo  "<!DOCTYPE html>"
echo  "<html>"
echo  "<head>"
echo  "</head>"

if [[ "$vote" = "a" ]];then
echo "you pressed A"
  sudo /usr/local/bin/run_a.sh
elif [[ "$vote" = "b" ]];then
echo "you pressed B"
  sudo /usr/local/bin/run_b.sh
fi

echo  "<body>"
echo  "<div id=\"content-container\">"
echo  "<div id=\"content-container-center\">"
echo  "<form id=\"choice\" name='form' method=\"POST\" action=\"/\">"
echo  "<button id=\"a\" type=\"submit\" name=\"vote\" class=\"a\" value=\"a\">A</button>"
echo  "<button id=\"b\" type=\"submit\" name=\"vote\" class=\"b\" value=\"b\">B</button>"
echo  "</form>"
echo  "<div id=\"tip\">"
echo  "</div>"
echo  "</div>"
echo  "</div>"
echo  "</div>"
echo  "</body>"
echo  "</html>"

Build with https://github.com/tinoschroeter/bash_on_steroids

Java: Integer equals vs. ==

You can't compare two Integer with a simple == they're objects so most of the time references won't be the same.

There is a trick, with Integer between -128 and 127, references will be the same as autoboxing uses Integer.valueOf() which caches small integers.

If the value p being boxed is true, false, a byte, a char in the range \u0000 to \u007f, or an int or short number between -128 and 127, then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.


Resources :

On the same topic :

Does Enter key trigger a click event?

Here is the correct SOLUTION! Since the button doesn't have a defined attribute type, angular maybe attempting to issue the keyup event as a submit request and triggers the click event on the button.

<button type="button" ...></button>

Big thanks to DeborahK!

Angular2 - Enter Key executes first (click) function present on the form

Java optional parameters

If you are planning to use an interface with multiple parameters, one can use the following structural pattern and implement or override apply - a method based on your requirement.

public abstract class Invoker<T> {
    public T apply() {
        return apply(null);
    }
    public abstract T apply(Object... params);
}

What's the difference between “mod” and “remainder”?

Does '%' mean either "mod" or "rem" in C?

In C, % is the remainder1.

..., the result of the / operator is the algebraic quotient with any fractional part discarded ... (This is often called "truncation toward zero".) C11dr §6.5.5 6

The operands of the % operator shall have integer type. C11dr §6.5.5 2

The result of the / operator is the quotient from the division of the first operand by the second; the result of the % operator is the remainder ... C11dr §6.5.5 5


What's the difference between “mod” and “remainder”?

C does not define "mod", such as the integer modulus function used in Euclidean division or other modulo. "Euclidean mod" differs from C's a%b operation when a is negative.

 // a % b
 7 %  3 -->  1  
 7 % -3 -->  1  
-7 %  3 --> -1  
-7 % -3 --> -1   

Modulo as Euclidean division

 7 modulo  3 -->  1  
 7 modulo -3 -->  1  
-7 modulo  3 -->  2  
-7 modulo -3 -->  2   

Candidate modulo code:

int modulo_Euclidean(int a, int b) {
  int m = a % b;
  if (m < 0) {
    // m += (b < 0) ? -b : b; // avoid this form: it is UB when b == INT_MIN
    m = (b < 0) ? m - b : m + b;
  }
  return m;
}

Note about floating point: double fmod(double x, double y), even though called "fmod", it is not the same as Euclidean division "mod", but similar to C integer remainder:

The fmod functions compute the floating-point remainder of x/y. C11dr §7.12.10.1 2

fmod( 7,  3) -->  1.0  
fmod( 7, -3) -->  1.0  
fmod(-7,  3) --> -1.0  
fmod(-7, -3) --> -1.0   

Disambiguation: C also has a similar named function double modf(double value, double *iptr) which breaks the argument value into integral and fractional parts, each of which has the same type and sign as the argument. This has little to do with the "mod" discussion here except name similarity.


[Edit Dec 2020]

For those who want proper functionality in all cases, an improved modulo_Euclidean() that 1) detects mod(x,0) and 2) a good and no UB result with modulo_Euclidean2(INT_MIN, -1). Inspired by 4 different implementations of modulo with fully defined behavior.

int modulo_Euclidean2(int a, int b) {
  if (b == 0) TBD_Code(); // perhaps return -1 to indicate failure?
  if (b == -1) return 0; // This test needed to prevent UB of `INT_MIN % -1`.
  int m = a % b;
  if (m < 0) {
    // m += (b < 0) ? -b : b; // avoid this form: it is UB when b == INT_MIN
    m = (b < 0) ? m - b : m + b;
  }
  return m;
}

1 Prior to C99, C's definition of % was still the remainder from division, yet then / allowed negative quotients to round down rather than "truncation toward zero". See Why do you get different values for integer division in C89?. Thus with some pre-C99 compilation, % code can act just like the Euclidean division "mod". The above modulo_Euclidean() will work with this alternate old-school remainder too.

Refused to display in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'

For embeding youtube video into your angularjs page, you can simply use following filter for your video

_x000D_
_x000D_
app.filter('scrurl', function($sce) {_x000D_
    return function(text) {_x000D_
        text = text.replace("watch?v=", "embed/");_x000D_
        return $sce.trustAsResourceUrl(text);_x000D_
    };_x000D_
});
_x000D_
<iframe class="ytplayer" type="text/html" width="100%" height="360" src="{{youtube_url | scrurl}}" frameborder="0"></iframe>
_x000D_
_x000D_
_x000D_

How to implement a FSM - Finite State Machine in Java

Here is a SUPER SIMPLE implementation/example of a FSM using just "if-else"s which avoids all of the above subclassing answers (taken from Using Finite State Machines for Pattern Matching in Java, where he is looking for a string which ends with "@" followed by numbers followed by "#"--see state graph here):

public static void main(String[] args) {
    String s = "A1@312#";
    String digits = "0123456789";
    int state = 0;
    for (int ind = 0; ind < s.length(); ind++) {
        if (state == 0) {
            if (s.charAt(ind) == '@')
                state = 1;
        } else {
            boolean isNumber = digits.indexOf(s.charAt(ind)) != -1;
            if (state == 1) {
                if (isNumber)
                    state = 2;
                else if (s.charAt(ind) == '@')
                    state = 1;
                else
                    state = 0;
            } else if (state == 2) {
                if (s.charAt(ind) == '#') {
                    state = 3;
                } else if (isNumber) {
                    state = 2;
                } else if (s.charAt(ind) == '@')
                    state = 1;
                else
                    state = 0;
            } else if (state == 3) {
                if (s.charAt(ind) == '@')
                    state = 1;
                else
                    state = 0;
            }
        }
    } //end for loop

    if (state == 3)
        System.out.println("It matches");
    else
        System.out.println("It does not match");
}

P.S: Does not answer your question directly, but shows you how to implement a FSM very easily in Java.

How do I decode a string with escaped unicode?

Note that the use of unescape() is deprecated and doesn't work with the TypeScript compiler, for example.

Based on radicand's answer and the comments section below, here's an updated solution:

var string = "http\\u00253A\\u00252F\\u00252Fexample.com";
decodeURIComponent(JSON.parse('"' + string.replace(/\"/g, '\\"') + '"'));

http://example.com

Simple pthread! C++

From the pthread function prototype:

int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
    void *(*start_routine)(void*), void *arg);

The function passed to pthread_create must have a prototype of

void* name(void *arg)

Get checkbox value in jQuery

$('.class[value=3]').prop('checked', true);

What is Model in ModelAndView from Spring MVC?

new ModelAndView("welcomePage", "WelcomeMessage", message);

is shorthand for

ModelAndView mav = new ModelAndView();
mav.setViewName("welcomePage");
mav.addObject("WelcomeMessage", message);

Looking at the code above, you can see the view name is "welcomePage". Your ViewResolver (usually setup in .../WEB-INF/spring-servlet.xml) will translate this into a View. The last line of the code sets an attribute in your model (addObject("WelcomeMessage", message)). That's where the model comes into play.

Get event listeners attached to node using addEventListener

I can't find a way to do this with code, but in stock Firefox 64, events are listed next to each HTML entity in the Developer Tools Inspector as noted on MDN's Examine Event Listeners page and as demonstrated in this image:

screen shot of FF Inspector

How to include a child object's child object in Entity Framework 5

If you include the library System.Data.Entity you can use an overload of the Include() method which takes a lambda expression instead of a string. You can then Select() over children with Linq expressions rather than string paths.

return DatabaseContext.Applications
     .Include(a => a.Children.Select(c => c.ChildRelationshipType));

Null pointer Exception on .setOnClickListener

Submit is null because it is not part of activity_main.xml

When you call findViewById inside an Activity, it is going to look for a View inside your Activity's layout.

try this instead :

Submit = (Button)loginDialog.findViewById(R.id.Submit);

Another thing : you use

android:layout_below="@+id/LoginTitle"

but what you want is probably

android:layout_below="@id/LoginTitle"

See this question about the difference between @id and @+id.

How to export JavaScript array info to csv (on client side)?

Create a blob with the csv data .ie var blob = new Blob([data], type:"text/csv");

If the browser supports saving of blobs i.e if window.navigator.mSaveOrOpenBlob)===true, then save the csv data using: window.navigator.msSaveBlob(blob, 'filename.csv')

If the browser doesn't support saving and opening of blobs, then save csv data as:

var downloadLink = document.createElement('<a></a>');
downloadLink.attr('href', window.URL.createObjectURL(blob));
downloadLink.attr('download', filename);
downloadLink.attr('target', '_blank');
document.body.append(downloadLink);

Full Code snippet:

var filename = 'data_'+(new Date()).getTime()+'.csv';
var charset = "utf-8";
var blob = new Blob([data], {
     type: "text/csv;charset="+ charset + ";"
});
if (window.navigator.msSaveOrOpenBlob) {
     window.navigator.msSaveBlob(blob, filename);
} else {
    var downloadLink = document.element('<a></a>');
    downloadLink.attr('href', window.URL.createObjectURL(blob));
    downloadLink.attr('download', filename);
    downloadLink.attr('target', '_blank');  
    document.body.append(downloadLink); 
    downloadLink[0].click(); 
}

PHP get domain name

Similar question has been asked in stackoverflow before.

See here: PHP $_SERVER['HTTP_HOST'] vs. $_SERVER['SERVER_NAME'], am I understanding the man pages correctly?

Also see this article: http://shiflett.org/blog/2006/mar/server-name-versus-http-host

Recommended using HTTP_HOST, and falling back on SERVER_NAME only if HTTP_HOST was not set. He said that SERVER_NAME could be unreliable on the server for a variety of reasons, including:

  • no DNS support
  • misconfigured
  • behind load balancing software

Source: http://discussion.dreamhost.com/thread-4388.html

DataFrame constructor not properly called! error

You are providing a string representation of a dict to the DataFrame constructor, and not a dict itself. So this is the reason you get that error.

So if you want to use your code, you could do:

df = DataFrame(eval(data))

But better would be to not create the string in the first place, but directly putting it in a dict. Something roughly like:

data = []
for row in result_set:
    data.append({'value': row["tag_expression"], 'key': row["tag_name"]})

But probably even this is not needed, as depending on what is exactly in your result_set you could probably:

  • provide this directly to a DataFrame: DataFrame(result_set)
  • or use the pandas read_sql_query function to do this for you (see docs on this)

Resource interpreted as Document but transferred with MIME type application/json warning in Chrome Developer Tools

This type of warnings are usually flagged because of the request HTTP headers. Specifically the Accept request header. The MDN documentation for HTTP headers states

The Accept request HTTP header advertises which content types, expressed as MIME types, the client is able to understand. Using content negotiation, the server then selects one of the proposals, uses it and informs the client of its choice with the Content-Type response header. Browsers set adequate values for this header depending of the context where the request is done....

application/json is probably not on the list of MIME types in the Accept header sent by the browser hence the warning.

Solution

Custom HTTP headers can only be sent programmatically via XMLHttpRequest or any of the js library wrappers implementing it.

How to include Authorization header in cURL POST HTTP Request in PHP?

use "Content-type: application/x-www-form-urlencoded" instead of "application/json"

Is there a way to add/remove several classes in one single instruction with classList?

To add class to a element

document.querySelector(elem).className+=' first second third';

UPDATE:

Remove a class

document.querySelector(elem).className=document.querySelector(elem).className.split(class_to_be_removed).join(" ");

Arrays in type script

You can also do this as well (shorter cut) instead of having to do instance declaration. You do this in JSON instead.

class Book {
    public BookId: number;
    public Title: string;
    public Author: string;
    public Price: number;
    public Description: string;
}

var bks: Book[] = [];

 bks.push({BookId: 1, Title:"foo", Author:"foo", Price: 5, Description: "foo"});   //This is all done in JSON.

Unable to obtain LocalDateTime from TemporalAccessor when parsing LocalDateTime (Java 8)

If the date String does not include any value for hours, minutes and etc you cannot directly convert this to a LocalDateTime. You can only convert it to a LocalDate, because the string only represent the year,month and date components it would be the correct thing to do.

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMdd");
LocalDate ld = LocalDate.parse("20180306", dtf); // 2018-03-06

Anyway you can convert this to LocalDateTime.

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMdd");
LocalDate ld = LocalDate.parse("20180306", dtf);
LocalDateTime ldt = LocalDateTime.of(ld, LocalTime.of(0,0)); // 2018-03-06T00:00

Float sum with javascript

(parseFloat('2.3') + parseFloat('2.4')).toFixed(1);

its going to give you solution i suppose

Efficient SQL test query or validation query that will work across all (or most) databases

How about

SELECT user()

I use this before.MySQL, H2 is OK, I don't know others.

Using onBlur with JSX and React

There are a few problems here.

1: onBlur expects a callback, and you are calling renderPasswordConfirmError and using the return value, which is null.

2: you need a place to render the error.

3: you need a flag to track "and I validating", which you would set to true on blur. You can set this to false on focus if you want, depending on your desired behavior.

handleBlur: function () {
  this.setState({validating: true});
},
render: function () {
  return <div>
    ...
    <input
        type="password"
        placeholder="Password (confirm)"
        valueLink={this.linkState('password2')}
        onBlur={this.handleBlur}
     />
    ...
    {this.renderPasswordConfirmError()}
  </div>
},
renderPasswordConfirmError: function() {
  if (this.state.validating && this.state.password !== this.state.password2) {
    return (
      <div>
        <label className="error">Please enter the same password again.</label>
      </div>
    );
  }  
  return null;
},

How can I check if mysql is installed on ubuntu?

"mysql" may be found even if mysql and mariadb is uninstalled, but not "mysqld".

Faster than rpm -qa | grep mysqld is:

which mysqld

Java 8 lambdas, Function.identity() or t->t

From the JDK source:

static <T> Function<T, T> identity() {
    return t -> t;
}

So, no, as long as it is syntactically correct.

Can I have multiple primary keys in a single table?

A table can have multiple candidate keys. Each candidate key is a column or set of columns that are UNIQUE, taken together, and also NOT NULL. Thus, specifying values for all the columns of any candidate key is enough to determine that there is one row that meets the criteria, or no rows at all.

Candidate keys are a fundamental concept in the relational data model.

It's common practice, if multiple keys are present in one table, to designate one of the candidate keys as the primary key. It's also common practice to cause any foreign keys to the table to reference the primary key, rather than any other candidate key.

I recommend these practices, but there is nothing in the relational model that requires selecting a primary key among the candidate keys.

How can I get my Android device country code without using GPS?

The checked answer has deprecated code. You need to implement this:

String locale;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    locale = context.getResources().getConfiguration().getLocales().get(0).getCountry();
} else {
    locale = context.getResources().getConfiguration().locale.getCountry();
}

How can I disable editing cells in a WPF Datagrid?

If you want to disable editing the entire grid, you can set IsReadOnly to true on the grid. If you want to disable user to add new rows, you set the property CanUserAddRows="False"

<DataGrid IsReadOnly="True" CanUserAddRows="False" />

Further more you can set IsReadOnly on individual columns to disable editing.

Append same text to every cell in a column in Excel

Select the range of cells, type in the value and press Ctrl + Enter.

This, of course, is true if you want to do it manually.

How to return first 5 objects of Array in Swift?

let a: [Int] = [0, 0, 1, 1, 2, 2, 3, 3, 4]
let b: [Int] = Array(a.prefix(5))
// result is [0, 0, 1, 1, 2]

Parse strings to double with comma and point

The problem is that you (or the system) cannot distinguish a decimal separator from a thousands separator when they can be both a comma or dot. For example:

In my culture,

1.123 is a normal notation for a number above 1000; whereas

1,123 is a number near 1.

Using the invariant culture defaults to using the dot as a decimal separator. In general you should ensure that all numbers are written using the same constant culture on all systems (e.g. the invariant culture).

If you are sure that your numbers never contain anything other than a comma or dot for a decimal separator (i.e. no thousands separators), I'd String.Replace() the comma with a dot and do the rest as you did.

Otherwise, you'll have a hard time programming something that can distinguish 1.123 from 1,123 without knowing the culture.

how to hide keyboard after typing in EditText in android?

Solution included in the EditText action listenner:

public void onCreate(Bundle savedInstanceState) {
    ...
    ...
    edittext = (EditText) findViewById(R.id.EditText01);
    edittext.setOnEditorActionListener(new OnEditorActionListener() {
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (event != null&& (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                in.hideSoftInputFromWindow(edittext.getApplicationWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);
            }
            return false;
        }
    });
    ...
    ...
}

How to detect window.print() finish

Implementing window.onbeforeprint and window.onafterprint

The window.close() call after the window.print() is not working in Chrome v 78.0.3904.70

To approach this I'm using Adam's answer with a simple modification:

     function print() {
    (function () {
       let afterPrintCounter = !!window.chrome ? 0 : 1;
       let beforePrintCounter = !!window.chrome ? 0 : 1;
       var beforePrint = function () {
          beforePrintCounter++;
          if (beforePrintCounter === 2) {
             console.log('Functionality to run before printing.');
          }
       };
       var afterPrint = function () {
          afterPrintCounter++;
          if (afterPrintCounter === 2) {
             console.log('Functionality to run after printing.');
             //window.close();
          }
       };
       if (window.matchMedia) {
          var mediaQueryList = window.matchMedia('print');
          mediaQueryList.addListener(function (mql) {
             if (mql.matches) {
                beforePrint();
             } else {
                afterPrint();
             }
          });
       }
       window.onbeforeprint = beforePrint;
       window.onafterprint = afterPrint;
    }());
    //window.print(); //To print the page when it is loaded
 }

I'm calling it in here:

<body onload="print();">

This works for me. Note that I use a counter for both functions, so that I can handle this event in different browsers (fires twice in Chrome, and one time in Mozilla). For detecting the browser you can refer to this answer

Can a java file have more than one class?

Yes you can have more than one class inside a .java file. At most one of them can be public. The others are package-private. They CANNOT be private or protected. If one is public, the file must have the name of that class. Otherwise ANYTHING can be given to that file as its name.

Having many classes inside one file means those classes are in the same package. So any other classes which are inside that package but not in that file can also use those classes. Moreover, when that package is imported, importing class can use them as well.

For a more detailed investigation, you can visit my blog post in here.

Laravel 5.4 ‘cross-env’ Is Not Recognized as an Internal or External Command

The following worked for Laravel 7.x (and should probably work for any other version as well given the nature of the issue).

npm uninstall --save-dev cross-env
npm install -g cross-env

Just moving cross-env from being a local devDependency to a globally available package.

Freemarker iterating over hashmap keys

For completeness, it's worth mentioning there's a decent handling of empty collections in Freemarker since recently.

So the most convenient way to iterate a map is:

<#list tags>
<ul class="posts">
    <#items as tagName, tagCount>
        <li>{$tagName} (${tagCount})</li>
    </#items>
</ul>
<#else>
    <p>No tags found.</p>
</#list>

No more <#if ...> wrappers.

oracle varchar to number

If you want formated number then use

SELECT TO_CHAR(number, 'fmt')
   FROM DUAL;

SELECT TO_CHAR('123', 999.99)
   FROM DUAL;

Result 123.00

Why .NET String is immutable?

Strings are not really immutable. They are just publicly immutable. It means you cannot modify them from their public interface. But in the inside the are actually mutable.

If you don't believe me look at the String.Concat definition using reflector. The last lines are...

int length = str0.Length;
string dest = FastAllocateString(length + str1.Length);
FillStringChecked(dest, 0, str0);
FillStringChecked(dest, length, str1);
return dest;

As you can see the FastAllocateString returns an empty but allocated string and then it is modified by FillStringChecked

Actually the FastAllocateString is an extern method and the FillStringChecked is unsafe so it uses pointers to copy the bytes.

Maybe there are better examples but this is the one I have found so far.

jQuery Datepicker close datepicker after selected date

actually you don't need to replace this all....

there are 2 ways to do this. One is to use autoclose property, the other (alternativ) way is to use the on change property thats fired by the input when selecting a Date.

HTML

<div class="container">
    <div class="hero-unit">
        <input type="text" placeholder="Sample 1: Click to show datepicker" id="example1">
    </div>
    <div class="hero-unit">
        <input type="text" placeholder="Sample 2: Click to show datepicker" id="example2">
    </div>
</div>

jQuery

$(document).ready(function () {
    $('#example1').datepicker({
        format: "dd/mm/yyyy",
        autoclose: true
    });

    //Alternativ way
    $('#example2').datepicker({
      format: "dd/mm/yyyy"
    }).on('change', function(){
        $('.datepicker').hide();
    });

});

this is all you have to do :)

HERE IS A FIDDLE to see whats happening.

Fiddleupdate on 13 of July 2016: CDN wasnt present anymore

According to your EDIT:

$('#example1').datepicker().on('changeDate', function (ev) {
    $('#example1').Close();
});

Here you take the Input (that has no Close-Function) and create a Datepicker-Element. If the element changes you want to close it but you still try to close the Input (That has no close-function).

Binding a mouseup event to the document state may not be the best idea because you will fire all containing scripts on each click!

Thats it :)

EDIT: August 2017 (Added a StackOverFlowFiddle aka Snippet. Same as in Top of Post)

_x000D_
_x000D_
$(document).ready(function () {_x000D_
    $('#example1').datepicker({_x000D_
        format: "dd/mm/yyyy",_x000D_
        autoclose: true_x000D_
    });_x000D_
_x000D_
    //Alternativ way_x000D_
    $('#example2').datepicker({_x000D_
      format: "dd/mm/yyyy"_x000D_
    }).on('change', function(){_x000D_
        $('.datepicker').hide();_x000D_
    });_x000D_
});
_x000D_
.hero-unit{_x000D_
  float: left;_x000D_
  width: 210px;_x000D_
  margin-right: 25px;_x000D_
}_x000D_
.hero-unit input{_x000D_
  width: 100%;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>_x000D_
<div class="container">_x000D_
    <div class="hero-unit">_x000D_
        <input type="text" placeholder="Sample 1: Click to show datepicker" id="example1">_x000D_
    </div>_x000D_
    <div class="hero-unit">_x000D_
        <input type="text" placeholder="Sample 2: Click to show datepicker" id="example2">_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

EDIT: December 2018 Obviously Bootstrap-Datepicker doesnt work with jQuery 3.x see this to fix

How to convert An NSInteger to an int?

I'm not sure about the circumstances where you need to convert an NSInteger to an int.

NSInteger is just a typedef:

NSInteger Used to describe an integer independently of whether you are building for a 32-bit or a 64-bit system.

#if __LP64__ || TARGET_OS_EMBEDDED || TARGET_OS_IPHONE || TARGET_OS_WIN32 || NS_BUILD_32_LIKE_64 
typedef long NSInteger;
#else
typedef int NSInteger;
#endif

You can use NSInteger any place you use an int without converting it.

How to compute precision, recall, accuracy and f1-score for the multiclass case with scikit learn?

I think there is a lot of confusion about which weights are used for what. I am not sure I know precisely what bothers you so I am going to cover different topics, bear with me ;).

Class weights

The weights from the class_weight parameter are used to train the classifier. They are not used in the calculation of any of the metrics you are using: with different class weights, the numbers will be different simply because the classifier is different.

Basically in every scikit-learn classifier, the class weights are used to tell your model how important a class is. That means that during the training, the classifier will make extra efforts to classify properly the classes with high weights.
How they do that is algorithm-specific. If you want details about how it works for SVC and the doc does not make sense to you, feel free to mention it.

The metrics

Once you have a classifier, you want to know how well it is performing. Here you can use the metrics you mentioned: accuracy, recall_score, f1_score...

Usually when the class distribution is unbalanced, accuracy is considered a poor choice as it gives high scores to models which just predict the most frequent class.

I will not detail all these metrics but note that, with the exception of accuracy, they are naturally applied at the class level: as you can see in this print of a classification report they are defined for each class. They rely on concepts such as true positives or false negative that require defining which class is the positive one.

             precision    recall  f1-score   support

          0       0.65      1.00      0.79        17
          1       0.57      0.75      0.65        16
          2       0.33      0.06      0.10        17
avg / total       0.52      0.60      0.51        50

The warning

F1 score:/usr/local/lib/python2.7/site-packages/sklearn/metrics/classification.py:676: DeprecationWarning: The 
default `weighted` averaging is deprecated, and from version 0.18, 
use of precision, recall or F-score with multiclass or multilabel data  
or pos_label=None will result in an exception. Please set an explicit 
value for `average`, one of (None, 'micro', 'macro', 'weighted', 
'samples'). In cross validation use, for instance, 
scoring="f1_weighted" instead of scoring="f1".

You get this warning because you are using the f1-score, recall and precision without defining how they should be computed! The question could be rephrased: from the above classification report, how do you output one global number for the f1-score? You could:

  1. Take the average of the f1-score for each class: that's the avg / total result above. It's also called macro averaging.
  2. Compute the f1-score using the global count of true positives / false negatives, etc. (you sum the number of true positives / false negatives for each class). Aka micro averaging.
  3. Compute a weighted average of the f1-score. Using 'weighted' in scikit-learn will weigh the f1-score by the support of the class: the more elements a class has, the more important the f1-score for this class in the computation.

These are 3 of the options in scikit-learn, the warning is there to say you have to pick one. So you have to specify an average argument for the score method.

Which one you choose is up to how you want to measure the performance of the classifier: for instance macro-averaging does not take class imbalance into account and the f1-score of class 1 will be just as important as the f1-score of class 5. If you use weighted averaging however you'll get more importance for the class 5.

The whole argument specification in these metrics is not super-clear in scikit-learn right now, it will get better in version 0.18 according to the docs. They are removing some non-obvious standard behavior and they are issuing warnings so that developers notice it.

Computing scores

Last thing I want to mention (feel free to skip it if you're aware of it) is that scores are only meaningful if they are computed on data that the classifier has never seen. This is extremely important as any score you get on data that was used in fitting the classifier is completely irrelevant.

Here's a way to do it using StratifiedShuffleSplit, which gives you a random splits of your data (after shuffling) that preserve the label distribution.

from sklearn.datasets import make_classification
from sklearn.cross_validation import StratifiedShuffleSplit
from sklearn.metrics import accuracy_score, f1_score, precision_score, recall_score, classification_report, confusion_matrix

# We use a utility to generate artificial classification data.
X, y = make_classification(n_samples=100, n_informative=10, n_classes=3)
sss = StratifiedShuffleSplit(y, n_iter=1, test_size=0.5, random_state=0)
for train_idx, test_idx in sss:
    X_train, X_test, y_train, y_test = X[train_idx], X[test_idx], y[train_idx], y[test_idx]
    svc.fit(X_train, y_train)
    y_pred = svc.predict(X_test)
    print(f1_score(y_test, y_pred, average="macro"))
    print(precision_score(y_test, y_pred, average="macro"))
    print(recall_score(y_test, y_pred, average="macro"))    

Hope this helps.

Python - add PYTHONPATH during command line module run

You may try this to execute a function inside your script

python -c "import sys; sys.path.append('/your/script/path'); import yourscript; yourscript.yourfunction()"

How can I directly view blobs in MySQL Workbench

there is few things that you can do

SELECT GROUP_CONCAT(CAST(name AS CHAR))
FROM product
WHERE  id   IN (12345,12346,12347)

If you want to order by the query you can order by cast as well like below

SELECT GROUP_CONCAT(name ORDER BY name))
FROM product
WHERE id   IN (12345,12346,12347)

as it says on this blog

http://www.kdecom.com/mysql-group-concat-blob-bug-solved/

How can I change column types in Spark SQL's DataFrame?

[EDIT: March 2016: thanks for the votes! Though really, this is not the best answer, I think the solutions based on withColumn, withColumnRenamed and cast put forward by msemelman, Martin Senne and others are simpler and cleaner].

I think your approach is ok, recall that a Spark DataFrame is an (immutable) RDD of Rows, so we're never really replacing a column, just creating new DataFrame each time with a new schema.

Assuming you have an original df with the following schema:

scala> df.printSchema
root
 |-- Year: string (nullable = true)
 |-- Month: string (nullable = true)
 |-- DayofMonth: string (nullable = true)
 |-- DayOfWeek: string (nullable = true)
 |-- DepDelay: string (nullable = true)
 |-- Distance: string (nullable = true)
 |-- CRSDepTime: string (nullable = true)

And some UDF's defined on one or several columns:

import org.apache.spark.sql.functions._

val toInt    = udf[Int, String]( _.toInt)
val toDouble = udf[Double, String]( _.toDouble)
val toHour   = udf((t: String) => "%04d".format(t.toInt).take(2).toInt ) 
val days_since_nearest_holidays = udf( 
  (year:String, month:String, dayOfMonth:String) => year.toInt + 27 + month.toInt-12
 )

Changing column types or even building a new DataFrame from another can be written like this:

val featureDf = df
.withColumn("departureDelay", toDouble(df("DepDelay")))
.withColumn("departureHour",  toHour(df("CRSDepTime")))
.withColumn("dayOfWeek",      toInt(df("DayOfWeek")))              
.withColumn("dayOfMonth",     toInt(df("DayofMonth")))              
.withColumn("month",          toInt(df("Month")))              
.withColumn("distance",       toDouble(df("Distance")))              
.withColumn("nearestHoliday", days_since_nearest_holidays(
              df("Year"), df("Month"), df("DayofMonth"))
            )              
.select("departureDelay", "departureHour", "dayOfWeek", "dayOfMonth", 
        "month", "distance", "nearestHoliday")            

which yields:

scala> df.printSchema
root
 |-- departureDelay: double (nullable = true)
 |-- departureHour: integer (nullable = true)
 |-- dayOfWeek: integer (nullable = true)
 |-- dayOfMonth: integer (nullable = true)
 |-- month: integer (nullable = true)
 |-- distance: double (nullable = true)
 |-- nearestHoliday: integer (nullable = true)

This is pretty close to your own solution. Simply, keeping the type changes and other transformations as separate udf vals make the code more readable and re-usable.

Tomcat won't stop or restart

I faced the same problem as mentioned below.

PID file found but no matching process was found. Stop aborted.

Solution is to find the free space of the linux machine by using the following command

df -h

The above command shows my home directory was 100% used. Then identified which files to be removed by using the following command

du -h .

After removing, it was able to perform IO operation on the linux machine and the tomcat was able to start.

Centering FontAwesome icons vertically and horizontally

This is all you need, no wrapper needed:

.login-icon{
    display:inline-block;
    font-size: 40px;
    line-height: 50px;
    background-color:black;
    color:white;
    width: 50px;
    height: 50px;
    text-align: center;
    vertical-align: bottom;
}

http://jsfiddle.net/e2UPC/6/

What's the location of the JavaFX runtime JAR file, jfxrt.jar, on Linux?

The location of jfxrt.jar in Oracle Java 7 is:

<JRE_HOME>/lib/jfxrt.jar

The location of jfxrt.jar in Oracle Java 8 is:

<JRE_HOME>/lib/ext/jfxrt.jar

The <JRE_HOME> will depend on where you installed the Oracle Java and may differ between Linux distributions and installations.

jfxrt.jar is not in the Linux OpenJDK 7 (which is what you are using).


An open source package which provides JavaFX 8 for Debian based systems such as Ubuntu is available. To install this package it is necessary to install both the Debian OpenJDK 8 package and the Debian OpenJFX package. I don't run Debian, so I'm not sure where the Debian OpenJFX package installs jfxrt.jar.


Use Oracle Java 8.

With Oracle Java 8, JavaFX is both included in the JDK and is on the default classpath. This means that JavaFX classes will automatically be found both by the compiler during the build and by the runtime when your users use your application. So using Oracle Java 8 is currently the best solution to your issue.

OpenJDK for Java 8 could include JavaFX (as JavaFX for Java 8 is now open source), but it will depend on the OpenJDK package assemblers as to whether they choose to include JavaFX 8 with their distributions. I hope they do, as it should help remove the confusion you experienced in your question and it also provides a great deal more functionality in OpenJDK.

My understanding is that although JavaFX has been included with the standard JDK since version JDK 7u6

Yes, but only the Oracle JDK.

The JavaFX version bundled with Java 7 was not completely open source so it could not be included in the OpenJDK (which is what you are using).

In you need to use Java 7 instead of Java 8, you could download the Oracle JDK for Java 7 and use that. Then JavaFX will be included with Java 7. Due to the way Oracle configured Java 7, JavaFX won't be on the classpath. If you use Java 7, you will need to add it to your classpath and use appropriate JavaFX packaging tools to allow your users to run your application. Some tools such as e(fx)clipse and NetBeans JavaFX project type will take care of classpath issues and packaging tasks for you.

Getting the actual usedrange

Timings on Excel 2013 fairly slow machine with a big bad used range million rows:

26ms Cells.Find xlPrevious method (as above)

0.4ms Sheet.UsedRange (just call it)

0.14ms Counta binary search + 0.4ms Used Range to start search (12 CountA calls)

So the Find xlPrevious is quite slow if that is of concern.

The CountA binary search approach is to first do a Used Range. Then chop the range in half and see if there are any non-empty cells in the bottom half, and then halve again as needed. It is tricky to get right.

Pandas groupby: How to get a union of strings

You could try this:

df.groupby('A').agg({'B':'sum','C':'-'.join})

wp-admin shows blank page, how to fix it?

Try turning on WP Debug. If this is happening due to a PHP error (which I bet that it is), you will be able to see what's going on and fix the error.

What is the meaning of <> in mysql query?

<> means not equal to, != also means not equal to.

Documentation

PHP Try and Catch for SQL Insert

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

I am not sure if there is a mysql version of this but adding this line of code allows throwing mysqli_sql_exception.
I know, passed a lot of time and the question is already checked answered but I got a different answer and it may be helpful.

ImportError: No module named pythoncom

You are missing the pythoncom package. It comes with ActivePython but you can get it separately on GitHub (previously on SourceForge) as part of pywin32.

You can also simply use:

pip install pywin32

postgresql duplicate key violates unique constraint

The primary key is already protecting you from inserting duplicate values, as you're experiencing when you get that error. Adding another unique constraint isn't necessary to do that.

The "duplicate key" error is telling you that the work was not done because it would produce a duplicate key, not that it discovered a duplicate key already commited to the table.

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

This: "Disconnected: No supported authentication methods available (server sent: publickey)" happened to me after I turned on Microsoft One Drive backup and sync for my files including the directory where I saved my ssh key. In my case the solution is simple: just go to Putty => SSH => Auth and just (re)browse again to where my same key is located and saved, then it worked. It looks backup and sync software such as Microsoft One Drive (and may be the same with Google Drive), affect the way Putty sees and identifies directories if the key directory is specified and then later some time installing or turning on backup and sync including that directory.

Created Button Click Event c#

if your button is inside your form class:

buttonOk.Click += new EventHandler(your_click_method);

(might not be exactly EventHandler)

and in your click method:

this.Close();

If you need to show a message box:

MessageBox.Show("test");

In Flask, What is request.args and how is it used?

request.args is a MultiDict with the parsed contents of the query string. From the documentation of get method:

get(key, default=None, type=None)

Return the default value if the requested data doesn’t exist. If type is provided and is a callable it should convert the value, return it or raise a ValueError if that is not possible.

Set folder browser dialog start location

Set the SelectedPath property before you call ShowDialog ...

folderBrowserDialog1.SelectedPath = @"c:\temp\";
folderBrowserDialog1.ShowDialog();

Will start them at C:\Temp

Show ProgressDialog Android

While creating the object for the progressbar check the following.

This fails:

dialog = new ProgressDialog(getApplicationContext());

While adding the activities context works..

dialog = new ProgressDialog(MainActivity.this);

Put a Delay in Javascript

If you're okay with ES2017, await is good:

const DEF_DELAY = 1000;

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms || DEF_DELAY));
}

await sleep(100);

Note that the await part needs to be in an async function:

//IIAFE (immediately invoked async function expression)
(async()=>{
  //Do some stuff
  await sleep(100);
  //Do some more stuff
})()

Leading zeros for Int in Swift

in Xcode 8.3.2, iOS 10.3 Thats is good to now

Sample1:

let dayMoveRaw = 5 
let dayMove = String(format: "%02d", arguments: [dayMoveRaw])
print(dayMove) // 05

Sample2:

let dayMoveRaw = 55 
let dayMove = String(format: "%02d", arguments: [dayMoveRaw])
print(dayMove) // 55

Learning to write a compiler

  1. This is a vast subject. Do not underestimate this point. And do not underestimate my point to not underestimate it.
  2. I hear the Dragon Book is a (the?) place to start, along with searching. :) Get better at searching, eventually it will be your life.
  3. Building your own programming language is absolutely a good exercise! But know that it will never be used for any practical purpose in the end. Exceptions to this are few and very far between.

Ternary operator (?:) in Bash

[ $b == 5 ] && { a=$c; true; } || a=$d

This will avoid executing the part after || by accident when the code between && and || fails.

How to add a tooltip to an svg graphic?

I always go with the generic css title with my setup. I'm just building analytics for my blog admin page. I don't need anything fancy. Here's some code...

let comps = g.selectAll('.myClass')
   .data(data)
   .enter()
   .append('rect')
   ...styling...
   ...transitions...
   ...whatever...

g.selectAll('.myClass')
   .append('svg:title')
   .text((d, i) => d.name + '-' + i);

And a screenshot of chrome...

enter image description here

Accessing localhost of PC from USB connected Android mobile device

Google posted a solution for this kind of problem here.

The steps:

  • Connect your Android device and your development machine with USB debugging enabled
  • Open Chrome in your development machine, open new tab, right click in the new browser tab, click inspect
  • Click the three dots icon on right top side three dots, -> More Tools, Remote Devices.
  • Look at bottom of the screen, make sure your device name is appeared on the list with Green colored dot.
  • Look below at the settings part, check the Port forwarding mark
  • Add rule. Example, if your python web server is running on your machine localhost:5000 and you want to access it from your device port 3333, you type 3333 on the left part, and type localhost:5000, and click add rule.
  • Voila, now you can access your web server from your device. Try open new browser tab, and visit http://localhost:3333 from your device

Using prepared statements with JDBCTemplate

Try the following:

PreparedStatementCreator creator = new PreparedStatementCreator() {
    @Override
    public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
        PreparedStatement updateSales = con.prepareStatement(
        "UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ? ");
        updateSales.setInt(1, 75); 
        updateSales.setString(2, "Colombian"); 
        return updateSales;
    }
};

Adding values to Arraylist

The second one would be preferred:

  • it avoids unnecessary/inefficient constructor calls
  • it makes you specify the element type for the list (if that is missing, you get a warning)

However, having two different types of object in the same list has a bit of a bad design smell. We need more context to speak on that.

inject bean reference into a Quartz job in Spring?

You can use this SpringBeanJobFactory to automatically autowire quartz objects using spring:

import org.quartz.spi.TriggerFiredBundle;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.scheduling.quartz.SpringBeanJobFactory;

public final class AutowiringSpringBeanJobFactory extends SpringBeanJobFactory implements
    ApplicationContextAware {

    private transient AutowireCapableBeanFactory beanFactory;

    @Override
    public void setApplicationContext(final ApplicationContext context) {
        beanFactory = context.getAutowireCapableBeanFactory();
    }

    @Override
    protected Object createJobInstance(final TriggerFiredBundle bundle) throws Exception {
        final Object job = super.createJobInstance(bundle);
        beanFactory.autowireBean(job);
        return job;
    }
}

Then, attach it to your SchedulerBean (in this case, with Java-config):

@Bean
public SchedulerFactoryBean quartzScheduler() {
    SchedulerFactoryBean quartzScheduler = new SchedulerFactoryBean();

    ...

    AutowiringSpringBeanJobFactory jobFactory = new AutowiringSpringBeanJobFactory();
    jobFactory.setApplicationContext(applicationContext);
    quartzScheduler.setJobFactory(jobFactory);

    ...

    return quartzScheduler;
}

Working for me, using spring-3.2.1 and quartz-2.1.6.

Check out the complete gist here.

I found the solution in this blog post

Detect whether current Windows version is 32 bit or 64 bit

Interestingly, if I use

get-wmiobject -class Win32_Environment -filter "Name='PROCESSOR_ARCHITECTURE'"

I get AMD64 in both 32-bit and 64-bit ISE (on Win7 64-bit).

python int( ) function

Integers (int for short) are the numbers you count with 0, 1, 2, 3 ... and their negative counterparts ... -3, -2, -1 the ones without the decimal part.

So once you introduce a decimal point, your not really dealing with integers. You're dealing with rational numbers. The Python float or decimal types are what you want to represent or approximate these numbers.

You may be used to a language that automatically does this for you(Php). Python, though, has an explicit preference for forcing code to be explicit instead implicit.

How to create a cron job using Bash automatically without the interactive editor?

No, there is no option in crontab to modify the cron files.

You have to: take the current cron file (crontab -l > newfile), change it and put the new file in place (crontab newfile).

If you are familiar with perl, you can use this module Config::Crontab.

LLP, Andrea

Why does ASP.NET webforms need the Runat="Server" attribute?

Microsoft Msdn article The Forgotten Controls: HTML Server Controls explains use of runat="server" with an example on text box <input type="text"> by converting it to <input type="text" id="Textbox1" runat="server">

Doing this will give you programmatic access to the HTML element on the server before the Web page is created and sent down to the client. The HTML element must contain an id attribute. This attribute serves as an identity for the element and enables you to program to elements by their specific IDs. In addition to this attribute, the HTML element must contain runat="server". This tells the processing server that the tag is processed on the server and is not to be considered a traditional HTML element.

In short, to enable programmatic access to the HTML element add runat="server" to it.

How can I show three columns per row?

Try this one using Grid Layout:

_x000D_
_x000D_
.grid-container {_x000D_
  display: grid;_x000D_
  grid-template-columns: auto auto auto;_x000D_
  padding: 10px;_x000D_
}_x000D_
.grid-item {_x000D_
  background-color: rgba(255, 255, 255, 0.8);_x000D_
  border: 1px solid rgba(0, 0, 0, 0.8);_x000D_
  padding: 20px;_x000D_
  font-size: 30px;_x000D_
  text-align: center;_x000D_
}
_x000D_
<div class="grid-container">_x000D_
  <div class="grid-item">1</div>_x000D_
  <div class="grid-item">2</div>_x000D_
  <div class="grid-item">3</div>  _x000D_
  <div class="grid-item">4</div>_x000D_
  <div class="grid-item">5</div>_x000D_
  <div class="grid-item">6</div>  _x000D_
  <div class="grid-item">7</div>_x000D_
  <div class="grid-item">8</div>_x000D_
  <div class="grid-item">9</div>  _x000D_
</div>
_x000D_
_x000D_
_x000D_

Call Class Method From Another Class

You can call a function from within a class with:

A().method1()

How do I get the day month and year from a Windows cmd.exe script?

I have converted to using Powershell calls for this purpose in my scripts. It requires script execution permission and is by far the slowest option. However it is also localization independent, very easy to write and read, and it is much more feasible to perform adjustments to the date like addition/subtraction or get the last day of the month, etc.

Here is how to get the day, month, and year

for /f %%i in ('"powershell (Get-Date).ToString(\"dd\")"') do set day=%%i
for /f %%i in ('"powershell (Get-Date).ToString(\"MM\")"') do set month=%%i
for /f %%i in ('"powershell (Get-Date).ToString(\"yyyy\")"') do set year=%%i

Or, here is yesterday's date in yyyy-MM-dd format

for /f %%i in ('"powershell (Get-Date).AddDays(-1).ToString(\"yyyy-MM-dd\")"') do set yesterday=%%i

Day of the week

for /f %%d in ('"powershell (Get-Date).DayOfWeek"') do set DayOfWeek=%%d

Current time plus 15 minutes

for /f %%i in ('"powershell (Get-Date).AddMinutes(15).ToString(\"HH:mm\")"') do set time=%%i

How to keep the local file or the remote file during merge using Git and the command line?

You can as well do:

git checkout --theirs /path/to/file

to keep the remote file, and:

git checkout --ours /path/to/file

to keep local file.

Then git add them and everything is done.

Edition: Keep in mind that this is for a merge scenario. During a rebase --theirs refers to the branch where you've been working.

PyCharm error: 'No Module' when trying to import own module (python script)

Pycharm 2017.1.1

  1. Click on View->ToolBar & View->Tool Buttons
  2. On the left pane Project would be visible, right click on it and press Autoscroll to source and then run your code.

This worked for me.

How to copy a char array in C?

None of the above was working for me.. this works perfectly name here is char *name which is passed via the function

  1. get length of char *name using strlen(name)
  2. storing it in a const variable is important
  3. create same length size char array
  4. copy name 's content to temp using strcpy(temp, name);

use however you want, if you want original content back. strcpy(name, temp); copy temp back to name and voila works perfectly

    const int size = strlen(name);
    char temp[size];
    cout << size << endl;
    strcpy(temp, name);

Declare variable in SQLite and use it

For a read-only variable (that is, a constant value set once and used anywhere in the query), use a Common Table Expression (CTE).

WITH const AS (SELECT 'name' AS name, 10 AS more)
SELECT table.cost, (table.cost + const.more) AS newCost
FROM table, const 
WHERE table.name = const.name

SQLite WITH clause

How to create an ArrayList from an Array in PowerShell?

Probably the shortest version:

[System.Collections.ArrayList]$someArray

It is also faster because it does not call relatively expensive New-Object.

Why can't I reference my class library?

I faced this problem, and I solved it by closing visual studio, reopening visual studio, cleaning and rebuilding the solution. This worked for me.

Sqlite convert string to date

The UDF approach is my preference compared to brittle substr values.

#!/usr/bin/env python3
import sqlite3
from dateutil import parser
from pprint import pprint


def date_parse(s):
    ''' Converts a string to a date '''
    try:
        t = parser.parse(s, parser.parserinfo(dayfirst=True))
        return t.strftime('%Y-%m-%d')
    except:
        return None


def dict_factory(cursor, row):
    ''' Helper for dict row results '''
    d = {}
    for idx, col in enumerate(cursor.description):
        d[col[0]] = row[idx]
    return d


def main():
    ''' Demonstrate UDF '''
    with sqlite3.connect(":memory:") as conn:
        conn.row_factory = dict_factory
        setup(conn)

        ##################################################
        # This is the code that matters. The rest is setup noise.
        conn.create_function("date_parse", 1, date_parse)
        cur = conn.cursor()
        cur.execute(''' select "date", date_parse("date") as parsed from _test order by 2; ''')
        pprint(cur.fetchall())
        ##################################################

def setup(conn):
    ''' Setup some values to parse '''
    cur = conn.cursor()

    # Make a table
    sql = '''
    create table _test (
        "id" integer primary key,
        "date" text
    );
    '''
    cur.execute(sql)

    # Fill the table
    dates = [
        '2/1/03', '03/2/04', '4/03/05', '05/04/06',
        '6/5/2007', '07/6/2008', '8/07/2009', '09/08/2010',
        '2-1-03', '03-2-04', '4-03-05', '05-04-06',
        '6-5-2007', '07-6-2008', '8-07-2009', '09-08-2010',
        '31/12/20', '31-12-2020',
        'BOMB!',
    ]
    params = [(x,) for x in dates]
    cur.executemany(''' insert into _test ("date") values(?); ''', params)


if __name__ == "__main__":
    main()

This will give you these results:

[{'date': 'BOMB!', 'parsed': None},
 {'date': '2/1/03', 'parsed': '2003-01-02'},
 {'date': '2-1-03', 'parsed': '2003-01-02'},
 {'date': '03/2/04', 'parsed': '2004-02-03'},
 {'date': '03-2-04', 'parsed': '2004-02-03'},
 {'date': '4/03/05', 'parsed': '2005-03-04'},
 {'date': '4-03-05', 'parsed': '2005-03-04'},
 {'date': '05/04/06', 'parsed': '2006-04-05'},
 {'date': '05-04-06', 'parsed': '2006-04-05'},
 {'date': '6/5/2007', 'parsed': '2007-05-06'},
 {'date': '6-5-2007', 'parsed': '2007-05-06'},
 {'date': '07/6/2008', 'parsed': '2008-06-07'},
 {'date': '07-6-2008', 'parsed': '2008-06-07'},
 {'date': '8/07/2009', 'parsed': '2009-07-08'},
 {'date': '8-07-2009', 'parsed': '2009-07-08'},
 {'date': '09/08/2010', 'parsed': '2010-08-09'},
 {'date': '09-08-2010', 'parsed': '2010-08-09'},
 {'date': '31/12/20', 'parsed': '2020-12-31'},
 {'date': '31-12-2020', 'parsed': '2020-12-31'}]

The SQLite equivalent of anything this robust is a tangled weave of substr and instr calls that you should avoid.

Why does git status show branch is up-to-date when changes exist upstream?

What the status is telling you is that you're behind the ref called origin/master which is a local ref in your local repo. In this case that ref happens to track a branch in some remote, called origin, but the status is not telling you anything about the branch on the remote. It's telling you about the ref, which is just a commit ID stored on your local filesystem (in this case, it's typically in a file called .git/refs/remotes/origin/master in your local repo).

git pull does two operations; first it does a git fetch to get up to date with the commits in the remote repo (which updates the origin/master ref in your local repo), then it does a git merge to merge those commits into the current branch.

Until you do the fetch step (either on its own or via git pull) your local repo has no way to know that there are additional commits upstream, and git status only looks at your local origin/master ref.

When git status says up-to-date, it means "up-to-date with the branch that the current branch tracks", which in this case means "up-to-date with the local ref called origin/master". That only equates to "up-to-date with the upstream status that was retrieved last time we did a fetch" which is not the same as "up-to-date with the latest live status of the upstream".

Why does it work this way? Well the fetch step is a potentially slow and expensive network operation. The design of Git (and other distributed version control systems) is to avoid network operations when unnecessary, and is a completely different model to the typical client-server system many people are used to (although as pointed out in the comments below, Git's concept of a "remote tracking branch" that causes confusion here is not shared by all DVCSs). It's entirely possible to use Git offline, with no connection to a centralized server, and the output of git status reflects this.

Creating and switching branches (and checking their status) in Git is supposed to be lightweight, not something that performs a slow network operation to a centralized system. The assumption when designing Git, and the git status output, was that users understand this (too many Git features only make sense if you already know how Git works). With the adoption of Git by lots and lots of users who are not familiar with DVCS this assumption is not always valid.

SQL DELETE with INNER JOIN

if the database is InnoDB you dont need to do joins in deletion. only

DELETE FROM spawnlist WHERE spawnlist.type = "monster";

can be used to delete the all the records that linked with foreign keys in other tables, to do that you have to first linked your tables in design time.

CREATE TABLE IF NOT EXIST spawnlist (
  npc_templateid VARCHAR(20) NOT NULL PRIMARY KEY

)ENGINE=InnoDB;

CREATE TABLE IF NOT EXIST npc (
  idTemplate VARCHAR(20) NOT NULL,

  FOREIGN KEY (idTemplate) REFERENCES spawnlist(npc_templateid) ON DELETE CASCADE

)ENGINE=InnoDB;

if you uses MyISAM you can delete records joining like this

DELETE a,b
FROM `spawnlist` a
JOIN `npc` b
ON a.`npc_templateid` = b.`idTemplate`
WHERE a.`type` = 'monster';

in first line i have initialized the two temp tables for delet the record, in second line i have assigned the existance table to both a and b but here i have linked both tables together with join keyword, and i have matched the primary and foreign key for both tables that make link, in last line i have filtered the record by field to delete.

Uncaught TypeError: Cannot read property 'toLowerCase' of undefined

It causes the error when you access $(this).val() when it called by change event this points to the invoker i.e. CourseSelect so it is working and and will get the value of CourseSelect. but when you manually call it this points to document. so either you will have to pass the CourseSelect object or access directly like $("#CourseSelect").val() instead of $(this).val().

What is Java EE?

Java EE is a collection of specifications for developing and deploying enterprise applications.

In general, enterprise applications refer to software hosted on servers that provide the applications that support the enterprise.

The specifications (defined by Sun) describe services, application programming interfaces (APIs), and protocols.

The 13 core technologies that make up Java EE are:

  1. JDBC
  2. JNDI
  3. EJBs
  4. RMI
  5. JSP
  6. Java servlets
  7. XML
  8. JMS
  9. Java IDL
  10. JTS
  11. JTA
  12. JavaMail
  13. JAF

The Java EE product provider is typically an application-server, web-server, or database-system vendor who provides classes that implement the interfaces defined in the specifications. These vendors compete on implementations of the Java EE specifications.

When a company requires Java EE experience what are they really asking for is experience using the technologies that make up Java EE. Frequently, a company will only be using a subset of the Java EE technologies.

Effective method to hide email from spam bots

Not my idea originally but I can't find the author:

<a href="mailto:[email protected]"
    onmouseover="this.href=this.href.replace(/x/g,'');">link</a>

Add as many x's as you like. It works perfectly to read, copy and paste, and can't be read by a bot.

How to vertically align label and input in Bootstrap 3?

This works perfectly for me in Bootstrap 4.

<div class="form-row align-items-center">
   <div class="col-md-2">
     <label for="FirstName" style="margin-bottom:0rem !important;">First Name</label>
 </div>
 <div class="col-md-10">
    <input type="text" id="FirstName" name="FirstName" class="form-control" val=""/>
  /div>
</div>

The project cannot be built until the build path errors are resolved.

1-Right CLick on your project folder, Choose Build Path > Configure Build Path
2-Select Libraries Tab and delete any arbitrary library present there.
3-Click on Add Library option, Select JRE System Library and click Next.
4-Choose last Radiobutton option Workspace default JRE and click Finish.
5-press f5 for refresh.
6-run ur program .

How to get DATE from DATETIME Column in SQL?

Use Getdate()

 select sum(transaction_amount) from TransactionMaster
 where Card_No=' 123' and transaction_date =convert(varchar(10), getdate(), 102)

Is there a way to get a collection of all the Models in your Rails app?

The Rails implements the method descendants, but models not necessarily ever inherits from ActiveRecord::Base, for example, the class that includes the module ActiveModel::Model will have the same behavior as a model, just doesn't will be linked to a table.

So complementing what says the colleagues above, the slightest effort would do this:

Monkey Patch of class Class of the Ruby:

class Class
  def extends? constant
    ancestors.include?(constant) if constant != self
  end
end

and the method models, including ancestors, as this:

The method Module.constants returns (superficially) a collection of symbols, instead of constants, so, the method Array#select can be substituted like this monkey patch of the Module:

class Module

  def demodulize
    splitted_trail = self.to_s.split("::")
    constant = splitted_trail.last

    const_get(constant) if defines?(constant)
  end
  private :demodulize

  def defines? constant, verbose=false
    splitted_trail = constant.split("::")
    trail_name = splitted_trail.first

    begin
      trail = const_get(trail_name) if Object.send(:const_defined?, trail_name)
      splitted_trail.slice(1, splitted_trail.length - 1).each do |constant_name|
        trail = trail.send(:const_defined?, constant_name) ? trail.const_get(constant_name) : nil
      end
      true if trail
    rescue Exception => e
      $stderr.puts "Exception recovered when trying to check if the constant \"#{constant}\" is defined: #{e}" if verbose
    end unless constant.empty?
  end

  def has_constants?
    true if constants.any?
  end

  def nestings counted=[], &block
    trail = self.to_s
    collected = []
    recursivityQueue = []

    constants.each do |const_name|
      const_name = const_name.to_s
      const_for_try = "#{trail}::#{const_name}"
      constant = const_for_try.constantize

      begin
        constant_sym = constant.to_s.to_sym
        if constant && !counted.include?(constant_sym)
          counted << constant_sym
          if (constant.is_a?(Module) || constant.is_a?(Class))
            value = block_given? ? block.call(constant) : constant
            collected << value if value

            recursivityQueue.push({
              constant: constant,
              counted: counted,
              block: block
            }) if constant.has_constants?
          end
        end
      rescue Exception
      end

    end

    recursivityQueue.each do |data|
      collected.concat data[:constant].nestings(data[:counted], &data[:block])
    end

    collected
  end

end

Monkey patch of String.

class String
  def constantize
    if Module.defines?(self)
      Module.const_get self
    else
      demodulized = self.split("::").last
      Module.const_get(demodulized) if Module.defines?(demodulized)
    end
  end
end

And, finally, the models method

def models
  # preload only models
  application.config.eager_load_paths = model_eager_load_paths
  application.eager_load!

  models = Module.nestings do |const|
    const if const.is_a?(Class) && const != ActiveRecord::SchemaMigration && (const.extends?(ActiveRecord::Base) || const.include?(ActiveModel::Model))
  end
end

private

  def application
    ::Rails.application
  end

  def model_eager_load_paths
    eager_load_paths = application.config.eager_load_paths.collect do |eager_load_path|
      model_paths = application.config.paths["app/models"].collect do |model_path|
        eager_load_path if Regexp.new("(#{model_path})$").match(eager_load_path)
      end
    end.flatten.compact
  end

removing new line character from incoming stream using sed

This might work for you:

printf "{new\nto\nlinux}" | paste -sd' '            
{new to linux}

or:

printf "{new\nto\nlinux}" | tr '\n' ' '            
{new to linux}

or:

printf "{new\nto\nlinux}" |sed -e ':a' -e '$!{' -e 'N' -e 'ba' -e '}' -e 's/\n/ /g'
{new to linux}

Detect if a browser in a mobile device (iOS/Android phone/tablet) is used

Many mobile devices have resolutions so high that it's hard to distinguish between them and much larger screens. There are two ways to deal with this problem:

Use the following HTML code to scale the pixels (grouping smaller pixels into groups the size of the unit pixel - 96dpi, so px units will have the same physical size on all screens). Note that this will affect the scale of pretty much everything in your website, but this is generally the way to go when making sites mobile-friendly.

<meta name="viewport" content="width=device-width, initial-scale=1">

Alternatively, measuring the screen width in @media queries using cm instead of px units can tell you if you're dealing with a physically small screen regardless of resolution.

Get selected element's outer HTML

Anothe similar solution with added remove() of the temporary DOM object.

javascript check for not null

Use !== as != will get you into a world of nontransitive JavaScript truth table weirdness.

How to get commit history for just one branch?

The git merge-base command can be used to find a common ancestor. So if my_experiment has not been merged into master yet and my_experiment was created from master you could:

git log --oneline `git merge-base my_experiment master`..my_experiment

How to add buttons at top of map fragment API v2 layout

Button Above The Map

If this is what you want ...simply add button inside the Fragment.

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.LocationChooser">


    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="right|top"
        android:text="Demo Button" 
        android:padding="10dp"
        android:layout_marginTop="20dp"
        android:paddingRight="10dp"/>

</fragment>

Left align block of equations

You can use \begin{flalign}, like the example bellow:

\begin{flalign}
    &f(x) = -1.25x^{2} + 1.5x&
\end{flalign}

IE8 support for CSS Media Query

An easy way to use the css3-mediaqueries-js is to include the following before the closing body tag:

<!-- css3-mediaqueries.js for IE less than 9 -->
<!--[if lt IE 9]>
<script 
   src="//css3-mediaqueries-js.googlecode.com/svn/trunk/css3-mediaqueries.js">
</script>
<![endif]-->

Android: How to enable/disable option menu item on button click?

How to update the current menu in order to enable or disable the items when an AsyncTask is done.

In my use case I needed to disable my menu while my AsyncTask was loading data, then after loading all the data, I needed to enable all the menu again in order to let the user use it.

This prevented the app to let users click on menu items while data was loading.

First, I declare a state variable , if the variable is 0 the menu is shown, if that variable is 1 the menu is hidden.

private mMenuState = 1; //I initialize it on 1 since I need all elements to be hidden when my activity starts loading.

Then in my onCreateOptionsMenu() I check for this variable , if it's 1 I disable all my items, if not, I just show them all

 @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        getMenuInflater().inflate(R.menu.menu_galeria_pictos, menu);

        if(mMenuState==1){
            for (int i = 0; i < menu.size(); i++) {
                menu.getItem(i).setVisible(false);
            }
        }else{
             for (int i = 0; i < menu.size(); i++) {
                menu.getItem(i).setVisible(true);
            }
        }

        return super.onCreateOptionsMenu(menu);
    }

Now, when my Activity starts, onCreateOptionsMenu() will be called just once, and all my items will be gone because I set up the state for them at the start.

Then I create an AsyncTask Where I set that state variable to 0 in my onPostExecute()

This step is very important!

When you call invalidateOptionsMenu(); it will relaunch onCreateOptionsMenu();

So, after setting up my state to 0, I just redraw all the menu but this time with my variable on 0 , that said, all the menu will be shown after all the asynchronous process is done, and then my user can use the menu.

 public class LoadMyGroups extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mMenuState = 1; //you can set here the state of the menu too if you dont want to initialize it at global declaration. 

        }

        @Override
        protected Void doInBackground(Void... voids) {
           //Background work

            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);

            mMenuState=0; //We change the state and relaunch onCreateOptionsMenu
            invalidateOptionsMenu(); //Relaunch onCreateOptionsMenu

        }
    }

Results

enter image description here

Java: getMinutes and getHours

java.time

While I am a fan of Joda-Time, Java 8 introduces the java.time package which is finally a worthwhile Java standard solution! Read this article, Java SE 8 Date and Time, for a good amount of information on java.time outside of hours and minutes.

In particular, look at the LocalDateTime class.

Hours and minutes:

LocalDateTime.now().getHour();
LocalDateTime.now().getMinute();

How to read file from res/raw by name

You can read files in raw/res using getResources().openRawResource(R.raw.myfilename).

BUT there is an IDE limitation that the file name you use can only contain lower case alphanumeric characters and dot. So file names like XYZ.txt or my_data.bin will not be listed in R.

WAMP server, localhost is not working

Goto This link its working..

http://www.ttkalec.com/blog/resolving-yellow-wamp-server-status-freeing-up-port-80-for-apache/

Update: Using XAMP

After I’ve written this blog post I’ve figured out that XAMP, although very similar to WAMP, doesn’t force you to run Apache as a service, instead it can run it as a regular process. So I ended up using XAMP, and changed Apache port to 8080 so now everything works.

WAMP Issues

If you have Window 7 or later you may have come across issues with WAMP server trying to start Apache service on port 80 and failing.

There are many conflict and issues that might have come up. Before you try anything, check if you have ZoneAlarm, Nod32, or any other program/firewall that might be blocking Apache server. If you’re sure that firewall isn’t the problem here is a couple of fixes that you can try.

NOTE: After every fix you try, you must click on yellow WAMP icon and choose Restart All Services

Checking which process is causing the problem

Open Command Prompt window by typing cmd in Run command box or Start Search, and hit Enter. Type in the following command: netstat -o -n -a | findstr 0.0:80 The last column of each row is the process identified (process ID or PID). Identify which process or application is using the port by matching the PID against PID number in Task Manager. If you don’t see PID column in your Task Manager you need to go to Processes tab -> View Menu -> Select Columns and choose PID from the list Now, you may have identified application that reserves port 80, or you may have found out that System is using your port 80. That means that one of internal services is using your port, in which case continue reading further. Conflict with Skype

If you found out that Skype is using your port 80, you need to change some settings in Skype. On Windows, Skype reserves port 80 which is used for HTTP. Apache requires this port. So if you’re running Skype, you must go to Tools > Options. Then in the Advanced section, select Connection. Un-check the box that says “Use port 80 and 443 as alternatives for incoming connection“. Quit Skype and restart. The issue should be resolved.

Conflict with IIS Server

IIS Server and Apache are both web server that use port 80 so they might be in conflict. Try stopping IIS by:

Going into Control Panel -> Administrative Tools -> Internet Information Services Right click on Default Web Site Click on Stop option in the popup menu, and see of the listener on port 80 has cleared. Conflict with MS SQL Server

MS SQL Server installs “SQL Server Reporting Services (MSSQLSERVER)” that apparently defaults to 80. You can try stopping it to free up port 80.

Go to Control Panel -> Administrative Tools -> Services There find MSSQLSERVER (might be found also under SQL Server) Double click it -> Click Stop Under Startup type: choose Manual Other Services that can cause conflicts

As described above for MS SQL Server:

Go to Control Panel -> Administrative Tools -> Services You can try stopping: Web Deployment Agent Service Windows Remote Management Autodesk EDM Server World Wide Web Publishing Service There are probably more of them, but this where the ones that I tryed.

Try turning off HTTP driver directly

If you’ve tried everything mentioned above and your WAMP server is still not working you could try this (which eventually helped me).

Right click on My Computer icon -> Properties Go to Device Manager Click on View menu and chooseShow hidden devices Now from the list choose Non-Plug and Play devices Double click HTTP -> go to Driver For Type choose Disabled Restart your computer After your computer boots up you should be able to start up WAMP server.

If everything else fails

You could try changing Apache server to listen to some other port other than port 80.

Click on yellow WAMP icon in your taskbar Choose Apache -> httpd.conf Inside find these two lines of code:

Listen 80 ServerName localhost:80 and change them to something like this (they are not one next to the other):

Listen 8080 ServerName localhost:8080 Restart all services, and try typing localhost:8080 into your browser. WAMP server should now be working.

Remove blank lines with grep

I tried hard, but this seems to work (assuming \r is biting you here):

printf "\r" | egrep -xv "[[:space:]]*"

Why is the apt-get function not working in the terminal on Mac OS X v10.9 (Mavericks)?

Conda can also be used as package manager. It can be installed from Anaconda.

Alternatively, a free minimal installer is Miniconda.

How to get the path of the batch script in Windows?

You can use following script to get the path without trailing "\"

for %%i in ("%~dp0.") do SET "mypath=%%~fi"

Can there be an apostrophe in an email address?

Yes, according to RFC 3696 apostrophes are valid as long as they come before the @ symbol.

"Least Astonishment" and the Mutable Default Argument

Every other answer explains why this is actually a nice and desired behavior, or why you shouldn't be needing this anyway. Mine is for those stubborn ones who want to exercise their right to bend the language to their will, not the other way around.

We will "fix" this behavior with a decorator that will copy the default value instead of reusing the same instance for each positional argument left at its default value.

import inspect
from copy import copy

def sanify(function):
    def wrapper(*a, **kw):
        # store the default values
        defaults = inspect.getargspec(function).defaults # for python2
        # construct a new argument list
        new_args = []
        for i, arg in enumerate(defaults):
            # allow passing positional arguments
            if i in range(len(a)):
                new_args.append(a[i])
            else:
                # copy the value
                new_args.append(copy(arg))
        return function(*new_args, **kw)
    return wrapper

Now let's redefine our function using this decorator:

@sanify
def foo(a=[]):
    a.append(5)
    return a

foo() # '[5]'
foo() # '[5]' -- as desired

This is particularly neat for functions that take multiple arguments. Compare:

# the 'correct' approach
def bar(a=None, b=None, c=None):
    if a is None:
        a = []
    if b is None:
        b = []
    if c is None:
        c = []
    # finally do the actual work

with

# the nasty decorator hack
@sanify
def bar(a=[], b=[], c=[]):
    # wow, works right out of the box!

It's important to note that the above solution breaks if you try to use keyword args, like so:

foo(a=[4])

The decorator could be adjusted to allow for that, but we leave this as an exercise for the reader ;)

PHP - remove <img> tag from string

I wanted to display the first 300 words of a news story as a preview which unfortunately meant that if a story had an image within the first 300 words then it was displayed in the list of previews which really messed with my layout. I used the above code to hide all of the images from the string taken from my database and it works wonderfully!

$news = $row_latest_news ['content'];
$news = preg_replace("/<img[^>]+\>/i", "", $news); 
if (strlen($news) > 300){
echo substr($news, 0, strpos($news,' ',300)).'...';
} 
else { 
echo $news; 
}

The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256

In Java I had to set a property

System.setProperty(SDKGlobalConfiguration.ENFORCE_S3_SIGV4_SYSTEM_PROPERTY, "true")

and add the region to the s3Client instance.

s3Client.setRegion(Region.getRegion(Regions.EU_CENTRAL_1))

A process crashed in windows .. Crash dump location

http://support.microsoft.com/kb/931673

There are Registry changes you can make to explicitly select where the crash dump file resides, otherwise %localappdata%\Microsoft\Windows\WER is the default location. I assume that %localappdata% is defined differently for a user or a service running under System. You will need to enable WER I believe.

Nginx no-www to www and www to no-www

Ghost blog

in order to make nginx recommended method with return 301 $scheme://example.com$request_uri; work with Ghost you will need to add in your main server block:

proxy_set_header    X-Real-IP           $remote_addr;
proxy_set_header    X-Forwarded-For     $proxy_add_x_forwarded_for;
proxy_set_header    Host                $http_host;
proxy_set_header    X-Forwarded-Proto   $scheme;
proxy_set_header    X-NginX-Proxy       true;

proxy_pass_header   X-CSRF-TOKEN;
proxy_buffering     off;
proxy_redirect      off;  

Can a local variable's memory be accessed outside its scope?

Because the storage space wasn't stomped on just yet. Don't count on that behavior.

How do I remove objects from an array in Java?

Something about the make a list of it then remove then back to an array strikes me as wrong. Haven't tested, but I think the following will perform better. Yes I'm probably unduly pre-optimizing.

boolean [] deleteItem = new boolean[arr.length];
int size=0;
for(int i=0;i<arr.length;i==){
   if(arr[i].equals("a")){
      deleteItem[i]=true;
   }
   else{
      deleteItem[i]=false;
      size++;
   }
}
String[] newArr=new String[size];
int index=0;
for(int i=0;i<arr.length;i++){
   if(!deleteItem[i]){
      newArr[index++]=arr[i];
   }
}

How do I get bootstrap-datepicker to work with Bootstrap 3?

For anyone else who runs into this...

Version 1.2.0 of this plugin (current as of this post) doesn't quite work in all cases as documented with Bootstrap 3.0, but it does with a minor workaround.

Specifically, if using an input with icon, the HTML markup is of course slightly different as class names have changed:

<div class="input-group" data-datepicker="true">
    <input name="date" type="text" class="form-control" />
    <span class="input-group-addon"><i class="icon-calendar"></i></span>
</div>

It seems because of this, you need to use a selector that points directly to the input element itself NOT the parent container (which is what the auto generated HTML on the demo page suggests).

$('*[data-datepicker="true"] input[type="text"]').datepicker({
    todayBtn: true,
    orientation: "top left",
    autoclose: true,
    todayHighlight: true
});

Having done this you will probably also want to add a listener for clicking/tapping on the icon so it sets focus on the text input when clicked (which is the behaviour when using this plugin with TB 2.x by default).

$(document).on('touch click', '*[data-datepicker="true"] .input-group-addon', function(e){
    $('input[type="text"]', $(this).parent()).focus();
});

NB: I just use a data-datepicker boolean attribute because the class name 'datepicker' is reserved by the plugin and I already use 'date' for styling elements.

How to get device make and model on iOS?

Below is the code for that (code may not contain all device's string, I'm with other guys are maintaining the same code on GitHub so please take the latest code from there)

Objective-C : GitHub/DeviceUtil

Swift : GitHub/DeviceGuru


#include <sys/types.h>
#include <sys/sysctl.h>

- (NSString*)hardwareDescription {
    NSString *hardware = [self hardwareString];
    if ([hardware isEqualToString:@"iPhone1,1"]) return @"iPhone 2G";
    if ([hardware isEqualToString:@"iPhone1,2"]) return @"iPhone 3G";
    if ([hardware isEqualToString:@"iPhone3,1"]) return @"iPhone 4";
    if ([hardware isEqualToString:@"iPhone4,1"]) return @"iPhone 4S";
    if ([hardware isEqualToString:@"iPhone5,1"]) return @"iPhone 5";
    if ([hardware isEqualToString:@"iPod1,1"]) return @"iPodTouch 1G";
    if ([hardware isEqualToString:@"iPod2,1"]) return @"iPodTouch 2G";
    if ([hardware isEqualToString:@"iPad1,1"]) return @"iPad";
    if ([hardware isEqualToString:@"iPad2,6"]) return @"iPad Mini";
    if ([hardware isEqualToString:@"iPad4,1"]) return @"iPad Air WIFI";
    //there are lots of other strings too, checkout the github repo
    //link is given at the top of this answer

    if ([hardware isEqualToString:@"i386"]) return @"Simulator";
    if ([hardware isEqualToString:@"x86_64"]) return @"Simulator";

    return nil;
}

- (NSString*)hardwareString {
    size_t size = 100;
    char *hw_machine = malloc(size);
    int name[] = {CTL_HW,HW_MACHINE};
    sysctl(name, 2, hw_machine, &size, NULL, 0);
    NSString *hardware = [NSString stringWithUTF8String:hw_machine];
    free(hw_machine);
    return hardware;
}

Insert into C# with SQLCommand

You should avoid hardcoding SQL statements in your application. If you don't use ADO nor EntityFramework, I would suggest you to ad a stored procedure to the database and call it from your c# application. A sample code can be found here: How to execute a stored procedure within C# program and here http://msdn.microsoft.com/en-us/library/ms171921%28v=vs.80%29.aspx.

Maven: how to override the dependency added by a library

What you put inside the </dependencies> tag of the root pom will be included by all child modules of the root pom. If all your modules use that dependency, this is the way to go.

However, if only 3 out of 10 of your child modules use some dependency, you do not want this dependency to be included in all your child modules. In that case, you can just put the dependency inside the </dependencyManagement>. This will make sure that any child module that needs the dependency must declare it in their own pom file, but they will use the same version of that dependency as specified in your </dependencyManagement> tag.

You can also use the </dependencyManagement> to modify the version used in transitive dependencies, because the version declared in the upper most pom file is the one that will be used. This can be useful if your project A includes an external project B v1.0 that includes another external project C v1.0. Sometimes it happens that a security breach is found in project C v1.0 which is corrected in v1.1, but the developers of B are slow to update their project to use v1.1 of C. In that case, you can simply declare a dependency on C v1.1 in your project's root pom inside `, and everything will be good (assuming that B v1.0 will still be able to compile with C v1.1).

jQuery Validate Plugin - Trigger validation of single field

This method seems to do what you want:

$('#email-field-only').valid();

jQuery select option elements by value

$("#h273yrjdfhgsfyiruwyiywer").children('[value="' + i + '"]').prop("selected", true);

Bitbucket fails to authenticate on git pull

I know that this is an old question, but I thought I would provide the solution that worked for me. I signed up for bitbucket using my google account and did not have a password. Turns out the password is my Atlassian account password. If you have an Atlassian account then try this password to see if it works.

Create PostgreSQL ROLE (user) if it doesn't exist

As you are on 9.x, you can wrap that into a DO statement:

do 
$body$
declare 
  num_users integer;
begin
   SELECT count(*) 
     into num_users
   FROM pg_user
   WHERE usename = 'my_user';

   IF num_users = 0 THEN
      CREATE ROLE my_user LOGIN PASSWORD 'my_password';
   END IF;
end
$body$
;

How to get ELMAH to work with ASP.NET MVC [HandleError] attribute?

A completely alternative solution is to not use the MVC HandleErrorAttribute, and instead rely on ASP.Net error handling, which Elmah is designed to work with.

You need to remove the default global HandleErrorAttribute from App_Start\FilterConfig (or Global.asax), and then set up an error page in your Web.config:

<customErrors mode="RemoteOnly" defaultRedirect="~/error/" />

Note, this can be an MVC routed URL, so the above would redirect to the ErrorController.Index action when an error occurs.

Apply formula to the entire column

Found another solution:

  • Apply the formula to the first 3 or 4 cells of the column
  • Ctrl + C the formula in one of the last rows (if you copy the first line it won't work)
  • Click on the column header to select the whole column
  • Press Ctrl + V to paste it in all cells bellow

Error when trying vagrant up

Check Homestead.yaml file carefully.Check if there is any extra space character after line ends. Then, open gitbash -> go Homestead directory -> command "vagrant up --provision".

Java URLConnection Timeout

You can set timeouts for all connections made from the jvm by changing the following System-properties:

System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
System.setProperty("sun.net.client.defaultReadTimeout", "10000");

Every connection will time out after 10 seconds.

Setting 'defaultReadTimeout' is not needed, but shown as an example if you need to control reading.

Docker - Container is not running

For anyone attempting something similar using a Dockerfile...

Running in detached mode won't help. The container will always exit (stop running) if the command is non-blocking, this is the case with bash.

In this case, a workaround would be: 1. Commit the resulting image: (container_name = the name of the container you want to base the image off of, image_name = the name of the image to be created docker commit container_name image_name 2. Use docker run to create a new container using the new image, specifying the command you want to run. Here, I will run "bash": docker run -it image_name bash

This would get you the interactive login you're looking for.

Add a month to a Date

Vanilla R has a naive difftime class, but the Lubridate CRAN package lets you do what you ask:

require(lubridate)
d <- ymd(as.Date('2004-01-01')) %m+% months(1)
d
[1] "2004-02-01"

Hope that helps.

Oracle DB : java.sql.SQLException: Closed Connection

It means the connection was successfully established at some point, but when you tried to commit right there, the connection was no longer open. The parameters you mentioned sound like connection pool settings. If so, they're unrelated to this problem. The most likely cause is a firewall between you and the database that is killing connections after a certain amount of idle time. The most common fix is to make your connection pool run a validation query when a connection is checked out from it. This will immediately identify and evict dead connnections, ensuring that you only get good connections out of the pool.

Should methods in a Java interface be declared with or without a public access modifier?

I prefer skipping it, I read somewhere that interfaces are by default, public and abstract.

To my surprise the book - Head First Design Patterns, is using public with interface declaration and interface methods... that made me rethink once again and I landed up on this post.

Anyways, I think redundant information should be ignored.

Type List vs type ArrayList in Java

For example you might decide a LinkedList is the best choice for your application, but then later decide ArrayList might be a better choice for performance reason.

Use:

List list = new ArrayList(100); // will be better also to set the initial capacity of a collection 

Instead of:

ArrayList list = new ArrayList();

For reference:

enter image description here

(posted mostly for Collection diagram)

The I/O operation has been aborted because of either a thread exit or an application request

In my case, the request was getting timed out. So all you need to do is to increase the time out while creating the HttpClient.

HttpClient client = new HttpClient();

client.Timeout = TimeSpan.FromMinutes(5);

How should I choose an authentication library for CodeIgniter?

Note that the "comprehensive listing" by Jens Roland doesn't include user roles. If you're interested in assigning different user roles (like admin/user or admin/editor/user), these libraries allow it:

  • Ion_Auth (rewrite of Redux)
  • Redux
  • Backend Pro

Tank_Auth (#1 above in Jens's list) doesn't have user roles. I realize it's not exactly part of authentication, but since

  • authentication and role management are both handled upon page load
  • Both involve security
  • The same table/model can be used for both.
  • Both can be set up to load in the controller constructor (or even autoload)

It makes a LOT of sense to have one library to handle both, if you need it. I'm switching to Ion_Auth from Tank_Auth because of this.

Why does git say "Pull is not possible because you have unmerged files"?

You are attempting to add one more new commits into your local branch while your working directory is not clean. As a result, Git is refusing to do the pull. Consider the following diagrams to better visualize the scenario:

remote: A <- B <- C <- D
local: A <- B*
(*indicates that you have several files which have been modified but not committed.)

There are two options for dealing with this situation. You can either discard the changes in your files, or retain them.

Option one: Throw away the changes
You can either use git checkout for each unmerged file, or you can use git reset --hard HEAD to reset all files in your branch to HEAD. By the way, HEAD in your local branch is B, without an asterisk. If you choose this option, the diagram becomes:

remote: A <- B <- C <- D
local: A <- B

Now when you pull, you can fast-forward your branch with the changes from master. After pulling, you branch would look like master:

local: A <- B <- C <- D

Option two: Retain the changes
If you want to keep the changes, you will first want to resolve any merge conflicts in each of the files. You can open each file in your IDE and look for the following symbols:

<<<<<<< HEAD
// your version of the code
=======
// the remote's version of the code
>>>>>>>

Git is presenting you with two versions of code. The code contained within the HEAD markers is the version from your current local branch. The other version is what is coming from the remote. Once you have chosen a version of the code (and removed the other code along with the markers), you can add each file to your staging area by typing git add. The final step is to commit your result by typing git commit -m with an appropriate message. At this point, our diagram looks like this:

remote: A <- B <- C <- D
local: A <- B <- C'

Here I have labelled the commit we just made as C' because it is different from the commit C on the remote. Now, if you try to pull you will get a non-fast forward error. Git cannot play the changes in remote on your branch, because both your branch and the remote have diverged from the common ancestor commit B. At this point, if you want to pull you can either do another git merge, or git rebase your branch on the remote.

Getting a mastery of Git requires being able to understand and manipulate uni-directional linked lists. I hope this explanation will get you thinking in the right direction about using Git.

CSS: how to add white space before element's content?

Since you are looking for adding space between elements you may need something as simple as a margin-left or padding-left. Here are examples of both http://jsfiddle.net/BGHqn/3/

This will add 10 pixels to the left of the paragraph element

p {
    margin-left: 10px;
 }

or if you just want some padding within your paragraph element

p {
    padding-left: 10px;
}

Are 'Arrow Functions' and 'Functions' equivalent / interchangeable?

Arrow functions => best ES6 feature so far. They are a tremendously powerful addition to ES6, that I use constantly.

Wait, you can't use arrow function everywhere in your code, its not going to work in all cases like this where arrow functions are not usable. Without a doubt, the arrow function is a great addition it brings code simplicity.

But you can’t use an arrow function when a dynamic context is required: defining methods, create objects with constructors, get the target from this when handling events.

Arrow functions should NOT be used because:

  1. They do not have this

    It uses “lexical scoping” to figure out what the value of “this” should be. In simple word lexical scoping it uses “this” from the inside the function’s body.

  2. They do not have arguments

    Arrow functions don’t have an arguments object. But the same functionality can be achieved using rest parameters.

    let sum = (...args) => args.reduce((x, y) => x + y, 0) sum(3, 3, 1) // output - 7 `

  3. They cannot be used with new

    Arrow functions can't be construtors because they do not have a prototype property.

When to use arrow function and when not:

  1. Don't use to add function as a property in object literal because we can not access this.
  2. Function expressions are best for object methods. Arrow functions are best for callbacks or methods like map, reduce, or forEach.
  3. Use function declarations for functions you’d call by name (because they’re hoisted).
  4. Use arrow functions for callbacks (because they tend to be terser).

Return value using String result=Command.ExecuteScalar() error occurs when result returns null

You can use like the following

string result = null;
object value = cmd.ExecuteScalar();
 if (value != null)
 {
    result = value.ToString();
 }     
 conn.Close();
return result;

Delete all items from a c++ std::vector

Adding to the above mentioned benefits of swap(). That clear() does not guarantee deallocation of memory. You can use swap() as follows:

std::vector<T>().swap(myvector);

How do I create a ListView with rounded corners in Android?

Yet another solution to selection highlight problems with first, and last items in the list:

Add padding to the top and bottom of your list background equal to or greater than the radius. This ensures the selection highlighting doesn't overlap with your corner curves.

This is the easiest solution when you need non-transparent selection highlighting.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
    <solid android:color="@color/listbg" />
    <stroke
        android:width="2dip"
        android:color="#D5D5D5" />
    <corners android:radius="10dip" />

    <!-- Make sure bottom and top padding match corner radius -->
    <padding
        android:bottom="10dip"
        android:left="2dip"
        android:right="2dip"
        android:top="10dip" />
</shape>

Access-Control-Allow-Origin Multiple Origin Domains?

Here is what i did for a PHP application which is being requested by AJAX

$request_headers        = apache_request_headers();
$http_origin            = $request_headers['Origin'];
$allowed_http_origins   = array(
                            "http://myDumbDomain.example"   ,
                            "http://anotherDumbDomain.example"  ,
                            "http://localhost"  ,
                          );
if (in_array($http_origin, $allowed_http_origins)){  
    @header("Access-Control-Allow-Origin: " . $http_origin);
}

If the requesting origin is allowed by my server, return the $http_origin itself as value of the Access-Control-Allow-Origin header instead of returning a * wildcard.

Bind a function to Twitter Bootstrap Modal Close

Starting Bootstrap 3 (edit: still the same in Bootstrap 4) there are 2 instances in which you can fire up events, being:

1. When modal "hide" event starts

$('#myModal').on('hide.bs.modal', function () { 
    console.log('Fired at start of hide event!');
});  

2. When modal "hide" event finished

$('#myModal').on('hidden.bs.modal', function () {
    console.log('Fired when hide event has finished!');
});

Ref: http://getbootstrap.com/javascript/#js-events

No module named pkg_resources

I fixed the error with virtualenv by doing this:

Copied pkg_resources.py from

/Library/Python/2.7/site-packages/setuptools

to

/Library/Python/2.7/site-packages/

This may be a cheap workaround, but it worked for me.

.

If setup tools doesn't exist, you can try installing system-site-packages by typing virtualenv --system-site-packages /DESTINATION DIRECTORY, changing the last part to be the directory you want to install to. pkg_rousources.py will be under that directory in lib/python2.7/site-packages

How to develop Android app completely using python?

To answer your first question: yes it is feasible to develop an android application in pure python, in order to achieve this I suggest you use BeeWare, which is just a suite of python tools, that work together very well and they enable you to develop platform native applications in python.

checkout this video by the creator of BeeWare that perfectly explains and demonstrates it's application

How it works

Android's preferred language of implementation is Java - so if you want to write an Android application in Python, you need to have a way to run your Python code on a Java Virtual Machine. This is what VOC does. VOC is a transpiler - it takes Python source code, compiles it to CPython Bytecode, and then transpiles that bytecode into Java-compatible bytecode. The end result is that your Python source code files are compiled directly to a Java .class file, which can be packaged into an Android application.

VOC also allows you to access native Java objects as if they were Python objects, implement Java interfaces with Python classes, and subclass Java classes with Python classes. Using this, you can write an Android application directly against the native Android APIs.

Once you've written your native Android application, you can use Briefcase to package your Python code as an Android application.

Briefcase is a tool for converting a Python project into a standalone native application. You can package projects for:

  • Mac
  • Windows
  • Linux
  • iPhone/iPad
  • Android
  • AppleTV
  • tvOS.

You can check This native Android Tic Tac Toe app written in Python, using the BeeWare suite. on GitHub

in addition to the BeeWare tools, you'll need to have a JDK and Android SDK installed to test run your application.

and to answer your second question: a good environment can be anything you are comfortable with be it a text editor and a command line, or an IDE, if you're looking for a good python IDE I would suggest you try Pycharm, it has a community edition which is free, and it has a similar environment as android studio, due to to the fact that were made by the same company.

I hope this has been helpful

How do I clone into a non-empty directory?

I had a similar problem with a new Apache web directory (account created with WHM) that I planned to use as a staging web server. I needed to initially clone my new project with the code base there and periodically deploy changes by pulling from repository.

The problem was that the account already contained web server files like:

.bash_history
.bash_logout
.bash_profile
.bashrc
.contactemail
.cpanel/
...

...that I did not want to either delete or commit to my repository. I needed them to just stay there unstaged and untracked.

What I did:

I went to my web folder (existing_folder):

cd /home/existing_folder

and then:

git init
git remote add origin PATH/TO/REPO
git pull origin master
git status

It displayed (as expected) a list of many not staged files - those that already existed initially from my cPanel web account.

Then, thanks to this article, I just added the list of those files to:

**.git/info/exclude**

This file, almost like the .gitignore file, allows you to ignore files from being staged. After this I had nothing to commit in the .git/ directory - it works like a personal .gitignore that no one else can see.

Now checking git status returns:

On branch master
nothing to commit, working tree clean

Now I can deploy changes to this web server by simply pulling from my git repository. Hope this helps some web developers to easily create a staging server.

How to enumerate an enum with String type?

This problem is now much easier. Here is my Swift 4.2 Solution:

enum Suit: Int, CaseIterable {
  case None
  case Spade, Heart, Diamond, Club

  static let allNonNullCases = Suit.allCases[Spade.rawValue...]
}

enum Rank: Int, CaseIterable {
  case Joker
  case Two, Three, Four, Five, Six, Seven, Eight
  case Nine, Ten, Jack, Queen, King, Ace

  static let allNonNullCases = Rank.allCases[Two.rawValue...]
}

func makeDeck(withJoker: Bool = false) -> [Card] {
  var deck = [Card]()
  for suit in Suit.allNonNullCases {
    for rank in Rank.allNonNullCases {
      deck.append(Card(suit: suit, rank: rank))
    }
  }
  if withJoker {
    deck.append(Card(suit: .None, rank: .Joker))
  }
  return deck
}

Pre 4.2:

I like this solution which I put together after finding "List comprehension in Swift".

It uses Int raws instead of Strings but it avoids typing twice, it allows customizing the ranges, and doesn't hard code raw values.

This is a Swift 4 version of my original solution but see the 4.2 improvement above:

enum Suit: Int {
  case None
  case Spade, Heart, Diamond, Club

  static let allRawValues = Suit.Spade.rawValue...Suit.Club.rawValue
  static let allCases = Array(allRawValues.map{ Suit(rawValue: $0)! })
}
enum Rank: Int {
  case Joker
  case Two, Three, Four, Five, Six
  case Seven, Eight, Nine, Ten
  case Jack, Queen, King, Ace

  static let allRawValues = Rank.Two.rawValue...Rank.Ace.rawValue
  static let allCases = Array(allRawValues.map{ Rank(rawValue: $0)! })
}
func makeDeck(withJoker: Bool = false) -> [Card] {
  var deck = [Card]()
  for suit in Suit.allCases {
    for rank in Rank.allCases {
      deck.append(Card(suit: suit, rank: rank))
    }
  }
  if withJoker {
    deck.append(Card(suit: .None, rank: .Joker))
  }
  return deck
}

find index of an int in a list

It's even easier if you consider that the Generic List in C# is indexed from 0 like an array. This means you can just use something like:

int index = 0; int i = accounts[index];

Instantiating a generic type

You basically have two choices:

1.Require an instance:

public Navigation(T t) {     this("", "", t); } 

2.Require a class instance:

public Navigation(Class<T> c) {     this("", "", c.newInstance()); } 

You could use a factory pattern, but ultimately you'll face this same issue, but just push it elsewhere in the code.

Why isn't this code to plot a histogram on a continuous value Pandas column working?

Here's another way to plot the data, involves turning the date_time into an index, this might help you for future slicing

#convert column to datetime
trip_data['lpep_pickup_datetime'] = pd.to_datetime(trip_data['lpep_pickup_datetime'])
#turn the datetime to an index
trip_data.index = trip_data['lpep_pickup_datetime']
#Plot
trip_data['Trip_distance'].plot(kind='hist')
plt.show()

How to hide command output in Bash

A process normally has two outputs to screen: stdout (standard out), and stderr (standard error).

Normally informational messages go to sdout, and errors and alerts go to stderr.

You can turn off stdout for a command by doing

MyCommand >/dev/null

and turn off stderr by doing:

MyCommand 2>/dev/null

If you want both off, you can do:

MyCommand 2>&1 >/dev/null

The 2>&1 says send stderr to the same place as stdout.

Displaying a 3D model in JavaScript/HTML5

a couple years down the road, I'd vote for three.js because

ie 11 supports webgl (to what extent I can't assure you since i'm usually in chrome)

and, as far as importing external models into three.js, here's a link to mrdoob's updated loaders (so many!)

UPDATE nov 2019: the THREE.js loaders are now far more and it makes little sense to post them all: just go to this link

http://threejs.org/examples and review the loaders - at least 20 of them

echo key and value of an array without and with loop

A recursive function for a change;) I use it to output the media information for videos etc elements of which can use nested array / attributes.

function custom_print_array($arr = array()) {
    $output = '';
    foreach($arr as $key => $val) {
        if(is_array($val)){
            $output .= '<li><strong>' . ucwords(str_replace('_',' ', $key)) . ':</strong><ul class="children">' . custom_print_array($val) . '</ul>' . '</li>';
        }
        else {
            $output .=  '<li><strong>' . ucwords(str_replace('_',' ', $key)) . ':</strong> ' . $val . '</li>';
        }
    }
    return $output;
}

Find the 2nd largest element in an array with minimum number of comparisons

Sorry, JS code...

Tested with the two inputs:

a = [55,11,66,77,72];
a = [ 0, 12, 13, 4, 5, 32, 8 ];

var first = Number.MIN_VALUE;
var second = Number.MIN_VALUE;
for (var i = -1, len = a.length; ++i < len;) {
    var dist = a[i];
    // get the largest 2
    if (dist > first) {
        second = first;
        first = dist;
    } else if (dist > second) { // && dist < first) { // this is actually not needed, I believe
        second = dist;
    }
}

console.log('largest, second largest',first,second);
largest, second largest 32 13

This should have a maximum of a.length*2 comparisons and only goes through the list once.

javac is not recognized as an internal or external command, operable program or batch file

TL;DR

For experienced readers:

  1. Find the Java path; it looks like this: C:\Program Files\Java\jdkxxxx\bin\
  2. Start-menu search for "environment variable" to open the options dialog.
  3. Examine PATH. Remove old Java paths.
  4. Add the new Java path to PATH.
  5. Edit JAVA_HOME.
  6. Close and re-open console/IDE.

Welcome!

You have encountered one of the most notorious technical issues facing Java beginners: the 'xyz' is not recognized as an internal or external command... error message.

In a nutshell, you have not installed Java correctly. Finalizing the installation of Java on Windows requires some manual steps. You must always perform these steps after installing Java, including after upgrading the JDK.

Environment variables and PATH

(If you already understand this, feel free to skip the next three sections.)

When you run javac HelloWorld.java, cmd must determine where javac.exe is located. This is accomplished with PATH, an environment variable.

An environment variable is a special key-value pair (e.g. windir=C:\WINDOWS). Most came with the operating system, and some are required for proper system functioning. A list of them is passed to every program (including cmd) when it starts. On Windows, there are two types: user environment variables and system environment variables.

You can see your environment variables like this:

C:\>set
ALLUSERSPROFILE=C:\ProgramData
APPDATA=C:\Users\craig\AppData\Roaming
CommonProgramFiles=C:\Program Files\Common Files
CommonProgramFiles(x86)=C:\Program Files (x86)\Common Files
CommonProgramW6432=C:\Program Files\Common Files
...

The most important variable is PATH. It is a list of paths, separated by ;. When a command is entered into cmd, each directory in the list will be scanned for a matching executable.

On my computer, PATH is:

C:\>echo %PATH%
C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPower
Shell\v1.0\;C:\ProgramData\Microsoft\Windows\Start Menu\Programs;C:\Users\craig\AppData\
Roaming\Microsoft\Windows\Start Menu\Programs;C:\msys64\usr\bin;C:\msys64\mingw64\bin;C:\
msys64\mingw32\bin;C:\Program Files\nodejs\;C:\Program Files (x86)\Yarn\bin\;C:\Users\
craig\AppData\Local\Yarn\bin;C:\Program Files\Java\jdk-10.0.2\bin;C:\ProgramFiles\Git\cmd;
C:\Program Files\Oracle\VirtualBox;C:\Program Files\7-Zip\;C:\Program Files\PuTTY\;C:\
Program Files\launch4j;C:\Program Files (x86)\NSIS\Bin;C:\Program Files (x86)\Common Files
\Adobe\AGL;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program
Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Intel\iCLS Client\;
C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files
(x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files (x86)\Intel\iCLS
Client\;C:\Users\craig\AppData\Local\Microsoft\WindowsApps

When you run javac HelloWorld.java, cmd, upon realizing that javac is not an internal command, searches the system PATH followed by the user PATH. It mechanically enters every directory in the list, and checks if javac.com, javac.exe, javac.bat, etc. is present. When it finds javac, it runs it. When it does not, it prints 'javac' is not recognized as an internal or external command, operable program or batch file.

You must add the Java executables directory to PATH.

JDK vs. JRE

(If you already understand this, feel free to skip this section.)

When downloading Java, you are offered a choice between:

  • The Java Runtime Environment (JRE), which includes the necessary tools to run Java programs, but not to compile new ones – it contains java but not javac.
  • The Java Development Kit (JDK), which contains both java and javac, along with a host of other development tools. The JDK is a superset of the JRE.

You must make sure you have installed the JDK. If you have only installed the JRE, you cannot execute javac because you do not have an installation of the Java compiler on your hard drive. Check your Windows programs list, and make sure the Java package's name includes the words "Development Kit" in it.

Don't use set

(If you weren't planning to anyway, feel free to skip this section.)

Several other answers recommend executing some variation of:

C:\>:: DON'T DO THIS
C:\>set PATH=C:\Program Files\Java\jdk1.7.0_09\bin

Do not do that. There are several major problems with that command:

  1. This command erases everything else from PATH and replaces it with the Java path. After executing this command, you might find various other commands not working.
  2. Your Java path is probably not C:\Program Files\Java\jdk1.7.0_09\bin – you almost definitely have a newer version of the JDK, which would have a different path.
  3. The new PATH only applies to the current cmd session. You will have to reenter the set command every time you open Command Prompt.

Points #1 and #2 can be solved with this slightly better version:

C:\>:: DON'T DO THIS EITHER
C:\>set PATH=C:\Program Files\Java\<enter the correct Java folder here>\bin;%PATH%

But it is just a bad idea in general.

Find the Java path

The right way begins with finding where you have installed Java. This depends on how you have installed Java.

Exe installer

You have installed Java by running a setup program. Oracle's installer places versions of Java under C:\Program Files\Java\ (or C:\Program Files (x86)\Java\). With File Explorer or Command Prompt, navigate to that directory.

Each subfolder represents a version of Java. If there is only one, you have found it. Otherwise, choose the one that looks like the newer version. Make sure the folder name begins with jdk (as opposed to jre). Enter the directory.

Then enter the bin directory of that.

You are now in the correct directory. Copy the path. If in File Explorer, click the address bar. If in Command Prompt, copy the prompt.

The resulting Java path should be in the form of (without quotes):

C:\Program Files\Java\jdkxxxx\bin\

Zip file

You have downloaded a .zip containing the JDK. Extract it to some random place where it won't get in your way; C:\Java\ is an acceptable choice.

Then locate the bin folder somewhere within it.

You are now in the correct directory. Copy its path. This is the Java path.

Remember to never move the folder, as that would invalidate the path.

Open the settings dialog

That is the dialog to edit PATH. There are numerous ways to get to that dialog, depending on your Windows version, UI settings, and how messed up your system configuration is.

Try some of these:

  • Start Menu/taskbar search box » search for "environment variable"
  • Win + R » control sysdm.cpl,,3
  • Win + R » SystemPropertiesAdvanced.exe » Environment Variables
  • File Explorer » type into address bar Control Panel\System and Security\System » Advanced System Settings (far left, in sidebar) » Environment Variables
  • Desktop » right-click This PC » Properties » Advanced System Settings » Environment Variables
  • Start Menu » right-click Computer » Properties » Advanced System Settings » Environment Variables
  • Control Panel (icon mode) » System » Advanced System Settings » Environment Variables
  • Control Panel (category mode) » System and Security » System » Advanced System Settings » Environment Variables
  • Desktop » right-click My Computer » Advanced » Environment Variables
  • Control Panel » System » Advanced » Environment Variables

Any of these should take you to the right settings dialog.

If you are on Windows 10, Microsoft has blessed you with a fancy new UI to edit PATH. Otherwise, you will see PATH in its full semicolon-encrusted glory, squeezed into a single-line textbox. Do your best to make the necessary edits without breaking your system.

Clean PATH

Look at PATH. You almost definitely have two PATH variables (because of user vs. system environment variables). You need to look at both of them.

Check for other Java paths and remove them. Their existence can cause all sorts of conflicts. (For instance, if you have JRE 8 and JDK 11 in PATH, in that order, then javac will invoke the Java 11 compiler, which will create version 55 .class files, but java will invoke the Java 8 JVM, which only supports up to version 52, and you will experience unsupported version errors and not be able to compile and run any programs.) Sidestep these problems by making sure you only have one Java path in PATH. And while you're at it, you may as well uninstall old Java versions, too. And remember that you don't need to have both a JDK and a JRE.

If you have C:\ProgramData\Oracle\Java\javapath, remove that as well. Oracle intended to solve the problem of Java paths breaking after upgrades by creating a symbolic link that would always point to the latest Java installation. Unfortunately, it often ends up pointing to the wrong location or simply not working. It is better to remove this entry and manually manage the Java path.

Now is also a good opportunity to perform general housekeeping on PATH. If you have paths relating to software no longer installed on your PC, you can remove them. You can also shuffle the order of paths around (if you care about things like that).

Add to PATH

Now take the Java path you found three steps ago, and place it in the system PATH.

It shouldn't matter where in the list your new path goes; placing it at the end is a fine choice.

If you are using the pre-Windows 10 UI, make sure you have placed the semicolons correctly. There should be exactly one separating every path in the list.

There really isn't much else to say here. Simply add the path to PATH and click OK.

Set JAVA_HOME

While you're at it, you may as well set JAVA_HOME as well. This is another environment variable that should also contain the Java path. Many Java and non-Java programs, including the popular Java build systems Maven and Gradle, will throw errors if it is not correctly set.

If JAVA_HOME does not exist, create it as a new system environment variable. Set it to the path of the Java directory without the bin/ directory, i.e. C:\Program Files\Java\jdkxxxx\.

Remember to edit JAVA_HOME after upgrading Java, too.

Close and re-open Command Prompt

Though you have modified PATH, all running programs, including cmd, only see the old PATH. This is because the list of all environment variables is only copied into a program when it begins executing; thereafter, it only consults the cached copy.

There is no good way to refresh cmd's environment variables, so simply close Command Prompt and open it again. If you are using an IDE, close and re-open it too.

See also

How to erase the file contents of text file in Python?

You cannot "erase" from a file in-place unless you need to erase the end. Either be content with an overwrite of an "empty" value, or read the parts of the file you care about and write it to another file.

How to get an object's methods?

var funcs = []
for(var name in myObject) {
    if(typeof myObject[name] === 'function') {
        funcs.push(name)
    }
}

I'm on a phone with no semi colons :) but that is the general idea.

Print a variable in hexadecimal in Python

A way that will fail if your input string isn't valid pairs of hex characters...:

>>> import binascii
>>> ' '.join(hex(ord(i)) for i in binascii.unhexlify('deadbeef'))
'0xde 0xad 0xbe 0xef'

Why do I always get the same sequence of random numbers with rand()?

rand() returns the next (pseudo) random number in a series. What's happening is you have the same series each time its run (default '1'). To seed a new series, you have to call srand() before you start calling rand().

If you want something random every time, you might try:

srand (time (0));

How to parse/read a YAML file into a Python object?

Here is one way to test which YAML implementation the user has selected on the virtualenv (or the system) and then define load_yaml_file appropriately:

load_yaml_file = None

if not load_yaml_file:
    try:
        import yaml
        load_yaml_file = lambda fn: yaml.load(open(fn))
    except:
        pass

if not load_yaml_file:
    import commands, json
    if commands.getstatusoutput('ruby --version')[0] == 0:
        def load_yaml_file(fn):
            ruby = "puts YAML.load_file('%s').to_json" % fn
            j = commands.getstatusoutput('ruby -ryaml -rjson -e "%s"' % ruby)
            return json.loads(j[1])

if not load_yaml_file:
    import os, sys
    print """
ERROR: %s requires ruby or python-yaml  to be installed.

apt-get install ruby

  OR

apt-get install python-yaml

  OR

Demonstrate your mastery of Python by using pip.
Please research the latest pip-based install steps for python-yaml.
Usually something like this works:
   apt-get install epel-release
   apt-get install python-pip
   apt-get install libyaml-cpp-dev
   python2.7 /usr/bin/pip install pyyaml
Notes:
Non-base library (yaml) should never be installed outside a virtualenv.
"pip install" is permanent:
  https://stackoverflow.com/questions/1550226/python-setup-py-uninstall
Beware when using pip within an aptitude or RPM script.
  Pip might not play by all the rules.
  Your installation may be permanent.
Ruby is 7X faster at loading large YAML files.
pip could ruin your life.
  https://stackoverflow.com/questions/46326059/
  https://stackoverflow.com/questions/36410756/
  https://stackoverflow.com/questions/8022240/
Never use PyYaml in numerical applications.
  https://stackoverflow.com/questions/30458977/
If you are working for a Fortune 500 company, your choices are
1. Ask for either the "ruby" package or the "python-yaml"
package. Asking for Ruby is more likely to get a fast answer.
2. Work in a VM. I highly recommend Vagrant for setting it up.

""" % sys.argv[0]
    os._exit(4)


# test
import sys
print load_yaml_file(sys.argv[1])

How can I convert NSDictionary to NSData and vice versa?

NSDictionary from NSData

http://www.cocoanetics.com/2009/09/nsdictionary-from-nsdata/

NSDictionary to NSData

You can use NSPropertyListSerialization class for that. Have a look at its method:

+ (NSData *)dataFromPropertyList:(id)plist format:(NSPropertyListFormat)format
                              errorDescription:(NSString **)errorString

Returns an NSData object containing a given property list in a specified format.

Custom CSS Scrollbar for Firefox

As of now there is just two property for firefox scrollbar customization is available .

scrollbar-color & scrollbar width

scrollbar-color:red yellow; (track,thumb) scrollbar-width:5px;

HTML

<div class="demo">

css

.demo {
overflow-y:scroll;
}

.demo {
scrollbar-color:red yellow;
scrollbar-width:5px;
}

Count the number of times a string appears within a string

With Linq...

string s = "7,true,NA,false:67,false,NA,false:5,false,NA,false:5,false,NA,false";
var count = s.Split(new[] {',', ':'}).Count(s => s == "true" );

Create local maven repository

Yes you can! For a simple repository that only publish/retrieve artifacts, you can use nginx.

  1. Make sure nginx has http dav module enabled, it should, but nonetheless verify it.

  2. Configure nginx http dav module:

    In Windows: d:\servers\nginx\nginx.conf

    location / {
        # maven repository
        dav_methods  PUT DELETE MKCOL COPY MOVE;
        create_full_put_path  on;
        dav_access  user:rw group:rw all:r;
    }
    

    In Linux (Ubuntu): /etc/nginx/sites-available/default

    location / {
            # First attempt to serve request as file, then
            # as directory, then fall back to displaying a 404.
            # try_files $uri $uri/ =404;  # IMPORTANT comment this
            dav_methods  PUT DELETE MKCOL COPY MOVE;
            create_full_put_path  on;
            dav_access  user:rw group:rw all:r;
    }
    

    Don't forget to give permissions to the directory where the repo will be located:

    sudo chmod +777 /var/www/html/repository

  3. In your project's pom.xml add the respective configuration:

    Retrieve artifacts:

    <repositories>
        <repository>
            <id>repository</id>
            <url>http://<your.ip.or.hostname>/repository</url>
        </repository>
    </repositories>
    

    Publish artifacts:

    <build>
        <extensions>
            <extension>
                <groupId>org.apache.maven.wagon</groupId>
                <artifactId>wagon-http</artifactId>
                <version>3.2.0</version>
            </extension>
        </extensions>
    </build>
    <distributionManagement>
        <repository>
            <id>repository</id>
            <url>http://<your.ip.or.hostname>/repository</url>
        </repository>
    </distributionManagement>
    
  4. To publish artifacts use mvn deploy. To retrieve artifacts, maven will do it automatically.

And there you have it a simple maven repo.

How do I create batch file to rename large number of files in a folder?

You don't need a batch file, just do this from powershell :

powershell -C "gci | % {rni $_.Name ($_.Name -replace 'Vacation2010', 'December')}"

Scatter plot with error bars

Using ggplot and a little dplyr for data manipulation:

set.seed(42)
df <- data.frame(x = rep(1:10,each=5), y = rnorm(50))

library(ggplot2)
library(dplyr)

df.summary <- df %>% group_by(x) %>%
    summarize(ymin = min(y),
              ymax = max(y),
              ymean = mean(y))

ggplot(df.summary, aes(x = x, y = ymean)) +
    geom_point(size = 2) +
    geom_errorbar(aes(ymin = ymin, ymax = ymax))

If there's an additional grouping column (OP's example plot has two errorbars per x value, saying the data is sourced from two files), then you should get all the data in one data frame at the start, add the grouping variable to the dplyr::group_by call (e.g., group_by(x, file) if file is the name of the column) and add it as a "group" aesthetic in the ggplot, e.g., aes(x = x, y = ymean, group = file).

Checking cin input stream produces an integer

If istream fails to insert, it will set the fail bit.

int i = 0;
std::cin >> i; // type a and press enter
if (std::cin.fail())
{
    std::cout << "I failed, try again ..." << std::endl
    std::cin.clear(); // reset the failed state
}

You can set this up in a do-while loop to get the correct type (int in this case) propertly inserted.

For more information: http://augustcouncil.com/~tgibson/tutorial/iotips.html#directly

How do I calculate the MD5 checksum of a file in Python?

In Python 3.8+ you can do

import hashlib

with open("your_filename.png", "rb") as f:
    file_hash = hashlib.md5()
    while chunk := f.read(8192):
        file_hash.update(chunk)

print(file_hash.digest())
print(file_hash.hexdigest())  # to get a printable str instead of bytes

On Python 3.7 and below:

with open("your_filename.png", "rb") as f:
    file_hash = hashlib.md5()
    chunk = f.read(8192)
    while chunk:
        file_hash.update(chunk)
        chunk = f.read(8192)

print(file_hash.hexdigest())

This reads the file 8192 (or 2¹³) bytes at a time instead of all at once with f.read() to use less memory.


Consider using hashlib.blake2b instead of md5 (just replace md5 with blake2b in the above snippets). It's cryptographically secure and faster than MD5.

How to switch to another domain and get-aduser

best solution TNX to Drew Chapin and all of you too:

I just want to add that if you don't inheritently know the name of a domain controller, you can get the closest one, pass it's hostname to the -Server argument.

$dc = Get-ADDomainController -DomainName example.com -Discover -NextClosestSite

Get-ADUser -Server $dc.HostName[0] `
    -Filter { EmailAddress -Like "*Smith_Karla*" } `
    -Properties EmailAddress

my script:

$dc = Get-ADDomainController -DomainName example.com -Discover -NextClosestSite
 Get-ADUser -Server $dc.HostName[0] ` -Filter { EmailAddress -Like "*Smith_Karla*" } `  -Properties EmailAddress | Export-CSV "C:\Scripts\Email.csv

How to write to Console.Out during execution of an MSTest test

You better setup a single test and create a performance test from this test. This way you can monitor the progress using the default tool set.

How to iterate through range of Dates in Java?

The following snippet (uses java.time.format of Java 8) maybe used to iterate over a date range :

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    // Any chosen date format maybe taken  
    LocalDate startDate = LocalDate.parse(startDateString,formatter);
    LocalDate endDate = LocalDate.parse(endDateString,formatter);
    if(endDate.isBefore(startDate))
    {
        //error
    }
    LocalDate itr = null;
    for (itr = startDate; itr.isBefore(endDate)||itr.isEqual(itr); itr = itr.plusDays(1))
    {
        //Processing  goes here
    }

The plusMonths()/plusYears() maybe chosen for time unit increment. Increment by a single day is being done in above illustration.

Removing single-quote from a string in php

You can substitute in HTML entitiy:

$FileName = preg_replace("/'/", "\&#39;", $UserInput);

How to create local notifications?

- (void)applicationDidEnterBackground:(UIApplication *)application
{
   UILocalNotification *notification = [[UILocalNotification alloc]init];
   notification.repeatInterval = NSDayCalendarUnit;
   [notification setAlertBody:@"Hello world"];
   [notification setFireDate:[NSDate dateWithTimeIntervalSinceNow:1]];
   [notification setTimeZone:[NSTimeZone  defaultTimeZone]];
   [application setScheduledLocalNotifications:[NSArray arrayWithObject:notification]];
}

This is worked, but in iOS 8.0 and later, your application must register for user notifications using -[UIApplication registerUserNotificationSettings:] before being able to schedule and present UILocalNotifications, do not forget this.

How can I list ALL DNS records?

  1. A zone transfer is the only way to be sure you have all the subdomain records. If the DNS is correctly configured you should not normally be able to perform an external zone transfer.

  2. The scans.io project has a database of DNS records that can be downloaded and searched for subdomains. This requires downloading the 87GB of DNS data, alternatively you can try the online search of the data at https://hackertarget.com/find-dns-host-records/

How do I add a auto_increment primary key in SQL Server database?

If the table already contains data and you want to change one of the columns to identity:

First create a new table that has the same columns and specify the primary key-kolumn:

create table TempTable
(
    Id int not null identity(1, 1) primary key
    --, Other columns...
)

Then copy all rows from the original table to the new table using a standard insert-statement.

Then drop the original table.

And finally rename TempTable to whatever you want using sp_rename:

http://msdn.microsoft.com/en-us/library/ms188351.aspx

Count number of occurrences of a pattern in a file (even on same line)

Ripgrep, which is a fast alternative to grep, has just introduced the --count-matches flag allowing counting each match in version 0.9 (I'm using the above example to stay consistent):

> echo afoobarfoobar | rg --count foo
1
> echo afoobarfoobar | rg --count-matches foo
2

As asked by OP, ripgrep allows for regex pattern as well (--regexp <PATTERN>). Also it can print each (line) match on a separate line:

> echo -e "line1foo\nline2afoobarfoobar" | rg foo
line1foo
line2afoobarfoobar

Creating an IFRAME using JavaScript

You can use:

<script type="text/javascript">
    function prepareFrame() {
        var ifrm = document.createElement("iframe");
        ifrm.setAttribute("src", "http://google.com/");
        ifrm.style.width = "640px";
        ifrm.style.height = "480px";
        document.body.appendChild(ifrm);
    }
</script> 

also check basics of the iFrame element

Facebook page automatic "like" URL (for QR Code)

For a hyperlink just use www.facebook.com/++page ID++/like

Eg: www.facebook.com/MYPAGEISAWESOME/like

To make it work with m.facebook.com here's what you do:

Open the Facebook page you're looking for then change the URL to the mobile URL ( which is www.m.facebook.com/MYPAGEISAWESOME ).

Now you should see a big version of the mobile Facebook page. Copy the target URL of the like button.

Pop that URL into the QR generator to make a "scan to like" barcode. This will open the m.Facebook page in the browser of most mobiles directly from the QR reader. If they are not logged into Facebook then they will be prompted to log in and then click 'like'. If logged in, it will auto like.

Hope this helps!

Also, definitely include something with a "click here/scan here to like us on Facebook"

How to remove carriage returns and new lines in Postgresql?

select regexp_replace(field, E'[\\n\\r\\u2028]+', ' ', 'g' )

I had the same problem in my postgres d/b, but the newline in question wasn't the traditional ascii CRLF, it was a unicode line separator, character U2028. The above code snippet will capture that unicode variation as well.

Update... although I've only ever encountered the aforementioned characters "in the wild", to follow lmichelbacher's advice to translate even more unicode newline-like characters, use this:

select regexp_replace(field, E'[\\n\\r\\f\\u000B\\u0085\\u2028\\u2029]+', ' ', 'g' )