Programs & Examples On #Gen fsm

gen_fsm stands for "generic finite state machine", a module behaviour in Erlang.

Browser back button handling

Warn/confirm User if Back button is Pressed is as below.

window.onbeforeunload = function() { return "Your work will be lost."; };

You can get more information using below mentioned links.

Disable Back Button in Browser using JavaScript

I hope this will help to you.

Show a PDF files in users browser via PHP/Perl

The safest way to have a PDF display instead of download seems to be embedding it using an object or iframe element. There are also 3rd party solutions like Google's PDF viewer.

See Best Way to Embed PDF in HTML for an overview.

There's also DoPDF, a Java based In-browser PDF viewer. I can't speak to its quality but it looks interesting.

What is the symbol for whitespace in C?

make use of isspace function .

The C library function int isspace(int c) checks whether the passed character is white-space.

sample code:

    int main()

       char var= ' ';

       if( isspace(var) )
          printf("var1 = |%c| is a white-space character\n", var );
/*instead you can easily compare character with ' '  
Standard white-space characters are -

' '   (0x20)    space (SPC)
'\t'    (0x09)  horizontal tab (TAB)
'\n'    (0x0a)  newline (LF)
'\v'    (0x0b)  vertical tab (VT)
'\f'    (0x0c)  feed (FF)
'\r'    (0x0d)  carriage return (CR)

source : tutorialpoint

jQuery to loop through elements with the same class

you can do it this way

$('.testimonial').each(function(index, obj){
    //you can use this to access the current item

Git Bash is extremely slow on Windows 7 x64

You might also gain a very subsquent performance boost by changing the following Git configuration:

git config --global status.submoduleSummary false

When running the simple git status command on Window 7 x64, it took my computer more than 30 seconds to run. After this option was defined, the command is immediate.

Activating Git's own tracing as explained in the following page helped me found the origin of the problem, which might differ in your installation:

How to list all AWS S3 objects in a bucket using Java

As a slightly more concise solution to listing S3 objects when they might be truncated:

ListObjectsRequest request = new ListObjectsRequest().withBucketName(bucketName);
ObjectListing listing = null;

while((listing == null) || (request.getMarker() != null)) {
  listing = s3Client.listObjects(request);
  // do stuff with listing

latex tabular width the same as the textwidth

The tabularx package gives you

  1. the total width as a first parameter, and
  2. a new column type X, all X columns will grow to fill up the total width.

For your example:

% ...    
% ...

Input & Output& Action return \\
DNF &  simulation & jsp\\

Sun JSTL taglib declaration fails with "Can not find the tag library descriptor"

This is a fix for people who are not using maven. You also need to add standard.jar to your lib folder for the core tag library to work. Works for jstl version 1.1.

<%@taglib prefix="core" uri=""%>

Where are static methods and static variables stored in Java?

When we create a static variable or method it is stored in the special area on heap: PermGen(Permanent Generation), where it lays down with all the data applying to classes(non-instance data). Starting from Java 8 the PermGen became - Metaspace. The difference is that Metaspace is auto-growing space, while PermGen has a fixed Max size, and this space is shared among all of the instances. Plus the Metaspace is a part of a Native Memory and not JVM Memory.

You can look into this for more details.

Difference between HashMap, LinkedHashMap and TreeMap

HashMap makes absolutely not guarantees about the iteration order. It can (and will) even change completely when new elements are added. TreeMap will iterate according to the "natural ordering" of the keys according to their compareTo() method (or an externally supplied Comparator). Additionally, it implements the SortedMap interface, which contains methods that depend on this sort order. LinkedHashMap will iterate in the order in which the entries were put into the map

Look at how performance varying.. enter image description here

Tree map which is an implementation of Sorted map. The complexity of the put, get and containsKey operation is O(log n) due to the Natural ordering

How to get character for a given ascii value

Simply Try this:

int n = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("data is: {0}", Convert.ToChar(n));

How To: Best way to draw table in console app (C#)

This is an improvement to a previous answer. It adds support for values with varying lengths and rows with a varying number of cells. For example:

¦Identifier¦     Type¦               Description¦  CPU Credit Use¦Hours¦Balance¦
¦ i-1234154¦ t2.small¦       This is an example.¦         3263.75¦  360¦
¦ i-1231412¦ t2.small¦  This is another example.¦         3089.93¦

Here is the code:

public class ArrayPrinter
    const string TOP_LEFT_JOINT = "+";
    const string TOP_RIGHT_JOINT = "+";
    const string BOTTOM_LEFT_JOINT = "+";
    const string BOTTOM_RIGHT_JOINT = "+";
    const string TOP_JOINT = "-";
    const string BOTTOM_JOINT = "-";
    const string LEFT_JOINT = "+";
    const string JOINT = "+";
    const string RIGHT_JOINT = "¦";
    const char HORIZONTAL_LINE = '-';
    const char PADDING = ' ';
    const string VERTICAL_LINE = "¦";

    private static int[] GetMaxCellWidths(List<string[]> table)
        int maximumCells = 0;
        foreach (Array row in table)
            if (row.Length > maximumCells)
                maximumCells = row.Length;

        int[] maximumCellWidths = new int[maximumCells];
        for (int i = 0; i < maximumCellWidths.Length; i++)
            maximumCellWidths[i] = 0;

        foreach (Array row in table)
            for (int i = 0; i < row.Length; i++)
                if (row.GetValue(i).ToString().Length > maximumCellWidths[i])
                    maximumCellWidths[i] = row.GetValue(i).ToString().Length;

        return maximumCellWidths;

    public static string GetDataInTableFormat(List<string[]> table)
        StringBuilder formattedTable = new StringBuilder();
        Array nextRow = table.FirstOrDefault();
        Array previousRow = table.FirstOrDefault();

        if (table == null || nextRow == null)
            return String.Empty;

        // FIRST LINE:
        int[] maximumCellWidths = GetMaxCellWidths(table);
        for (int i = 0; i < nextRow.Length; i++)
            if (i == 0 && i == nextRow.Length - 1)
                formattedTable.Append(String.Format("{0}{1}{2}", TOP_LEFT_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE), TOP_RIGHT_JOINT));
            else if (i == 0)
                formattedTable.Append(String.Format("{0}{1}", TOP_LEFT_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE)));
            else if (i == nextRow.Length - 1)
                formattedTable.AppendLine(String.Format("{0}{1}{2}", TOP_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE), TOP_RIGHT_JOINT));
                formattedTable.Append(String.Format("{0}{1}", TOP_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE)));

        int rowIndex = 0;
        int lastRowIndex = table.Count - 1;
        foreach (Array thisRow in table)
            // LINE WITH VALUES:
            int cellIndex = 0;
            int lastCellIndex = thisRow.Length - 1;
            foreach (object thisCell in thisRow)
                string thisValue = thisCell.ToString().PadLeft(maximumCellWidths[cellIndex], PADDING);

                if (cellIndex == 0 && cellIndex == lastCellIndex)
                    formattedTable.AppendLine(String.Format("{0}{1}{2}", VERTICAL_LINE, thisValue, VERTICAL_LINE));
                else if (cellIndex == 0)
                    formattedTable.Append(String.Format("{0}{1}", VERTICAL_LINE, thisValue));
                else if (cellIndex == lastCellIndex)
                    formattedTable.AppendLine(String.Format("{0}{1}{2}", VERTICAL_LINE, thisValue, VERTICAL_LINE));
                    formattedTable.Append(String.Format("{0}{1}", VERTICAL_LINE, thisValue));


            previousRow = thisRow;

            // SEPARATING LINE:
            if (rowIndex != lastRowIndex)
                nextRow = table[rowIndex + 1];

                int maximumCells = Math.Max(previousRow.Length, nextRow.Length);
                for (int i = 0; i < maximumCells; i++)
                    if (i == 0 && i == maximumCells - 1)
                        formattedTable.Append(String.Format("{0}{1}{2}", LEFT_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE), RIGHT_JOINT));
                    else if (i == 0)
                        formattedTable.Append(String.Format("{0}{1}", LEFT_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE)));
                    else if (i == maximumCells - 1)
                        if (i > previousRow.Length)
                            formattedTable.AppendLine(String.Format("{0}{1}{2}", TOP_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE), TOP_RIGHT_JOINT));
                        else if (i > nextRow.Length)
                            formattedTable.AppendLine(String.Format("{0}{1}{2}", BOTTOM_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE), BOTTOM_RIGHT_JOINT));
                        else if (i > previousRow.Length - 1)
                            formattedTable.AppendLine(String.Format("{0}{1}{2}", JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE), TOP_RIGHT_JOINT));
                        else if (i > nextRow.Length - 1)
                            formattedTable.AppendLine(String.Format("{0}{1}{2}", JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE), BOTTOM_RIGHT_JOINT));
                            formattedTable.AppendLine(String.Format("{0}{1}{2}", JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE), RIGHT_JOINT));
                        if (i > previousRow.Length)
                            formattedTable.Append(String.Format("{0}{1}", TOP_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE)));
                        else if (i > nextRow.Length)
                            formattedTable.Append(String.Format("{0}{1}", BOTTOM_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE)));
                            formattedTable.Append(String.Format("{0}{1}", JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE)));


        // LAST LINE:
        for (int i = 0; i < previousRow.Length; i++)
            if (i == 0)
                formattedTable.Append(String.Format("{0}{1}", BOTTOM_LEFT_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE)));
            else if (i == previousRow.Length - 1)
                formattedTable.AppendLine(String.Format("{0}{1}{2}", BOTTOM_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE), BOTTOM_RIGHT_JOINT));
                formattedTable.Append(String.Format("{0}{1}", BOTTOM_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE)));

        return formattedTable.ToString();

How to include external Python code to use in other files?

I've found the python inspect module to be very useful

For example with

import inspect

def dostuff():
    return __name__

DOSTUFF_SOURCE = inspect.getsource(dostuff)

if __name__ == "__main__":


And from the another script or the python console

import teststuff



And now dostuff should be in the local scope and dostuff() will return the console or scripts _name_ whereas executing test.dostuff() will return the python modules name.

"commence before first target. Stop." error

This means that there is a line which starts with a space, tab, or some other whitespace without having a target in front of it.

Operand type clash: int is incompatible with date + The INSERT statement conflicted with the FOREIGN KEY constraint

This expression 12-4-2005 is a calculated int and the value is -1997. You should do like this instead '2005-04-12' with the ' before and after.

Android: ListView elements with multiple clickable buttons

I don't have much experience than above users but I faced this same issue and I Solved this with below Solution


btnRemoveClick Click event

public void btnRemoveClick(View v)
    final int position = listviewItem.getPositionForView((View) v.getParent()); 


Parse rfc3339 date strings in Python?

You should have a look at moment which is a python port of the excellent js lib momentjs.

One advantage of it is the support of ISO 8601 strings formats, as well as a generic "% format" :

import moment

m =, '%Y-%m-%dT%H:%M:%SZ')
print m.format('YYYY-M-D H:M')
print m.weekday


2012-10-09 19:10

Executing multiple commands from a Windows cmd script

When you call another .bat file, I think you need "call" in front of the call:

call otherCommand.bat

Get the date (a day before current time) in Bash

eval `date "+day=%d; month=%m; year=%Y"`
# Subtract offset from day, if it goes below one use 'cal'
# to determine the number of days in the previous month.
day=`expr $day - $OFFSET`
if [ $day -le 0 ] ;then
month=`expr $month - 1`
if [ $month -eq 0 ] ;then
year=`expr $year - 1`
set `cal $month $year`
day=`expr $xday + $day`
echo $year-$month-$day

Get page title with Selenium WebDriver using Java

It could be done by getting the page title by Selenium and do assertion by using TestNG.

  1. Import Assert class in the import section:

    `import org.testng.Assert;`
  2. Create a WebDriver object:

    WebDriver driver=new FirefoxDriver();

  3. Apply this to assert the title of the page:

    Assert.assertEquals("Expected page title", driver.getTitle());

How to prevent XSS with HTML/PHP?

Cross-posting this as a consolidated reference from the SO Documentation beta which is going offline.


Cross-site scripting is the unintended execution of remote code by a web client. Any web application might expose itself to XSS if it takes input from a user and outputs it directly on a web page. If input includes HTML or JavaScript, remote code can be executed when this content is rendered by the web client.

For example, if a 3rd party side contains a JavaScript file:

document.write("I'm running");

And a PHP application directly outputs a string passed into it:

echo '<div>' . $_GET['input'] . '</div>';

If an unchecked GET parameter contains <script src=""></script> then the output of the PHP script will be:

<div><script src=""></script></div>

The 3rd party JavaScript will run and the user will see "I'm running" on the web page.


As a general rule, never trust input coming from a client. Every GET parameter, POST or PUT content, and cookie value could be anything at all, and should therefore be validated. When outputting any of these values, escape them so they will not be evaluated in an unexpected way.

Keep in mind that even in the simplest applications data can be moved around and it will be hard to keep track of all sources. Therefore it is a best practice to always escape output.

PHP provides a few ways to escape output depending on the context.

Filter Functions

PHPs Filter Functions allow the input data to the php script to be sanitized or validated in many ways. They are useful when saving or outputting client input.

HTML Encoding

htmlspecialchars will convert any "HTML special characters" into their HTML encodings, meaning they will then not be processed as standard HTML. To fix our previous example using this method:

echo '<div>' . htmlspecialchars($_GET['input']) . '</div>';
// or
echo '<div>' . filter_input(INPUT_GET, 'input', FILTER_SANITIZE_SPECIAL_CHARS) . '</div>';

Would output:

<div>&lt;script src=&quot;;&gt;&lt;/script&gt;</div>

Everything inside the <div> tag will not be interpreted as a JavaScript tag by the browser, but instead as a simple text node. The user will safely see:

<script src=""></script>

URL Encoding

When outputting a dynamically generated URL, PHP provides the urlencode function to safely output valid URLs. So, for example, if a user is able to input data that becomes part of another GET parameter:

$input = urlencode($_GET['input']);
// or
$input = filter_input(INPUT_GET, 'input', FILTER_SANITIZE_URL);
echo '<a href=""' . $input . '">Link</a>';

Any malicious input will be converted to an encoded URL parameter.

Using specialised external libraries or OWASP AntiSamy lists

Sometimes you will want to send HTML or other kind of code inputs. You will need to maintain a list of authorised words (white list) and un-authorized (blacklist).

You can download standard lists available at the OWASP AntiSamy website. Each list is fit for a specific kind of interaction (ebay api, tinyMCE, etc...). And it is open source.

There are libraries existing to filter HTML and prevent XSS attacks for the general case and performing at least as well as AntiSamy lists with very easy use. For example you have HTML Purifier

How to change the date format from MM/DD/YYYY to YYYY-MM-DD in PL/SQL?

select to_date(to_char(ORDER_DATE,'YYYY/MM/DD')) 
from ORDERS;

This might help but, at the end you will get a string not the date. Apparently, your format problem will get solved for sure .

One line if-condition-assignment

You can definitely use num1 = (20 if someBoolValue else num1) if you want.

Type definition in object literal in TypeScript

You could use predefined utility type Record<Keys, Type> :

const obj: Record<string, string> = {
  property: "value",

It allows to specify keys for your object literal:

type Keys = "prop1" | "prop2"

const obj: Record<Keys, string> = {
  prop1: "Hello",
  prop2: "Aloha",
  something: "anything" // TS Error: Type '{ prop1: string; prop2: string; something: string; }' is not assignable to type 'Record<Keys, string>'.
                        //   Object literal may only specify known properties, and 'something' does not exist in type 'Record<Keys, string>'.

And a type for the property value:

type Keys = "prop1" | "prop2"
type Value = "Hello" | "Aloha"

const obj1: Record<Keys, Value> = {
  prop1: "Hello",
  prop2: "Hey", // TS Error: Type '"Hey"' is not assignable to type 'Value'.

Highlight the difference between two strings in PHP

Just wrote a class to compute smallest (not to be taken literally) number of edits to transform one string into another string:

It has a static function to render a HTML version of the diff.

It's a first version, and likely to be improved, but it works just fine as of now, so I am throwing it out there in case someone needs to generate a compact diff efficiently, like I needed.

Edit: It's on Github now:

How do I measure separate CPU core usage for a process?

You can still do this in top. While top is running, press '1' on your keyboard, it will then show CPU usage per core.

Limit the processes shown by having that specific process run under a specific user account and use Type 'u' to limit to that user

Python - Check If Word Is In A String

Advanced way to check the exact word, that we need to find in a long string:

import re
text = "This text was of edited by Rock"
#try this string also
#text = "This text was officially edited by Rock" 
for m in re.finditer(r"\bof\b", text):
        print "Present"
        print "Absent"

How to list npm user-installed packages?

npm ls

npm list is just an alias for npm ls

For the extended info use

npm la    
npm ll

You can always set --depth=0 at the end to get the first level deep.

npm ls --depth=0

You can check development and production packages.

npm ls --only=dev
npm ls --only=prod

To show the info in json format

npm ls --json=true

The default is false

npm ls --json=false

You can insist on long format to show extended information.

npm ls --long=true

You can show parseable output instead of tree view.

npm ls --parseable=true

You can list packages in the global install prefix instead of in the current project.

npm ls --global=true
npm ls -g // shorthand

Full documentation you can find here.

Linear regression with matplotlib / numpy

This code:

from scipy.stats import linregress

linregress(x,y) #x and y are arrays or lists.

gives out a list with the following:

slope : float
slope of the regression line
intercept : float
intercept of the regression line
r-value : float
correlation coefficient
p-value : float
two-sided p-value for a hypothesis test whose null hypothesis is that the slope is zero
stderr : float
Standard error of the estimate


How to pass table value parameters to stored procedure from .net code


   public static DataTable ToTableValuedParameter<T, TProperty>(this IEnumerable<T> list, Func<T, TProperty> selector)
        var tbl = new DataTable();
        tbl.Columns.Add("Id", typeof(T));

        foreach (var item in list)


        return tbl;


Is it possible to focus on a <div> using JavaScript focus() function?

You can use tabindex

<div tabindex="-1"  id="tries"></div>

The tabindex value can allow for some interesting behaviour.

  • If given a value of "-1", the element can't be tabbed to but focus can be given to the element programmatically (using element.focus()).
  • If given a value of 0, the element can be focused via the keyboard and falls into the tabbing flow of the document. Values greater than 0 create a priority level with 1 being the most important.

When to use: Java 8+ interface default method, vs. abstract method

In Java 8, an interface looks like an abstract class although their might be some differences such as :

1) Abstract classes are classes, so they are not restricted to other restrictions of the interface in Java e.g. abstract class can have the state, but you cannot have the state on the interface in Java.

2) Another semantic difference between interface with default methods and abstract class is that you can define constructors inside an abstract class, but you cannot define constructor inside interface in Java

Use PHP to create, edit and delete crontab jobs?

Its simple You can you curl to do so, make sure curl installed on server :

for triggering every minute : * * * * * curl --request POST ''

        • *

    minute hour day month week

Let say you want to send this notification 2:15 PM everyday You may change POST/GET based on your API:

15 14 * * * curl --request POST 'url of ur API'

API vs. Webservice

An API (Application Programming Interface) is the means by which third parties can write code that interfaces with other code. A Web Service is a type of API, one that almost always operates over HTTP (though some, like SOAP, can use alternate transports, like SMTP). The official W3C definition mentions that Web Services don't necessarily use HTTP, but this is almost always the case and is usually assumed unless mentioned otherwise.

For examples of web services specifically, see SOAP, REST, and XML-RPC. For an example of another type of API, one written in C for use on a local machine, see the Linux Kernel API.

As far as the protocol goes, a Web service API almost always uses HTTP (hence the Web part), and definitely involves communication over a network. APIs in general can use any means of communication they wish. The Linux kernel API, for example, uses Interrupts to invoke the system calls that comprise its API for calls from user space.

How to connect to remote Redis server?

In Case of password also we need to pass one more parameter

redis-cli -h host -p port -a password

Selenium and xPath - locating a link by containing text

@FindBy(xpath = "//span[@class='y2' and contains(text(), 'Your Text')] ") 
private WebElementFacade emailLinkToVerifyAccount;

This approach will work for you, hopefully.

Where is my .vimrc file?

on unix vim --version tells you the various locations of the vim config files :

   system vimrc file: "$VIM/vimrc"
     user vimrc file: "$HOME/.vimrc"
 2nd user vimrc file: "~/.vim/vimrc"
      user exrc file: "$HOME/.exrc"
       defaults file: "$VIMRUNTIME/defaults.vim"
  fall-back for $VIM: "/usr/share/vim"

Cron job every three days

0 0 1-30/3 * *

This would run every three days starting 1st. Here are the 20 scheduled runs -

  • 2015-06-01 00:00:00
  • 2015-06-04 00:00:00
  • 2015-06-07 00:00:00
  • 2015-06-10 00:00:00
  • 2015-06-13 00:00:00
  • 2015-06-16 00:00:00
  • 2015-06-19 00:00:00
  • 2015-06-22 00:00:00
  • 2015-06-25 00:00:00
  • 2015-06-28 00:00:00
  • 2015-07-01 00:00:00
  • 2015-07-04 00:00:00
  • 2015-07-07 00:00:00
  • 2015-07-10 00:00:00
  • 2015-07-13 00:00:00
  • 2015-07-16 00:00:00
  • 2015-07-19 00:00:00
  • 2015-07-22 00:00:00
  • 2015-07-25 00:00:00
  • 2015-07-28 00:00:00

Android LinearLayout : Add border with shadow around a LinearLayout

1.First create a xml file name shadow.xml in "drawable" folder and copy the below code into it.

 <?xml version="1.0" encoding="utf-8"?>
    <layer-list xmlns:android="">
            <shape android:shape="rectangle">
                <solid android:color="#CABBBBBB" />
                <corners android:radius="10dp" />

            <shape android:shape="rectangle">
                <solid android:color="@android:color/white" />
                <corners android:radius="4dp" />

Then add the the layer-list as background in your LinearLayout.


How do I launch a Git Bash window with particular working directory using a script?

Let yet add up to the answer from @Drew Noakes:


"C:\Program Files\Git\git-bash.exe" --cd=C:\GitRepo

The cd param should be one of the options how to specify the working directory.

Also notice, that I have not any --login param there: Instead, I use another extra app, dedicated just for SSH keys: Pageant (PuTTY authentication agent).

Start in:


The same possible way, as @Drew Noakes mentioned/shown here sooner, I use it too.

Shortcut key:

Ctrl + Alt + B

Such shortcuts are another less known feature in Windows. But there is a restriction: To let the shortcut take effect, it must be placed somewhere on the User's subdirectory: The Desktop is fine.

If you do not want it visible, yet still activatable, place this .lnk file i.e. to the quick launch folder, as that dir is purposed for such shortcuts. (no matter whether displayed on the desktop) #76080 #3619355

"\Application Data\Microsoft\Internet Explorer\Quick Launch\"

differences in application/json and application/x-www-form-urlencoded

The first case is telling the web server that you are posting JSON data as in:

{ Name : 'John Smith', Age: 23}

The second option is telling the web server that you will be encoding the parameters in the URL as in:


How to Auto-start an Android Application?

I always get in here, for this topic. I'll put my code in here so i (or other) can use it next time. (Phew hate to search into my repository code).

Add the permission:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

Add receiver and service:

<receiver android:enabled="true" android:name=".BootUpReceiver"
        <action android:name="android.intent.action.BOOT_COMPLETED" />
        <category android:name="android.intent.category.DEFAULT" />
<service android:name="Launcher" />

Create class Launcher:

public class Launcher extends Service {
    public IBinder onBind(Intent intent) {
        return null;

    public int onStartCommand(Intent intent, int flags, int startId) {

        new AsyncTask<Service, Void, Service>() {

            protected Service doInBackground(Service... params) {
                Service service = params[0];
                PackageManager pm = service.getPackageManager();
                try {
                    Intent target = pm.getLaunchIntentForPackage("");
                    if (target != null) {
                        synchronized (this) {
                    } else {
                        throw new ActivityNotFoundException();
                } catch (ActivityNotFoundException | InterruptedException ignored) {
                return service;

            protected void onPostExecute(Service service) {


        return START_STICKY;

Create class BootUpReceiver to do action after android reboot.

For example launch MainActivity:

public class BootUpReceiver extends BroadcastReceiver{

    public void onReceive(Context context, Intent intent) {
        Intent target = new Intent(context, MainActivity.class);  

Loop through all the resources in a .resx file

The minute you add a resource .RESX file to your project, Visual Studio will create a Designer.cs with the same name, creating a a class for you with all the items of the resource as static properties. You can see all the names of the resource when you type the dot in the editor after you type the name of the resource file.

Alternatively, you can use reflection to loop through these names.

Type resourceType = Type.GetType("AssemblyName.Resource1");
PropertyInfo[] resourceProps = resourceType.GetProperties(
    BindingFlags.NonPublic | 
    BindingFlags.Static | 

foreach (PropertyInfo info in resourceProps)
    string name = info.Name;
    object value = info.GetValue(null, null);  // object can be an image, a string whatever
    // do something with name and value

This method is obviously only usable when the RESX file is in scope of the current assembly or project. Otherwise, use the method provided by "pulse".

The advantage of this method is that you call the actual properties that have been provided for you, taking into account any localization if you wish. However, it is rather redundant, as normally you should use the type safe direct method of calling the properties of your resources.

How can I create a table with borders in Android?

To make 1dp collapse-border around every cell without writing a java code and without creating another xml layout with <shape...> tag, you can try this solution:

In <TableLayout...> add android:background="#CCC" and android:paddingTop="1dp" and android:stretchColumns="0"

In <TableRow...> add android:background="#CCC" and android:paddingBottom="1dp" and android:paddingRight="1dp"

In every cell/child in TableRow, i.e. <TextView...> add android:background="#FFF" and android:layout_marginLeft="1dp"

It is very important to follow paddings and margins as described. This solution will draw a 1dp border aka border-collapse property in (X)HTML/CSS.

Background color in <TableLayout...> and <TableRow...> represents a border line color and background in <TextView...> fills a table cell. You can put some padding in cells if necessary.

An example is here:

<TableLayout xmlns:android=""


Show only two digit after decimal

First thing that should pop in a developer head while formatting a number into char sequence should be care of such details like do it will be possible to reverse the operation.

And other aspect is providing proper result. So you want to truncate the number or round it.

So before you start you should ask your self, am i interested on the value or not.

To achieve your goal you have multiple options but most of them refer to Format and Formatter, but i just suggest to look in this answer.

How to compile and run C files from within Notepad++ using NppExec plugin?

For perl,

To run perl script use this procedure

Requirement: You need to setup classpath variable.

Go to plugins->NppExec->Execute

In command section, type this


Save it and give name to it.(I give Perl).

Press OK. If editor wants to restart, do it first.

Now press F6 and you will find your Perl script output on below side.

Note: Not required seperate config for seperate files.

For java,

Requirement: You need to setup JAVA_HOME and classpath variable.

Go to plugins->NppExec->Execute

In command section, type this

cmd /c cd "$(CURRENT_DIRECTORY)"&&"%JAVA_HOME%\bin\javac""$(FULL_CURRENT_PATH)"

your *.class will generate on location of current folder; despite of programming error.

For Python,

Use this Plugin Python Plugin

Go to plugins->NppExec-> Run file in Python intercative

By using this you can run scripts within Notepad++.

For PHP,

No need for different configuration just download this plugin.

PHP Plugin and done.

For C language,

Requirement: You need to setup classpath variable.
I am using MinGW compiler.

Go to plugins->NppExec->Execute

paste this into there



   C:\MinGW32\bin\gcc.exe -g "$(FILE_NAME)" 


(Remember to give above four lines separate lines.)

Now, give name, save and ok.

Restart Npp.

Go to plugins->NppExec->Advanced options.

Menu Item->Item Name (I have C compiler)

Associated Script-> from combo box select the above name of script.

Click on Add/modify and Ok.

Now assign shortcut key as given in first answer.

Press F6 and select script or just press shortcut(I assigned Ctrl+2).

For C++,

Only change g++ instead of gcc and *.cpp instead on *.c

That's it!!

Getting attribute of element in ng-click function in angularjs

Try passing it directly to the ng-click function:

<div class="col-lg-1 text-center">
    <span class="glyphicon glyphicon-trash" data="{{}}"

Then it should be available in your handler:


Here's an example

JQuery style display value

Just call css with one argument


If I understand your question. Otherwise, you want cletus' answer.

jquery function val() is not equivalent to "$(this).value="?

One thing you can do is this:

$(this)[0].value = "Something";

This allows jQuery to return the javascript object for that element, and you can bypass jQuery Functions.

How do I do logging in C# without using 3rd party libraries?

If you want to stay close to .NET check out Enterprise Library Logging Application Block. Look here. Or for a quickstart tutorial check this. I have used the Validation application Block from the Enterprise Library and it really suits my needs and is very easy to "inherit" (install it and refrence it!) in your project.

Create or update mapping in elasticsearch

Please note that there is a mistake in the url provided in this answer:

For a PUT mapping request: the url should be as follows:


and NOT


Format numbers in thousands (K) in Excel

Enter this in the custom number format field:


What that means is that if the number is greater than 1,000, display at least one digit (indicated by the zero), but no digits after the thousands place, indicated by nothing coming after the comma. Then you follow the whole thing with the string "K".

Edited to add comma and euro.

WCF - How to Increase Message Size Quota

If you're still getting this error message while using the WCF Test Client, it's because the client has a separate MaxBufferSize setting.

To correct the issue:

  1. Right-Click on the Config File node at the bottom of the tree
  2. Select Edit with SvcConfigEditor

A list of editable settings will appear, including MaxBufferSize.

Note: Auto-generated proxy clients also set MaxBufferSize to 65536 by default.

Java LinkedHashMap get first or last entry

right, you have to manually enumerate keyset till the end of the linkedlist, then retrieve the entry by key and return this entry.

How can you strip non-ASCII characters from a string? (in C#)

I use this regular expression to filter out bad characters in a filename.

Regex.Replace(directory, "[^a-zA-Z0-9\\:_\- ]", "")

That should be all the characters allowed for filenames.

get one item from an array of name,value JSON

Arrays are normally accessed via numeric indexes, so in your example arr[0] == {name:"k1", value:"abc"}. If you know that the name property of each object will be unique you can store them in an object instead of an array, as follows:

var obj = {};
obj["k1"] = "abc";
obj["k2"] = "hi";
obj["k3"] = "oa";

alert(obj["k2"]); // displays "hi"

If you actually want an array of objects like in your post you can loop through the array and return when you find an element with an object having the property you want:

function findElement(arr, propName, propValue) {
  for (var i=0; i < arr.length; i++)
    if (arr[i][propName] == propValue)
      return arr[i];

  // will return undefined if not found; you could return a default instead

// Using the array from the question
var x = findElement(arr, "name", "k2"); // x is {"name":"k2", "value":"hi"}
alert(x["value"]); // displays "hi"

var y = findElement(arr, "name", "k9"); // y is undefined
alert(y["value"]); // error because y is undefined

alert(findElement(arr, "name", "k2")["value"]); // displays "hi";

alert(findElement(arr, "name", "zzz")["value"]); // gives an error because the function returned undefined which won't have a "value" property

Failed to read artifact descriptor for org.apache.maven.plugins:maven-source-plugin:jar:2.4

I use intelliJ and finally I created my own settings.xml and added the following content structure to it. In my project's pom.xml, the nexus repositories were defined but for some reason it was always hitting the external apache maven repo which is blocked in my company.

     <url>nexusURL </url>



PyCharm import external library

updated on May 26-2018

If the external library is in a folder that is under the project then

File -> Settings -> Project -> Project structure -> select the folder and Mark as Sources!

If not, add content root, and do similar things.

How can I install the Beautiful Soup module on the Mac?

Brian beat me too it, but since I already have the transcript:


aaron@ares ~$ sudo easy_install BeautifulSoup
Searching for BeautifulSoup
Best match: BeautifulSoup 3.0.7a
Processing BeautifulSoup-3.0.7a-py2.5.egg
BeautifulSoup 3.0.7a is already the active version in easy-install.pth

Using /Library/Python/2.5/site-packages/BeautifulSoup-3.0.7a-py2.5.egg
Processing dependencies for BeautifulSoup
Finished processing dependencies for BeautifulSoup

.. or the normal boring way:

aaron@ares ~/Downloads$ curl > bs.tar.gz
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 71460  100 71460    0     0  84034      0 --:--:-- --:--:-- --:--:--  111k

aaron@ares ~/Downloads$ tar -xzvf bs.tar.gz 

aaron@ares ~/Downloads$ cd BeautifulSoup-

aaron@ares ~/Downloads/BeautifulSoup-$ sudo python install
running install
<... snip ...>

Undefined reference to vtable

In my case I'm using Qt and had defined a QObject subclass in a foo.cpp (not .h) file. The fix was to add #include "foo.moc" at the end of foo.cpp.

How to get Text BOLD in Alert or Confirm box?

Maybe you coul'd use UTF8 bold chars.

For examples:

It works on Chromium 80.0, I don't know on other browsers...

JavaScript get element by name

All Answers here seem to be outdated. Please use this now:


Python: How to convert datetime format?

@Tim's answer only does half the work -- that gets it into a datetime.datetime object.

To get it into the string format you require, you use datetime.strftime:

print(datetime.strftime('%b %d,%Y'))

How to replace values at specific indexes of a python list?

Why not just:

map(s.__setitem__, a, m)

The name 'ConfigurationManager' does not exist in the current context

You may also get this error if you add a reference to a different, unrelated project by mistake. Check if that applies to you.

How to `wget` a list of URLs in a text file?

If you're on OpenWrt or using some old version of wget which doesn't gives you -i option:

while IFS= read -r line
  wget $line
done < "$input"

Furthermore, if you don't have wget, you can use curl or whatever you use for downloading individual files.

Java Class.cast() vs. cast operator

First, you are strongly discouraged to do almost any cast, so you should limit it as much as possible! You lose the benefits of Java's compile-time strongly-typed features.

In any case, Class.cast() should be used mainly when you retrieve the Class token via reflection. It's more idiomatic to write

MyObject myObject = (MyObject) object

rather than

MyObject myObject = MyObject.class.cast(object)

EDIT: Errors at compile time

Over all, Java performs cast checks at run time only. However, the compiler can issue an error if it can prove that such casts can never succeed (e.g. cast a class to another class that's not a supertype and cast a final class type to class/interface that's not in its type hierarchy). Here since Foo and Bar are classes that aren't in each other hierarchy, the cast can never succeed.

Get list of certificates from the certificate store in C#

Try this:

//using System.Security.Cryptography.X509Certificates;
public static X509Certificate2 selectCert(StoreName store, StoreLocation location, string windowTitle, string windowMsg)

    X509Certificate2 certSelected = null;
    X509Store x509Store = new X509Store(store, location);

    X509Certificate2Collection col = x509Store.Certificates;
    X509Certificate2Collection sel = X509Certificate2UI.SelectFromCollection(col, windowTitle, windowMsg, X509SelectionFlag.SingleSelection);

    if (sel.Count > 0)
        X509Certificate2Enumerator en = sel.GetEnumerator();
        certSelected = en.Current;


    return certSelected;

Understanding dispatch_async

Swift version

This is the Swift version of David's Objective-C answer. You use the global queue to run things in the background and the main queue to update the UI. .background).async {
    // Background Thread
    DispatchQueue.main.async {
        // Run UI Updates

vertical align middle in <div>

You can use line-height: 50px;, you won't need vertical-align: middle; there.


The above will fail if you've multiple lines, so in that case you can wrap your text using span and than use display: table-cell; and display: table; along with vertical-align: middle;, also don't forget to use width: 100%; for #abc


  font:Verdana, Geneva, sans-serif;
  display: table;
  width: 100%;

#abc span {
  display: table-cell;

Another solution I can think of here is to use transform property with translateY() where Y obviously stands for Y Axis. It's pretty straight forward... All you need to do is set the elements position to absolute and later position 50% from the top and translate from it's axis with negative -50%

div {
  height: 100px;
  width: 100px;
  background-color: tomato;
  position: relative;

p {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);


Note that this won't be supported on older browsers, for example IE8, but you can make IE9 and other older browser versions of Chrome and Firefox by using -ms, -moz and -webkit prefixes respectively.

For more information on transform, you can refer here.

How can I make an EXE file from a Python program?

See a short list of python packaging tools on

Oracle: How to filter by date and time in a where clause

In the example that you have provided there is nothing that would throw a SQL command not properly formed error. How are you executing this query? What are you not showing us?

This example script works fine:

create table tableName
(session_start_date_time DATE);

insert into tableName (session_start_date_time) 
values (sysdate+1);

select * from tableName
where session_start_date_time > to_date('12-Jan-2012 16:00', 'DD-MON-YYYY hh24:mi');

As does this example:

create table tableName2
(session_start_date_time TIMESTAMP);

insert into tableName2 (session_start_date_time) 
values (to_timestamp('01/12/2012 16:01:02.345678','mm/dd/yyyy hh24:mi:ss.ff'));

select * from tableName2
where session_start_date_time > to_date('12-Jan-2012 16:00', 'DD-MON-YYYY hh24:mi');

select * from tableName2
where session_start_date_time > to_timestamp('01/12/2012 14:01:02.345678','mm/dd/yyyy hh24:mi:ss.ff');

So there must be something else that is wrong.

Spring 5.0.3 RequestRejectedException: The request was rejected because the URL was not normalized

I encountered the same problem with:

Spring Boot version = 1.5.10
Spring Security version = 4.2.4

The problem occurred on the endpoints, where the ModelAndView viewName was defined with a preceding forward slash. Example:

ModelAndView mav = new ModelAndView("/your-view-here");

If I removed the slash it worked fine. Example:

ModelAndView mav = new ModelAndView("your-view-here");

I also did some tests with RedirectView and it seemed to work with a preceding forward slash.

Best way to define private methods for a class in Objective-C

You could use blocks?

@implementation MyClass

id (^createTheObject)() = ^(){ return [[NSObject alloc] init];};

NSInteger (^addEm)(NSInteger, NSInteger) =
^(NSInteger a, NSInteger b)
    return a + b;

//public methods, etc.

- (NSObject) thePublicOne
    return createTheObject();


I'm aware this is an old question, but it's one of the first I found when I was looking for an answer to this very question. I haven't seen this solution discussed anywhere else, so let me know if there's something foolish about doing this.

SQLite equivalent to ISNULL(), NVL(), IFNULL() or COALESCE()

For the equivalent of NVL() and ISNULL() use:

IFNULL(column, altValue)

column : The column you are evaluating.

altValue : The value you want to return if 'column' is null.


SELECT IFNULL(middle_name, 'N/A') FROM person;

*Note: The COALESCE() function works the same as it does for other databases.


How to JUnit test that two List<E> contain the same elements in the same order?

  • My answer about whether Iterables.elementsEqual is best choice:

Iterables.elementsEqual is enough to compare 2 Lists.

Iterables.elementsEqual is used in more general scenarios, It accepts more general types: Iterable. That is, you could even compare a List with a Set. (by iterate order, it is important)

Sure ArrayList and LinkedList define equals pretty good, you could call equals directly. While when you use a not well defined List, Iterables.elementsEqual is the best choice. One thing should be noticed: Iterables.elementsEqual does not accept null

  • To convert List to array: Iterables.toArray is easer.

  • For unit test, I recommend add empty list to your test case.

How do I delete everything below row X in VBA/Excel?

This function will clear the sheet data starting from specified row and column :

Sub ClearWKSData(wksCur As Worksheet, iFirstRow As Integer, iFirstCol As Integer)

Dim iUsedCols As Integer
Dim iUsedRows As Integer

iUsedRows = wksCur.UsedRange.Row + wksCur.UsedRange.Rows.Count - 1
iUsedCols = wksCur.UsedRange.Column + wksCur.UsedRange.Columns.Count - 1

If iUsedRows > iFirstRow And iUsedCols > iFirstCol Then
    wksCur.Range(wksCur.Cells(iFirstRow, iFirstCol), wksCur.Cells(iUsedRows, iUsedCols)).Clear
End If

End Sub

Python: Removing spaces from list objects

Strings in Python are immutable (meaning that their data cannot be modified) so the replace method doesn't modify the string - it returns a new string. You could fix your code as follows:

for i in hello:
    j = i.replace(' ','')

However a better way to achieve your aim is to use a list comprehension. For example the following code removes leading and trailing spaces from every string in the list using strip:

hello = [x.strip(' ') for x in hello]

Difference between an API and SDK

API is specifications on how to do something, an interface, such as "The railroad tracks are four feet apart, and the metal bar is 1 inch wide" Now that you have the API you can now build a train that will fit on those railroad tracks if you want to go anywhere. API is just information on how to build your code, it doesn't do anything.

SDK is some package of actual tools that already worried about the specifications. "Here's a train, some coal, and a maintenance man. Use it to go from place to place" With the SDK you don't worry about specifics. An SDK is actual code, it can be used by itself to do something, but of course, the train won't start up spontaneously, you still have to get a conductor to control the train.

SDKs also have their own APIs. "If you want to power the train put coal in it", "Pull the blue lever to move the train.", "If the train starts acting funny, call the maintenance man" etc.

How do I create an iCal-type .ics file that can be downloaded by other users?

That will work just fine. You can export an entire calendar with File > Export…, or individual events by dragging them to the Finder.

iCalendar (.ics) files are human-readable, so you can always pop it open in a text editor to make sure no private events made it in there. They consist of nested sections with start with BEGIN: and end with END:. You'll mostly find VEVENT sections (each of which represents an event) and VTIMEZONE sections, each of which represents a time zone that's referenced from one or more events.

Aggregate multiple columns at once

You could try:

agg <- aggregate(list(x$val1, x$val2, x$val3, x$val4), by = list(x$id1, x$id2), mean)

How to convert FormData (HTML5 object) to JSON

This post is already a year old... but, I really, really like the ES6 @dzuc answer. However it is incomplete by not been able to handle multiple selects or checkboxes. This has already pointed and code solutions has been offered. I find them heavy and not optimized. So I wrote a 2 versions based on @dzuc to handle these cases:

  • For ASP style forms where multiple items name could just simple repeated.
let r=Array.from(fd).reduce(
  (o , [k,v]) => (
     ? {...o , [k] : v}
     : {...o , [k] : [...o[k] , v]}
let obj=JSON.stringify(r);

One line Hotshot version:

  • For PHP style forms where the multiple item names must have a [] suffix.
let r=Array.from(fd).reduce(
  (o , [k,v]) => (
    ? (k=k.split('[')[0]
      , (!o[k])
      ? {...o , [k] : [v]}
      : {...o , [k] : [...o[k] , v ]}
    : {...o , [k] : v}
let obj=JSON.stringify(r);

One line Hotshot version:

  • Extension of PHP form that support multi-level arrays.

Since last time I wrote the previous second case, at work it came a case that the PHP form has checkboxes on multi-levels. I wrote a new case to support previous case and this one. I created a snippet to better showcase this case, the result show on the console for this demo, modify this to your need. Tried to optimize it the best I could without compromising performance, however, it compromise some human readability. It takes advantage that arrays are objects and variables pointing to arrays are kept as reference. No hotshot for this one, be my guest.

let nosubmit = (e) => {_x000D_
  const f = Array.from(new FormData(;_x000D_
  const obj = f.reduce((o, [k, v]) => {_x000D_
    let a = v,_x000D_
      b, i,_x000D_
      m = k.split('['),_x000D_
      n = m[0],_x000D_
      l = m.length;_x000D_
    if (l > 1) {_x000D_
      a = b = o[n] || [];_x000D_
      for (i = 1; i < l; i++) {_x000D_
        m[i] = (m[i].split(']')[0] || b.length) * 1;_x000D_
        b = b[m[i]] = ((i + 1) == l) ? v : b[m[i]] || [];_x000D_
    return { ...o, [n]: a };_x000D_
  }, {});_x000D_
document.querySelector('#theform').addEventListener('submit', nosubmit, {capture: true});
<h1>Multilevel Form</h1>_x000D_
<form action="#" method="POST" enctype="multipart/form-data" id="theform">_x000D_
  <input type="hidden" name="_id" value="93242" />_x000D_
  <input type="hidden" name="_fid" value="45c0ec96929bc0d39a904ab5c7af70ef" />_x000D_
    <select name="uselect">_x000D_
      <option value="A">A</option>_x000D_
      <option value="B">B</option>_x000D_
      <option value="C">C</option>_x000D_
  <br /><br />_x000D_
  <label>Checkboxes one level:<br/>_x000D_
    <input name="c1[]" type="checkbox" checked value="1"/>v1 _x000D_
    <input name="c1[]" type="checkbox" checked value="2"/>v2_x000D_
    <input name="c1[]" type="checkbox" checked value="3"/>v3_x000D_
  <br /><br />_x000D_
  <label>Checkboxes two levels:<br/>_x000D_
    <input name="c2[0][]" type="checkbox" checked value="4"/>0 v4 _x000D_
    <input name="c2[0][]" type="checkbox" checked value="5"/>0 v5_x000D_
    <input name="c2[0][]" type="checkbox" checked value="6"/>0 v6_x000D_
    <input name="c2[1][]" type="checkbox" checked value="7"/>1 v7 _x000D_
    <input name="c2[1][]" type="checkbox" checked value="8"/>1 v8_x000D_
    <input name="c2[1][]" type="checkbox" checked value="9"/>1 v9_x000D_
  <br /><br />_x000D_
    <input type="radio" name="uradio" value="yes">YES_x000D_
    <input type="radio" name="uradio" checked value="no">NO_x000D_
  <br /><br />_x000D_
  <input type="submit" value="Submit" />_x000D_

Python lookup hostname from IP with 1 second timeout

What you're trying to accomplish is called Reverse DNS lookup.

# => (hostname, alias-list, IP)

However, for the timeout part I have read about people running into problems with this. I would check out PyDNS or this solution for more advanced treatment.

adb shell command to make Android package uninstall dialog appear

Use this command in cmd:

adb shell pm uninstall -k com.packagename

For example:

adb shell pm uninstall -k com.fedmich.pagexray

The -k flag tells the package manager to keep the cache and data directories around, even though the app is removed. If you want a clean uninstall, don't specify -k.

CSS blur on background image but not on content


Unfortunately Mozilla has really dropped the ball and taken it's time with the feature. I'm personally hoping it makes it in to the next Firefox ESR as that is what the next major version of Waterfox will use.

MDN (Mozilla Developer Network) article:

Mozilla implementation:

From the MDN documentation page:

/* URL to SVG filter */
backdrop-filter: url(commonfilters.svg#filter);

/* <filter-function> values */
backdrop-filter: blur(2px);
backdrop-filter: brightness(60%);
backdrop-filter: contrast(40%);
backdrop-filter: drop-shadow(4px 4px 10px blue);
backdrop-filter: grayscale(30%);
backdrop-filter: hue-rotate(120deg);
backdrop-filter: invert(70%);
backdrop-filter: opacity(20%);
backdrop-filter: sepia(90%);
backdrop-filter: saturate(80%);

/* Multiple filters */
backdrop-filter: url(filters.svg#filter) blur(4px) saturate(150%);

How can I fix WebStorm warning "Unresolved function or method" for "require" (Firefox Add-on SDK)

In PHPStorm, it's a bit easier: you can just search for NPM in settings or:

File > Settings > Language & Frameworks > Node.js and NPM

Then click the enable button (apparently in new versions, it is called "Coding assistance for Node").

How to get html to print return value of javascript function?

It depends what you're going for. I believe the closest thing JS has to print is:

document.write( produceMessage() );

However, it may be more prudent to place the value inside a span or a div of your choosing like:

document.getElementById("mySpanId").innerHTML = produceMessage();

ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean

The solution is:

I explicitly set the below property to none in application.yml file.

    web-application-type: none

how to convert a string to date in mysql?

As was told at MySQL Using a string column with date text as a date field, you can do

SELECT  STR_TO_DATE(yourdatefield, '%m/%d/%Y')
FROM    yourtable

You can also handle these date strings in WHERE clauses. For example

SELECT whatever
  FROM yourtable
 WHERE STR_TO_DATE(yourdatefield, '%m/%d/%Y') > CURDATE() - INTERVAL 7 DAY

You can handle all kinds of date/time layouts this way. Please refer to the format specifiers for the DATE_FORMAT() function to see what you can put into the second parameter of STR_TO_DATE().

Batch Extract path and filename from a variable

if you want infos from the actual running batchfile, try this :

@echo off
set myNameFull=%0
echo myNameFull     %myNameFull%
set myNameShort=%~n0
echo myNameShort    %myNameShort%
set myNameLong=%~nx0
echo myNameLong     %myNameLong%
set myPath=%~dp0
echo myPath         %myPath%
set myLogfileWpath=%myPath%%myNameShort%.log
echo myLogfileWpath %myLogfileWpath%

more samples? C:> HELP CALL

%0 = parameter 0 = batchfile %1 = parameter 1 - 1st par. passed to batchfile... so you can try that stuff (e.g. "~dp") between 1st (e.g. "%") and last (e.g. "1") also for parameters

SQL Error: ORA-00933: SQL command not properly ended

Semicolon ; on the end of command had caused the same error on me.

                + "'" + txtUsername.Text + "',"
                + "'" + txtPassword.Text + "',"
                + "'" + txtFirstname.Text + "',"
                + "'" + txtLastname.Text + "');"; <== Semicolon in "" is the cause.
                                                      Removing it will be fine.

Hope it helps.

ping: Temporary failure in name resolution

I've faced the exactly same problem but I've fixed it with another approache.

Using Ubuntu 18.04, first disable systemd-resolved service.

sudo systemctl disable systemd-resolved.service

Stop the service

sudo systemctl stop systemd-resolved.service

Then, remove the link to /run/systemd/resolve/stub-resolv.conf in /etc/resolv.conf

sudo rm /etc/resolv.conf

Add a manually created resolv.conf in /etc/

sudo vim /etc/resolv.conf

Add your prefered DNS server there


I've tested this with success.

Downloading a large file using curl

//This is the file where we save the    information
$fp = fopen (dirname(__FILE__) . '/localfile.tmp', 'w+');
//Here is the file we are downloading, replace spaces with %20
$ch = curl_init(str_replace(" ","%20",$url));
curl_setopt($ch, CURLOPT_TIMEOUT, 50);
// write curl response to file
curl_setopt($ch, CURLOPT_FILE, $fp); 
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
// get curl response

How can I do a BEFORE UPDATED trigger with sql server?

MSSQL does not support BEFORE triggers. The closest you have is INSTEAD OF triggers but their behavior is different to that of BEFORE triggers in MySQL.

You can learn more about them here, and note that INSTEAD OF triggers "Specifies that the trigger is executed instead of the triggering SQL statement, thus overriding the actions of the triggering statements." Thus, actions on the update may not take place if the trigger is not properly written/handled. Cascading actions are also affected.

You may instead want to use a different approach to what you are trying to achieve.

JQuery window scrolling event?

Try this:

    var aTop = $('.ad').height();
        alert('header just passed.');
        // instead of alert you can use to show your ad
        // something like $('#footAd').slideup();

Clearing an HTML file upload field via JavaScript

You can't set the input value in most browsers, but what you can do is create a new element, copy the attributes from the old element, and swap the two.

Given a form like:

    <input id="fileInput" name="fileInput" type="file" /> 

The straight DOM way:

function clearFileInput(id) 
    var oldInput = document.getElementById(id); 

    var newInput = document.createElement("input"); 

    newInput.type = "file"; =; =; 
    newInput.className = oldInput.className; =; 
    // TODO: copy any other relevant attributes 

    oldInput.parentNode.replaceChild(newInput, oldInput); 


Simple DOM way. This may not work in older browsers that don't like file inputs:

oldInput.parentNode.replaceChild(oldInput.cloneNode(), oldInput);

The jQuery way:


// .val('') required for FF compatibility as per @nmit026

Resetting the whole form via jQuery:

How to suppress "error TS2533: Object is possibly 'null' or 'undefined'"?

This is not an answer for the OP but I've seen a lot of people confused about how to avoid this error in the comments. This is a simple way to pass the compiler check

if (typeof(object) !== 'undefined') {
    // your code

Note: This won't work

if (object !== undefined) {
        // your code

How to wrap text in textview in Android

Constraint Layout


  • Ensure your layout width is zero
  • left / right constraints are defined
  • layout height of wrap_content allows expansion up/down.
  • Set android:maxLines="2" to prevent vertical expansion (2 is just an e.g.)
  • Ellipses are prob. a good idea with max lines android:ellipsize="end"

0dp width allows left/right constraints to determine how wide your widget is.

Setting left/right constraints sets the actual width of your widget, within which your text will wrap.

Constraint Layout docs

Using crontab to execute script every minute and another every 24 hours

This is the format of /etc/crontab:

# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# |  |  |  |  |
# *  *  *  *  * user-name  command to be executed

I recommend copy & pasting that into the top of your crontab file so that you always have the reference handy. RedHat systems are setup that way by default.

To run something every minute:

* * * * * username /var/www/html/a.php

To run something at midnight of every day:

0 0 * * * username /var/www/html/reset.php

You can either include /usr/bin/php in the command to run, or you can make the php scripts directly executable:

chmod +x file.php

Start your php file with a shebang so that your shell knows which interpreter to use:

// your code here

Executing command line programs from within python

I am not familiar with sox, but instead of making repeated calls to the program as a command line, is it possible to set it up as a service and connect to it for requests? You can take a look at the connection interface such as sqlite for inspiration.

Google Maps API warning: NoApiKeys

A key currently still is not required ("required" in the meaning "it will not work without"), but I think there is a good reason for the warning.

But in the documentation you may read now : "All JavaScript API applications require authentication."

I'm sure that it's planned for the future , that Javascript API Applications will not work without a key(as it has been in V2).

You better use a key when you want to be sure that your application will still work in 1 or 2 years.

What is the difference between static_cast<> and C style casting?

Since there are many different kinds of casting each with different semantics, static_cast<> allows you to say "I'm doing a legal conversion from one type to another" like from int to double. A plain C-style cast can mean a lot of things. Are you up/down casting? Are you reinterpreting a pointer?

SQLSTATE[HY000] [2002] Connection refused within Laravel homestead

After you put all configuration on .env file, if you already run php artisan serve, RESTART IT.

How to keep a Python script output window open?

Try this,

import sys

stat='idlelib' in sys.modules

if stat==False:

This will only stop console window, not the IDLE.

Does Notepad++ show all hidden characters?

Double check your text with the Hex Editor Plug-in. In your case there may have been some control characters which have crept into your text. Usually you'll look at the white-space, and it will say 32 32 32 32, or for Unicode 32 00 32 00 32 00 32 00. You may find the problem this way, providing there isn't masses of code.

Download the Hex Plugin from here;

Angular exception: Can't bind to 'ngForIn' since it isn't a known native property

Try to import import { CommonModule } from '@angular/common'; in angular final as *ngFor ,*ngIf all are present in CommonModule

How can I open multiple files using "with open" in Python?

From Python 3.10 there is a new feature of Parenthesized context managers, which permits syntax like:

with (
    open("a", "w") as a,
    open("b", "w") as b

How to see if an object is an array without using reflection?

There is no subtyping relationship between arrays of primitive type, or between an array of a primitive type and array of a reference type. See JLS 4.10.3.

Therefore, the following is incorrect as a test to see if obj is an array of any kind:

public boolean isArray(final Object obj) {
    return obj instanceof Object[];

Specifically, it doesn't work if obj is 1-D array of primitives. (It does work for primitive arrays with higher dimensions though, because all array types are subtypes of Object. But it is moot in this case.)

I use Google GWT so I am not allowed to use reflection :(

The best solution (to the isArray array part of the question) depends on what counts as "using reflection".

  • In GWT, calling obj.getClass().isArray() does not count as using reflection1, so that is the best solution.

  • Otherwise, the best way of figuring out whether an object has an array type is to use a sequence of instanceof expressions.

    public boolean isArray(final Object obj) {
        return obj instanceof Object[] || obj instanceof boolean[] ||
           obj instanceof byte[] || obj instanceof short[] ||
           obj instanceof char[] || obj instanceof int[] ||
           obj instanceof long[] || obj instanceof float[] ||
           obj instanceof double[];
  • You could also try messing around with the name of the object's class as follows, but the call to obj.getClass() is bordering on reflection.

    public boolean isArray(final Object obj) {
        return obj.getClass().toString().charAt(0) == '[';

1 - More precisely, the Class.isArray method is listed as supported by GWT in this page.

Automatically create an Enum based on values in a database lookup table?

One way to keep the Enums and to create a Dynamic list of values at the same time is to use the Enums that you currently have with a Dynamically created Dictionary.

Since most Enums are used in the context that they are defined to be used, and the "dynamic enums" will be supported by dynamic processes, you can distinguish the 2.

The first step is to create a table/collection that houses the IDs and References for the Dynamic Entries. In the table you will autoincrement much larger than your largest Enum value.

Now comes the part for your dynamic Enums, I am assuming that you will be using the Enums to create a set of conditions that apply a set of rules, some are dynamically generated.

Get integer from database
If Integer is in Enum -> create Enum -> then run Enum parts
If Integer is not a Enum -> create Dictionary from Table -> then run Dictionary parts.

Reading CSV files using C#

First of all need to understand what is CSV and how to write it.

  1. Every next string ( /r/n ) is next "table" row.
  2. "Table" cells is separated by some delimiter symbol. Most often used symbols is \t or ,
  3. Every cell possibly can contain this delimiter symbol (cell must to start with quotes symbol and ends with this symbol in this case)
  4. Every cell possibly can contains /r/n sybols (cell must to start with quotes symbol and ends with this symbol in this case)

The easiest way for C#/Visual Basic to work with CSV files is to use standard Microsoft.VisualBasic library. You just need to add needed reference, and the following string to your class:

using Microsoft.VisualBasic.FileIO;

Yes, you can use it in C#, don't worry. This library can read relatively big files and supports all of needed rules, so you will be able to work with all of CSV files.

Some time ago I had wrote simple class for CSV read/write based on this library. Using this simple class you will be able to work with CSV like with 2 dimensions array. You can find my class by the following link:

Simple example of using:

Csv csv = new Csv("\t");//delimiter symbol


var row1Cell6Value = csv.Rows[0][5];



Resource interpreted as Document but transferred with MIME type application/zip

Just ran into this and none of the other information I could find helped: it was a stupid error: I was sending output to the browser before starting the file download. Surprisingly, I found no helpful errors found (like "headers already sent" etc.). Hopefully, this saves someone else some grief!

check if a file is open in Python

None of the other provided examples would work for me when dealing with this specific issue with excel on windows 10. The only other option I could think of was to try and rename the file or directory containing the file temporarily, then rename it back.

import os

    os.rename('file.xls', 'tempfile.xls')
    os.rename('tempfile.xls', 'file.xls')
except OSError:
    print('File is still open.')

Object does not support item assignment error

The error seems clear: model objects do not support item assignment. MyModel.objects.latest('id')['foo'] = 'bar' will throw this same error.

It's a little confusing that your model instance is called projectForm...

To reproduce your first block of code in a loop, you need to use setattr

for k,v in session_results.iteritems():
    setattr(projectForm, k, v)

design a stack such that getMinimum( ) should be O(1)

Here is my Code which runs with O(1). The previous code which I posted had problem when the minimum element gets popped. I modified my code. This one uses another Stack that maintains minimum element present in stack above the current pushed element.

 class StackDemo
    int[] stk = new int[100];
    int top;
    public StackDemo()
        top = -1;
    public void Push(int value)
        if (top == 100)
            Console.WriteLine("Stack Overflow");
            stk[++top] = value;
    public bool IsEmpty()
        if (top == -1)
            return true;
            return false;
    public int Pop()
        if (IsEmpty())
            Console.WriteLine("Stack Underflow");
            return 0;
            return stk[top--];
    public void Display()
        for (int i = top; i >= 0; i--)
class MinStack : StackDemo
    int top;
    int[] stack = new int[100];
    StackDemo s1; int min;
    public MinStack()
        top = -1;
        s1 = new StackDemo();
    public void PushElement(int value)
        if (top == 100)
            Console.WriteLine("Stack Overflow");
        if (top == -1)
            stack[++top] = value;
            stack[++top] = value;   
            //  stack[++top]=value;
            int ele = PopElement();
            stack[++top] = ele;
            int a = MininmumElement(min, value);
              stack[++top] = min;

                stack[++top] = value;
                stack[++top] = a;

    public int PopElement()

        if (top == -1)
            return 1000;
            min = stack[top--];
            return stack[top--];

    public int PopfromStack()
        if (top == -1)
            return 1000;
            return PopElement();
    public int MininmumElement(int a,int b)
        if (a > b)
            return b;
            return a;
    public int StackTop()
        return stack[top];
    public void DisplayMinStack()
        for (int i = top; i >= 0; i--)
class Program
    static void Main(string[] args)
        MinStack ms = new MinStack();
        Console.WriteLine("Min Stack");
        Console.WriteLine("Minimum Element:"+ms.StackTop());

        Console.WriteLine("Min Stack");
        Console.WriteLine("Minimum Element:" + ms.StackTop());

How do I convert a pandas Series or index to a Numpy array?

I converted the pandas dataframe to list and then used the basic list.index(). Something like this:

dd = list(zone[0]) #Where zone[0] is some specific column of the table
idx = dd.index(filename[i])

You have you index value as idx.

Plugin org.apache.maven.plugins:maven-compiler-plugin or one of its dependencies could not be resolved

Have you tried to remove the proxy username and password? A similar poster encountered that issue:

Could not calculate build plan: Plugin org.apache.maven.plugins:maven-jar-plugin:2.3.2 or one of its dependencies could not be resolved

Failing that I found the following worked:

  1. Delete project in Eclipse (but do not delete the contents on disk)
  2. Delete all files in your Maven repository
  3. Re-download all Maven dependencies:

mvn dependency:resolve

  1. Start up Eclipse
  2. Ensure that Eclipse is configured to use your external Maven installation (Window->Preferences->Maven->Installations)
  3. Re-import the existing project(s) into Eclipse
  4. Ensure that there are no Maven Eclipse plugin errors on the final screen of the project import

What are the differences between Visual Studio Code and Visual Studio?

Visual Studio (full version) is a "full-featured" and "convenient" development environment.

Visual Studio (free "Express" versions - only until 2017) are feature-centered and simplified versions of the full version. Feature-centered meaning that there are different versions (Visual Studio Web Developer, Visual Studio C#, etc.) depending on your goal.

Visual Studio (free Community edition - since 2015) is a simplified version of the full version and replaces the separated express editions used before 2015.

Visual Studio Code (VSCode) is a cross-platform (Linux, Mac OS, Windows) editor that can be extended with plugins to your needs.

For example, if you want to create an ASP.NET application using Visual Studio Code you need to perform several steps on your own to setup the project. There is a separate tutorial for each OS.

How are software license keys generated?

I've not got any experience with what people actually do to generate CD keys, but (assuming you're not wanting to go down the road of online activation) here are a few ways one could make a key:

  • Require that the number be divisible by (say) 17. Trivial to guess, if you have access to many keys, but the majority of potential strings will be invalid. Similar would be requiring that the checksum of the key match a known value.

  • Require that the first half of the key, when concatenated with a known value, hashes down to the second half of the key. Better, but the program still contains all the information needed to generate keys as well as to validate them.

  • Generate keys by encrypting (with a private key) a known value + nonce. This can be verified by decrypting using the corresponding public key and verifying the known value. The program now has enough information to verify the key without being able to generate keys.

These are still all open to attack: the program is still there and can be patched to bypass the check. Cleverer might be to encrypt part of the program using the known value from my third method, rather than storing the value in the program. That way you'd have to find a copy of the key before you could decrypt the program, but it's still vulnerable to being copied once decrypted and to having one person take their legit copy and use it to enable everyone else to access the software.

How to force reloading php.ini file?

To force a reload of the php.ini you should restart apache.

Try sudo service apache2 restart from the command line. Or sudo /etc/init.d/apache2 restart

How to convert "0" and "1" to false and true

You can use that form:

return returnValue.Equals("1") ? true : false;

Or more simply (thanks to Jurijs Kastanovs):

return returnValue.Equals("1");

How to use "svn export" command to get a single file from the repository?

I know the OP was asking about doing the export from the command line, but just in case this is helpful to anyone else out there...

You could just let Eclipse (plus one of the plugins discussed here) do the work for you.

Obviously, downloading Eclipse just for doing a single export is overkill, but if you are already using it for development, you can also do an svn export simply from your IDE's context menu when browsing an SVN repository.


  • easier for those not so familiar with using SVN at the command-line level (but you can learn about what happens at the command-line level by looking at the SVN console with a range of commands)
  • you'd already have your SVN details set up and wouldn't have to worry about authenticating, etc.
  • you don't have to worry about mistyping the URL, or remembering the order of parameters
  • you can specify in a dialog which directory you'd like to export to
  • you can specify in a dialog whether you'd like to export from TRUNK/HEAD or use a specific revision

How do I efficiently iterate over each entry in a Java Map?

With Java 8, you can iterate Map using forEach and lambda expression,

map.forEach((k, v) -> System.out.println((k + ":" + v)));

JComboBox Selection Change Listener?

Here is creating a ComboBox adding a listener for item selection change:

JComboBox comboBox = new JComboBox();

comboBox.setBounds(84, 45, 150, 20);

JComboBox comboBox_1 = new JComboBox();
comboBox_1.setBounds(84, 97, 150, 20);
comboBox.addItemListener(new ItemListener() {
    public void itemStateChanged(ItemEvent arg0) {
        //Do Something

Tokenizing Error: java.util.regex.PatternSyntaxException, dangling metacharacter '*'

It is because * is used as a metacharacter to signify one or more occurences of previous character. So if i write M* then it will look for files MMMMMM..... ! Here you are using * as the only character so the compiler is looking for the character to find multiple occurences of,so it throws the exception.:)

Git checkout: updating paths is incompatible with switching branches

I believe this occurs when you are trying to checkout a remote branch that your local git repo is not aware of yet. Try:

git remote show origin

If the remote branch you want to checkout is under "New remote branches" and not "Tracked remote branches" then you need to fetch them first:

git remote update
git fetch

Now it should work:

git checkout -b local-name origin/remote-name

SQL Server: Filter output of sp_who2

Yes, by capturing the output of sp_who2 into a table and then selecting from the table, but that would be a bad way of doing it. First, because sp_who2, despite its popularity, its an undocumented procedure and you shouldn't rely on undocumented procedures. Second because all sp_who2 can do, and much more, can be obtained from sys.dm_exec_requests and other DMVs, and show can be filtered, ordered, joined and all the other goodies that come with queriable rowsets.

How to rename a table column in Oracle 10g

suppose supply_master is a table, and

SQL>desc supply_master;


SQL>alter table Supply_master rename column ADDRESS1 TO ADDR;
Table altered

SQL> desc Supply_master;
 ADDR   ///////////this has been renamed........//////////////                

Resizing image in Java

Resize image with high quality:

private static InputStream resizeImage(InputStream uploadedInputStream, String fileName, int width, int height) {

        try {
            BufferedImage image =;
            Image originalImage= image.getScaledInstance(width, height, Image.SCALE_DEFAULT);

            int type = ((image.getType() == 0) ? BufferedImage.TYPE_INT_ARGB : image.getType());
            BufferedImage resizedImage = new BufferedImage(width, height, type);

            Graphics2D g2d = resizedImage.createGraphics();
            g2d.drawImage(originalImage, 0, 0, width, height, null);

            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

            ImageIO.write(resizedImage, fileName.split("\\.")[1], byteArrayOutputStream);
            return new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
        } catch (IOException e) {
            // Something is going wrong while resizing image
            return uploadedInputStream;

Check if a Python list item contains a string inside another string

I am new to Python. I got the code below working and made it easy to understand:

my_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
for str in my_list:
    if 'abc' in str:

VBA Excel - Insert row below with same format including borders and frames

When inserting a row, regardless of the CopyOrigin, Excel will only put vertical borders on the inserted cells if the borders above and below the insert position are the same.

I'm running into a similar (but rotated) situation with inserting columns, but Copy/Paste is too slow for my workbook (tens of thousands of rows, many columns, and complex formatting).

I've found three workarounds that don't require copying the formatting from the source row:

  1. Ensure the vertical borders are the same weight, color, and pattern above and below the insert position so Excel will replicate them in your new row. (This is the "It hurts when I do this," "Stop doing that!" answer.)

  2. Use conditional formatting to establish the border (with a Formula of "=TRUE"). The conditional formatting will be copied to the new row, so you still end up with a border.Caveats:

    • Conditional formatting borders are limited to the thin-weight lines.
    • Works best for sheets where borders are relatively consistent so you don't have to create a bunch of conditional formatting rules.
  3. Set the border on the inserted row in VBA after inserting the row. Setting a border on a range is much faster than copying and pasting all of the formatting just to get a border (assuming you know ahead of time what the border should be or can sample it from the row above without losing performance).

jQuery .each() index?

$('#list option').each(function(intIndex){
//do stuff

How can moment.js be imported with typescript?

1. install moment

npm install moment --save

2. test this code in your typescript file

import moment = require('moment');


Delay/Wait in a test case of Xcode UI testing

sleep will block the thread

"No run loop processing occurs while the thread is blocked."

you can use waitForExistence

let app = XCUIApplication()

if let label = app.staticTexts["Hello, world!"] {
label.waitForExistence(timeout: 5)

Google Map API v3 ~ Simply Close an infowindow?

Or you can share/reuse the same infoWindow object. See this google demo for reference.

Same code from demo

var Demo = { map: null,  infoWindow: null

 * Called when clicking anywhere on the map and closes the info window.
Demo.closeInfoWindow = function() {

 * Opens the shared info window, anchors it to the specified marker, and
 * displays the marker's position as its content.
Demo.openInfoWindow = function(marker) {
  var markerLatLng = marker.getPosition();
    '<b>Marker position is:</b><br/>',,
    ', ',
  ].join(''));, marker);

 * Called only once on initial page load to initialize the map.
Demo.init = function() {
  // Create single instance of a Google Map.
  var centerLatLng = new google.maps.LatLng(37.789879, -122.390442); = new google.maps.Map(document.getElementById('map-canvas'), {
    zoom: 13,
    center: centerLatLng,
    mapTypeId: google.maps.MapTypeId.ROADMAP

  // Create a single instance of the InfoWindow object which will be shared
  // by all Map objects to display information to the user.
  Demo.infoWindow = new google.maps.InfoWindow();

  // Make the info window close when clicking anywhere on the map.
  google.maps.event.addListener(, 'click', Demo.closeInfoWindow);

  // Add multiple markers in a few random locations around San Francisco.
  // First random marker
  var marker1 = new google.maps.Marker({
    position: centerLatLng

  // Register event listeners to each marker to open a shared info
  // window displaying the marker's position when clicked or dragged.
  google.maps.event.addListener(marker1, 'click', function() {

  // Second random marker
  var marker2 = new google.maps.Marker({
    position: new google.maps.LatLng(37.787814,-122.40764),
    draggable: true

  // Register event listeners to each marker to open a shared info
  // window displaying the marker's position when clicked or dragged.
  google.maps.event.addListener(marker2, 'click', function() {

  // Third random marker
  var marker3 = new google.maps.Marker({
    position: new google.maps.LatLng(37.767568,-122.391665),
    draggable: true

  // Register event listeners to each marker to open a shared info
  // window displaying the marker's position when clicked or dragged.
  google.maps.event.addListener(marker3, 'click', function() {

How to get english language word database?

You may check *spell en-GB dictionary used by Mozilla, OpenOffice, plenty of other software.

'foo' was not declared in this scope c++

In general, in C++ functions have to be declared before you call them. So sometime before the definition of getSkewNormal(), the compiler needs to see the declaration:

double integrate (double start, double stop, int numSteps, Evaluatable evalObj);

Mostly what people do is put all the declarations (only) in the header file, and put the actual code -- the definitions of the functions and methods -- into a separate source (*.cc or *.cpp) file. This neatly solves the problem of needing all the functions to be declared.

How Can I Override Style Info from a CSS Class in the Body of a Page?

Eli, it is important to remember that in css specificity goes a long way. If your inline css is using the !important and isn't overriding the imported stylesheet rules then closely observe the code using a tool such as 'firebug' for firefox. It will show you the css being applied to your element. If there is a syntax error firebug will show you in the warning panel that it has thrown out the declaration.

Also remember that in general an id is more specific than a class is more specific than an element.

Hope that helps.


Convert RGB values to Integer

int rgb = new Color(r, g, b).getRGB();

WAITING at sun.misc.Unsafe.park(Native Method)

From the stack trace it's clear that, the ThreadPoolExecutor > Worker thread started and it's waiting for the task to be available on the BlockingQueue(DelayedWorkQueue) to pick the task and execute.So this thread will be in WAIT status only as long as get a SIGNAL from the publisher thread.

Kill some processes by .exe file name

My solution is to use Process.GetProcess() for listing all the processes.

By filtering them to contain the processes I want, I can then run Process.Kill() method to stop them:

var chromeDriverProcesses = Process.GetProcesses().
    Where(pr => pr.ProcessName == "chromedriver"); // without '.exe'
foreach (var process in chromeDriverProcesses)


In case if want to use async approach with some useful recent methods from the C# 8 (Async Enumerables), then check this out:

const string processName = "chromedriver"; // without '.exe'
await Process.GetProcesses()
             .Where(pr => pr.ProcessName == processName)
             .ForEachAsync(p => p.Kill());

Note: using async methods doesn't always mean code will run faster, but it will not waste the CPU time and prevent the foreground thread from hanging while doing the operations. In any case, you need to think about what version you might want.

Best way to format if statement with multiple conditions

if (   ( single conditional expression A )
    && ( single conditional expression B )
    && ( single conditional expression C )

Formatting a multiple conditional expressions in an if-else statement this way:

  1. allows for enhanced readability:
    a. all binary logical operations {&&, ||} in the expression shown first
    b. both conditional operands of each binary operation are obvious because they align vertically
    c. nested logical expressions operations are made obvious using indentation, just like nesting statements inside clause
  2. requires explicit parenthesis (not rely on operator precedence rules)
    a. this avoids a common static analysis errors
  3. allows for easier debugging
    a. disable individual single conditional tests with just a //
    b. set a break point just before or after any individual test
    c. e.g. ...
// disable any single conditional test with just a pre-pended '//'
// set a break point before any individual test
// syntax '(1 &&' and '(0 ||' usually never creates any real code
if (   1
    && ( single conditional expression A )
    && ( single conditional expression B )
    && (   0
        || ( single conditional expression C )
        || ( single conditional expression D )
   ... ;

   ... ;

Convert data.frame column format from character to factor

Unless you need to identify the columns automatically, I found this to be the simplest solution:

df$name <- as.factor(df$name)

This makes column name in dataframe df a factor.

Getting Connection timed out in android

public JSONObject RequestWithHttpUrlConn(String _url, String param){

    HttpURLConnection con = null;
    URL url;
    String response = "";
    Scanner inStream = null;
    PrintWriter out = null;
    try {
        url = new URL(_url);
        con = (HttpURLConnection) url.openConnection();
        if(param != null){
        con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        out = new PrintWriter(con.getOutputStream());
        if(param != null){
        inStream = new Scanner(con.getInputStream());

    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
    } finally{
        if(con != null){
        }if(inStream != null){
        }if(out != null){

How do you find what version of libstdc++ library is installed on your linux machine?

The mechanism I tend to use is a combination of readelf -V to dump the .gnu.version information from libstdc++, and then a lookup table that matches the largest GLIBCXX_ value extracted.

readelf -sV /usr/lib/ | sed -n 's/.*@@GLIBCXX_//p' | sort -u -V | tail -1

if your version of sort is too old to have the -V option (which sorts by version number) then you can use:

tr '.' ' ' | sort -nu -t ' ' -k 1 -k 2 -k 3 -k 4 | tr ' ' '.'

instead of the sort -u -V, to sort by up to 4 version digits.

In general, matching the ABI version should be good enough.

If you're trying to track down the<VERSION>, though, you can use a little bash like:

while [ -h $file ]; do file=$(ls -l $file | sed -n 's/.*-> //p'); done
echo ${file#*.so.}

so for my system this yielded 6.0.10.

If, however, you're trying to get a binary that was compiled on systemX to work on systemY, then these sorts of things will only get you so far. In those cases, carrying along a copy of the that was used for the application, and then having a run script that does an:

export LD_LIBRARY_PATH=<directory of stashed>
exec application.bin "$@"

generally works around the issue of the .so that is on the box being incompatible with the version from the application. For more extreme differences in environment, I tend to just add all the dependent libraries until the application works properly. This is the linux equivalent of working around what, for windows, would be considered dll hell.

Java balanced expressions check {[()]}

Please try this I checked it. It works correctly

import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
public class CloseBrackets {
    private static Map<Character, Character> leftChar = new HashMap<>();
    private static Map<Character, Character> rightChar = new HashMap<>();

    static {
        leftChar.put('(', '(');
        rightChar.put(')', '(');
        leftChar.put('[', '[');
        rightChar.put(']', '[');
        leftChar.put('{', '{');
        rightChar.put('}', '{');

    public static void main(String[] args) throws IOException {
        BufferedReader bf = new BufferedReader(new InputStreamReader(;
        String st = bf.readLine();

    public static boolean isBalanced(String str) {

        boolean result = false;
        if (str.length() < 2)
            return false;
        Stack<Character> stack = new Stack<>();
        /* For Example I gave input 
         * str = "{()[]}" 

        for (int i = 0; i < str.length(); i++) {

            char ch = str.charAt(i);
            if (!rightChar.containsKey(ch) && !leftChar.containsKey(ch)) {
            // Left bracket only add to stack. Other wise it will goes to else case 
            // For both above input how value added in stack 
            // "{(" after close bracket go to else case
            if (leftChar.containsKey(ch)) {
            } else {
                if (!stack.isEmpty()) {
                    // For both input how it performs
                    // 3rd character is close bracket so it will pop . pop value is "(" and map value for ")" key will "(" . So both are same . 
                    // it will return true. 
                    // now stack will contain only "{" , and travers to next up to end.
                    if (stack.pop() == rightChar.get(ch).charValue() || stack.isEmpty()) {
                        result = true;
                    } else {
                        return false;
                } else {
                    return false;

        if (!stack.isEmpty())
            return result = false;
        return result;

What is the difference between angular-route and angular-ui-router?

ngRoute is a module developed by the Angular.js team which was earlier part of the Angular core.

ui-router is a framework which was made outside the Angular.js project to improve and enhance routing capabalities.

How to find the most recent file in a directory using .NET, and without looping?

Short and simple:

new DirectoryInfo(path).GetFiles().OrderByDescending(o => o.LastWriteTime).FirstOrDefault();

Unable to execute dex: Multiple dex files define

Even after going through multiple answers, no solution worked for me.

I deleted "Android Dependencies" from the build path. Added all the jar files again to the build path and the error was gone. Somehow eclipse seemed to cache the things.

Create list or arrays in Windows Batch

Sometimes the array element may be very long, at that time you can create an array in this way:

set list=a
set list=%list%;b 
set list=%list%;c 
set list=%list%;d

Then show it:

@echo off
for %%a in (%list%) do ( 
 echo %%a

What design patterns are used in Spring framework?

There are loads of different design patterns used, but there are a few obvious ones:

  • Proxy - used heavily in AOP, and remoting.

  • Singleton - beans defined in spring config files are singletons by default.

  • Template method - used extensively to deal with boilerplate repeated code (such as closing connections cleanly, etc..). For example JdbcTemplate, JmsTemplate, JpaTemplate.

Update following comments: For MVC, you might want to read the MVC Reference

Some obvious patterns in use in MVC:

  • Model View Controller :-) . The advantage with Spring MVC is that your controllers are POJOs as opposed to being servlets. This makes for easier testing of controllers. One thing to note is that the controller is only required to return a logical view name, and the view selection is left to a separate ViewResolver. This makes it easier to reuse controllers for different view technologies.

  • Front Controller. Spring provides DispatcherServlet to ensure an incoming request gets dispatched to your controllers.

  • View Helper - Spring has a number of custom JSP tags, and velocity macros, to assist in separating code from presentation in views.

Executing JavaScript without a browser?

I use Ubuntu 12.10 and js from commandline

It is available with my installation of java:

el@apollo:~/foo$ java -version
java version "1.6.0_27"
el@apollo:~/foo$ which js

Some examples:

el@apollo:~/foo$ js
> 5

> console.log("hello");

> var f = function(){ console.log("derp"); };
> f();

> var mybool = new Boolean();
> mybool
> mybool == true
> mybool == false

> var myobj = {};
> myobj.skipper = "on my mark, engage!"
'on my mark, engage!'
> myobj.skipper.split(" ");
[ 'on',
  'engage!' ]

The sky is the limit, then keep right on going.

Change a Git remote HEAD to point to something besides master

Update: This only works for the local copy of the repository (the "client"). Please see others' comments below.

With a recent version of git (Feb 2014), the correct procedure would be:

git remote set-head $REMOTE_NAME $BRANCH

So for example, switching the head on remote origin to branch develop would be:

git remote set-head origin develop

How to select the first element of a set with JSTL?

Work for arrays and lists only, not for set.

Display number with leading zeros

x = [1, 10, 100]
for i in x:
    print '%02d' % i

results in:


Read more information about string formatting using % in the documentation.

check if "it's a number" function in Oracle

Function for mobile number of length 10 digits and starting from 9,8,7 using regexp

   "MOBILE_NUMBER" IN varchar2
RETURN varchar2
  v_result varchar2(10);

    WHEN length(MOBILE_NUMBER) = 10 
    v_result := 'valid';
    RETURN v_result;
      v_result := 'invalid';
       RETURN v_result;
       end case;

How to specify a local file within html using the file: scheme?

the "file://" url protocol can only be used to locate files in the file system of the local machine. since this html code is interpreted by a browser, the "local machine" is the machine that is running the browser.

if you are getting file not found errors, i suspect it is because the file is not found. however, it could also be a security limitation of the browser. some browsers will not let you reference a filesystem file from a non-filesystem html page. you could try using the file path from the command line on the machine running the browser to confirm that this is a browser limitation and not a legitimate missing file.

How can I get query parameters from a URL in Vue.js?

According to the docs of route object, you have access to a $route object from your components, which exposes what you need. In this case

//from your component
console.log(this.$route.query.test) // outputs 'yay'

SQL Server returns error "Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'." in Windows application

FWIW, in our case a (PHP) website running on IIS was showing this message on attempting to connect to a database.

The resolution was to edit the Anonymous Authentication on that website to use the Application pool identity (and we set the application pool entry up to use a service account designed for that website).

How to read/write from/to file using Go?

Using io.Copy

package main

import (

func main () {
    // open files r and w
    r, err := os.Open("input.txt")
    if err != nil {
    defer r.Close()

    w, err := os.Create("output.txt")
    if err != nil {
    defer w.Close()

    // do the actual work
    n, err := io.Copy(w, r)
    if err != nil {
    log.Printf("Copied %v bytes\n", n)

If you don't feel like reinventing the wheel, the io.Copy and io.CopyN may serve you well. If you check the source of the io.Copy function, it is nothing but one of the Mostafa's solutions (the 'basic' one, actually) packaged in the Go library. They are using a significantly larger buffer than he is, though.

Javascript isnull

Why not try .test() ? ... Try its and best boolean (true or false):

$.urlParam = function(name){
    var results = new RegExp('[\\?&]' + name + '=([^&#]*)');
    return results.test(window.location.href);


How to connect to my http://localhost web server from Android Emulator

Another workaround is to get a free domain from and point it to your local ip address. Then, instead of using http://localhost/yourwebservice you can try

Defining constant string in Java?

public static final String YOUR_STRING_CONSTANT = "";

how to call url of any other website in php

As other's have mentioned, PHP's cURL functions will allow you to perform advanced HTTP requests. You can also use file_get_contents to access REST APIs:

$payload = file_get_contents('');

Starting with PHP 5 you can also create a stream context which will allow you to change headers or post data to the service.

Redirecting from cshtml page

This clearly is a bad case of controller logic in a view. It would be better to do this in a controller and return the desired view.

public ActionResult Results() 
    EnumerableRowCollection<DataRow> custs = ViewBag.Customers;
    bool anyRows = custs.Any();

    if(anyRows == false)
        return View("NoResults");
        return View("OtherView");

Modify NoResults.cshtml to a Partial.

And call this as a Partial view in the parent view


You might have to pass the Customer collection as a model to the Result action or in a ViewDataDictionary due to reasons explained here: Can't access ViewBag in a partial view in ASP.NET MVC3

The ChildActionOnly attribute will make sure you cannot go to this page by navigating and that this view must be rendered as a partial, thus by a parent view. cfr: Using ChildActionOnly in MVC

PostgreSQL - fetch the row which has the Max value for a column

I like the style of Mike Woodhouse's answer on the other page you mentioned. It's especially concise when the thing being maximised over is just a single column, in which case the subquery can just use MAX(some_col) and GROUP BY the other columns, but in your case you have a 2-part quantity to be maximised, you can still do so by using ORDER BY plus LIMIT 1 instead (as done by Quassnoi):

FROM lives outer
WHERE (usr_id, time_stamp, trans_id) IN (
    SELECT usr_id, time_stamp, trans_id
    FROM lives sq
    WHERE sq.usr_id = outer.usr_id
    ORDER BY trans_id, time_stamp
    LIMIT 1

I find using the row-constructor syntax WHERE (a, b, c) IN (subquery) nice because it cuts down on the amount of verbiage needed.

Emulate Samsung Galaxy Tab

You can't.

"The Samsung Emulator has the same functionality as the Generic Android Emulator, but varies with the size and appearance of the device."

The problem with Samsung is that they don't use a generic android image, they have custom apps and they react in custom ways and do weird things you wouldn't expect and when you're trying to fix bugs that's what you want. You cannot get that. You need access to a physical device to get the right ecosystem to hunt down the bugs and map out which intents work and how they work on that device. And sometimes there are errors that only occur on Samsung devices because some of the core rendering code is different as well. I've had errors where all Android devices except Samsung would work flawlessly but the scheme itself could not work on Samsung and had to be scrapped. The only thing Samsung allows is skinning and that won't properly note the changes in the rendering pipeline or how the samsung ecosystem deals with intents.

You can make the device look similar, that's worthless. I don't care what it looks like, I care whether this bug still affects that particular model or whether the tweak to the intents I made rectified the issue and I can't learn that from a pretty picture as the border to the same device.

Ifelse statement in R with multiple conditions

Based on suggestions from @jaimedash and @Old_Mortality I found a solution:

DF$Den <- ifelse(DF$Denial1 < 1 & !$Denial1) | DF$Denial2 < 1 &  
!$Denial2) | DF$Denial3 < 1 & !$Denial3), "0", "1")

Then to ensure a value of NA if all values of the conditional variables are NA:

DF$Den <- ifelse($Denial1) &$Denial2) &$Denial3), 
NA, DF$Den)

How to remove specific elements in a numpy array

If you don't know the index, you can't use logical_and

x = 10*np.random.randn(1,100)
low = 5
high = 27

How to filter object array based on attributes?

I prefer the Underscore framework. It suggests many useful operations with objects. Your task:

var newArray = homes.filter(
    price <= 1000 & 
    sqft >= 500 &
    num_of_beds >=2 & 
    num_of_baths >= 2.5);

can be overwriten like:

var newArray = _.filter (homes, function(home) {
    return home.price<=1000 && sqft>=500 && num_of_beds>=2 && num_of_baths>=2.5;

Hope it will be useful for you!

How to calculate the sum of the datatable column in

You Can use Linq by Name Grouping

  var allEntries = from r in dt.AsEnumerable()
                            select r["Amount"];

using name space using System.Linq;

You can find the sample total,subtotal,grand total in datatable using c# at Myblog

Can the Twitter Bootstrap Carousel plugin fade in and out on slide transition

Yes. Although I use the following code.

    opacity: 1;

        -moz-transition: opacity ease-in-out .7s;
        -o-transition: opacity ease-in-out .7s;
        -webkit-transition: opacity ease-in-out .7s;
        transition: opacity ease-in-out .7s;
        left: 0 !important;
        opacity: 0;
        width: 100%;
        display:block !important;

            opacity: 1;
            -moz-transition: opacity ease-in-out .7s;
            -o-transition: opacity ease-in-out .7s;
            -webkit-transition: opacity ease-in-out .7s;
            transition: opacity ease-in-out .7s;

Then change the class on the carousel from "carousel slide" to "carousel fade". This works in safari, chrome, firefox, and IE 10. It will correctly downgrade in IE 9, however, the nice face effect doesn't happen.

Edit: Since this answer has gotten so popular I've added the following which rewritten as pure CSS instead of the above which was LESS:

.carousel.fade {
  opacity: 1;
.carousel.fade .item {
  -moz-transition: opacity ease-in-out .7s;
  -o-transition: opacity ease-in-out .7s;
  -webkit-transition: opacity ease-in-out .7s;
  transition: opacity ease-in-out .7s;
  left: 0 !important;
  opacity: 0;
  width: 100%;
  display:block !important;
.carousel.fade .item:first-child {
.carousel.fade {
  opacity: 1;
  -moz-transition: opacity ease-in-out .7s;
  -o-transition: opacity ease-in-out .7s;
  -webkit-transition: opacity ease-in-out .7s;
  transition: opacity ease-in-out .7s;

ASP.NET MVC3 - textarea with @Html.EditorFor

Someone asked about adding attributes (specifically, 'rows' and 'cols'). If you're using Razor, you could just do this:

@Html.TextAreaFor(model => model.Text, new { cols = 35, @rows = 3 })

That works for me. The '@' is used to escape keywords so they are treated as variables/properties.

Maven dependency for Servlet 3.0 API?

Unfortunately, adding the javaee-(web)-api as a dependency doesn't give you the Javadoc or the Source to the Servlet Api to browse them from within the IDE. This is also the case for all other dependencies (JPA, EJB, ...) If you need the Servlet API sources/javadoc, you can add the following to your pom.xml (works at least for JBoss&Glassfish):


  <name>JBoss Public Repository Group</name>


<!-- Servlet 3.0 Api Specification -->

I completely removed the javaee-api from my dependencies and replaced it with the discrete parts (javax.ejb, javax.faces, ...) to get the sources and Javadocs for all parts of Java EE 6.


Here is the equivalent Glassfish dependency (although both dependencies should work, no matter what appserver you use).


Unique device identification

I have following idea how you can deal with such Access Device ID (ADID):


  • prepare web-page where trusted user e.g. Manager can login from device - that page should show button "Give access to this device"
  • when user press button, page send request to server to generate ADID
  • server gen ADID, store it on whitelist and return to page
  • then page store it in device localstorage
  • trusted user now logout.

Use device

  • Then other user e.g. Employee using same device go to and page send to server request for statistics including parameter ADID (previous stored in localstorage)
  • server checks if the ADID is on the whitelist, and if yes then return data

In this approach, as long user use same browser and don't make device reset, the device has access to data. If someone made device-reset then again trusted user need to login and gen ADID.

You can even create some ADID management system for trusted user where on generate ADID he can also input device serial-number and in future in case of device reset he can find this device and regenerate ADID for it (which not increase whitelist size) and he can also drop some ADID from whitelist for devices which he will not longer give access to server data.

In case when sytem use many domains/subdomains te manager after login should see many "Give access from domain to this device" buttons - each button will redirect device do proper domain, gent ADID and redirect back.


Simpler approach based on links:

  • Manager login to system using any device and generate ONE-TIME USE LINK (which works e.g. 24h).
  • Then manager send this link to employee (or someone else; e.g. by email) which put that link into device and server returns ADID to device which store it in Local Storage. After that link above stops working - so only the system and device know ADID
  • Then employee using this device can read data from because it has ADID which is on servers whitelist

What is the syntax of the enhanced for loop in Java?

  1. Enhanced For Loop (Java)
for (Object obj : list);
  1. Enhanced For Each in arraylist (Java)
ArrayList<Integer> list = new ArrayList<Integer>(); 
list.forEach((n) -> System.out.println(n)); 

Deleting specific rows from DataTable

I know this is, very, old question, and I have similar situation few days ago.

Problem was, in my table are approx. 10000 rows, so looping trough DataTable rows was very slow.

Finally, I found much faster solution, where I make copy of source DataTable with desired results, clear source DataTable and merge results from temporary DataTable into source one.

note : instead search for Joe in DataRow called name You have to search for all records whose not have name Joe (little opposite way of searching)

There is example ( :

'Copy all rows into tmpTable whose not contain Joe in name DataRow
Dim tmpTable As DataTable = drPerson.Select("name<>'Joe'").CopyToTable
'Clear source DataTable, in Your case dtPerson
'merge tmpTable into dtPerson (rows whose name not contain Joe)
tmpTable = Nothing

I hope so this shorter solution will help someone.

There is c# code (not sure is it correct because I used online converter :( ):

//Copy all rows into tmpTable whose not contain Joe in name DataRow
DataTable tmpTable = drPerson.Select("name<>'Joe'").CopyToTable;
//Clear source DataTable, in Your case dtPerson
//merge tmpTable into dtPerson (rows whose name not contain Joe)
tmpTable = null;

Of course, I used Try/Catch in case if there is no result (for example, if Your dtPerson don't contain name Joe it will throw exception), so You do nothing with Your table, it stays unchanged.

How to cast int to enum in C++?

Test castEnum = static_cast<Test>(a-1); will cast a to A. If you don't want to substruct 1, you can redefine the enum:

enum Test
    A:1, B

In this case Test castEnum = static_cast<Test>(a); could be used to cast a to A.

.htaccess: Invalid command 'RewriteEngine', perhaps misspelled or defined by a module not included in the server configuration

Steps to start Apache httpd.exe (I am using x64 VC11 example here)

Be sure that you have installed Visual C++ Redistributable for Visual Studio 2012 : VC11 vcredist_x64/86.exe

You may need to have Visual Studio 2012 Update 3 (VS2012.3) (vcredirect.exe)

Unzip and copy paste in


Unzip and copy paste them in


For further info on the modules see the Apache Lounge VC10 Win64 download page and/or the readme in the .zip's there.



un-comment (remove # sign) starting below this like copy pasted list in here

# Example:
# LoadModule foo_module modules/

LoadModule access_compat_module modules/
LoadModule actions_module modules/
LoadModule alias_module modules/
LoadModule allowmethods_module modules/
LoadModule asis_module modules/
LoadModule auth_basic_module modules/
LoadModule auth_digest_module modules/
LoadModule authn_anon_module modules/
LoadModule authn_core_module modules/
LoadModule authn_dbd_module modules/
LoadModule authn_dbm_module modules/
LoadModule authn_file_module modules/
LoadModule authn_socache_module modules/
LoadModule authnz_ldap_module modules/
LoadModule authz_core_module modules/
LoadModule authz_dbd_module modules/
LoadModule authz_dbm_module modules/
LoadModule authz_groupfile_module modules/
LoadModule authz_host_module modules/
LoadModule authz_owner_module modules/
LoadModule authz_user_module modules/
LoadModule autoindex_module modules/
LoadModule buffer_module modules/
LoadModule cache_module modules/
LoadModule cache_disk_module modules/
LoadModule cern_meta_module modules/
LoadModule cgi_module modules/
LoadModule charset_lite_module modules/
LoadModule data_module modules/
LoadModule dav_module modules/
LoadModule dav_fs_module modules/
LoadModule dav_lock_module modules/
LoadModule dbd_module modules/
LoadModule deflate_module modules/
LoadModule dir_module modules/
LoadModule dumpio_module modules/
LoadModule env_module modules/
LoadModule expires_module modules/
LoadModule ext_filter_module modules/
LoadModule file_cache_module modules/
LoadModule filter_module modules/
LoadModule headers_module modules/
LoadModule heartbeat_module modules/
LoadModule heartmonitor_module modules/
LoadModule ident_module modules/
LoadModule imagemap_module modules/
LoadModule include_module modules/
LoadModule info_module modules/
LoadModule isapi_module modules/
LoadModule lbmethod_bybusyness_module modules/
LoadModule lbmethod_byrequests_module modules/
LoadModule lbmethod_bytraffic_module modules/
LoadModule lbmethod_heartbeat_module modules/
LoadModule ldap_module modules/
LoadModule logio_module modules/
LoadModule log_config_module modules/
LoadModule log_debug_module modules/
LoadModule log_forensic_module modules/
LoadModule lua_module modules/
LoadModule mime_module modules/
LoadModule mime_magic_module modules/
LoadModule negotiation_module modules/
LoadModule proxy_module modules/
LoadModule proxy_ajp_module modules/
LoadModule proxy_balancer_module modules/
LoadModule proxy_connect_module modules/
LoadModule proxy_express_module modules/
LoadModule proxy_fcgi_module modules/
LoadModule proxy_ftp_module modules/
LoadModule proxy_html_module modules/
LoadModule proxy_http_module modules/
LoadModule proxy_scgi_module modules/
LoadModule ratelimit_module modules/
LoadModule reflector_module modules/
LoadModule remoteip_module modules/
LoadModule request_module modules/
LoadModule reqtimeout_module modules/
LoadModule rewrite_module modules/
LoadModule sed_module modules/
LoadModule session_module modules/
LoadModule session_cookie_module modules/
LoadModule session_crypto_module modules/
LoadModule session_dbd_module modules/
LoadModule setenvif_module modules/
LoadModule slotmem_plain_module modules/
LoadModule slotmem_shm_module modules/
LoadModule socache_dbm_module modules/
LoadModule socache_memcache_module modules/
LoadModule socache_shmcb_module modules/
LoadModule speling_module modules/
LoadModule ssl_module modules/
LoadModule status_module modules/
LoadModule substitute_module modules/
LoadModule unique_id_module modules/
LoadModule userdir_module modules/
LoadModule usertrack_module modules/
LoadModule version_module modules/
LoadModule vhost_alias_module modules/
LoadModule watchdog_module modules/
LoadModule xml2enc_module modules/

Then find


and double click on it.

Then in Command Prompt (CMD.exe) type


and press enter. It shows any error remaining.

Build with the latest Update 3 Visual Studio® 2012 aka VC11. VC11 has improvements, fixes and optimizations over VC10 in areas like Performance, MemoryManagement and Stability. For example code quality tuning and improvements done across different code generation areas for "speed". And makes more use of modern processors and win7, win8, 2008 and Server 2012 internal features.

The VC11 binaries loads VC11, VC10 and VC9 modules, and does not run on XP and 2003. Minimum system required: Windows 7 SP1, Windows 8 / 8.1, Windows Vista SP2, Windows Server 2008 R2 SP1, Windows Server 2012 / R2

After you have downloaded and before you attempt to install it, you should make sure that it is intact and has not been tampered with. Use the PGP Signature and/or the SHA Checksums to verify the integrity.

Thank you

Is it possible to make input fields read-only through CSS?

Why not hide the input element and replace it with a label element with the same content?

I puzzled over how the React TODOMVC app accomplished this same thing and this is the strategy they came up with.

To see it in action, check out the app below, and watch the CSS properties of the TODO items when you double click them and then click away.

When you render the page you can have either an editable input, or a non-editable label with display:none; depending on your media query.

How to give a time delay of less than one second in excel vba?

I found this on another site not sure if it works or not.

Application.Wait Now + 1/(24*60*60.0*2)

the numerical value 1 = 1 day

1/24 is one hour

1/(24*60) is one minute

so 1/(24*60*60*2) is 1/2 second

You need to use a decimal point somewhere to force a floating point number


Not sure if this will work worth a shot for milliseconds

Application.Wait (Now + 0.000001) 

importing external ".txt" file in python

The "import" keyword is for attaching python definitions that are created external to the current python program. So in your case, where you just want to read a file with some text in it, use:

text = open("words.txt", "rb").read()

How to free memory in Java?


Runs the garbage collector.

Calling the gc method suggests that the Java Virtual Machine expend effort toward recycling unused objects in order to make the memory they currently occupy available for quick reuse. When control returns from the method call, the Java Virtual Machine has made a best effort to reclaim space from all discarded objects.

Not recommended.

Edit: I wrote the original response in 2009. It's now 2015.

Garbage collectors have gotten steadily better in the ~20 years Java's been around. At this point, if you're manually calling the garbage collector, you may want to consider other approaches:

  • If you're forcing GC on a limited number of machines, it may be worth having a load balancer point away from the current machine, waiting for it to finish serving to connected clients, timeout after some period for hanging connections, and then just hard-restart the JVM. This is a terrible solution, but if you're looking at System.gc(), forced-restarts may be a possible stopgap.
  • Consider using a different garbage collector. For example, the (new in the last six years) G1 collector is a low-pause model; it uses more CPU overall, but does it's best to never force a hard-stop on execution. Since server CPUs now almost all have multiple cores, this is A Really Good Tradeoff to have available.
  • Look at your flags tuning memory use. Especially in newer versions of Java, if you don't have that many long-term running objects, consider bumping up the size of newgen in the heap. newgen (young) is where new objects are allocated. For a webserver, everything created for a request is put here, and if this space is too small, Java will spend extra time upgrading the objects to longer-lived memory, where they're more expensive to kill. (If newgen is slightly too small, you're going to pay for it.) For example, in G1:
    • XX:G1NewSizePercent (defaults to 5; probably doesn't matter.)
    • XX:G1MaxNewSizePercent (defaults to 60; probably raise this.)
  • Consider telling the garbage collector you're not okay with a longer pause. This will cause more-frequent GC runs, to allow the system to keep the rest of it's constraints. In G1:
    • XX:MaxGCPauseMillis (defaults to 200.)

diff current working copy of a file with another branch's committed copy

To see local changes compare to your current branch

git diff .

To see local changed compare to any other existing branch

git diff <branch-name> .

To see changes of a particular file

git diff <branch-name> -- <file-path>

Make sure you run git fetch at the beginning.

Java GUI frameworks. What to choose? Swing, SWT, AWT, SwingX, JGoodies, JavaFX, Apache Pivot?

I've been quite happy with Swing for the desktop applications I've been involved in. However, I do share your view on Swing not offering advanced components. What I've done in these cases is to go for JIDE. It's not free, but not that pricey either and it gives you a whole lot more tools under your belt. Specifically, they do offer a filterable TreeTable.

super() fails with error: TypeError "argument 1 must be type, not classobj" when parent does not inherit from object

Also, if you can't change class B, you can fix the error by using multiple inheritance.

class B:
    def meth(self, arg):
        print arg

class C(B, object):
    def meth(self, arg):
        super(C, self).meth(arg)

print C().meth(1)

Android setOnClickListener method - How does it work?

its an implementation of anonymouse class object creation to give ease of writing less code and to save time

"Please try running this command again as Root/Administrator" error when trying to install LESS

I kept having this problem because windows was setting my node_modules folder to Readonly. Make sure you uncheck this.

enter image description here

How does Python return multiple values from a function?

Python functions always return a unique value. The comma operator is the constructor of tuples so self.first_name, self.last_name evaluates to a tuple and that tuple is the actual value the function is returning.

Yarn install command error No such file or directory: 'install'

For Ubuntu 18.04.4 LTS I just followed the official instructions:

curl -sS | sudo apt-key add -
echo "deb stable main" | sudo tee /etc/apt/sources.list.d/yarn.list

sudo apt update && sudo apt install yarn

No need to do:

sudo apt remove cmdtest

That is only necessary on Ubuntu 17.04.* I think.

I hope it helps!

How can I echo a newline in a batch file?

This worked for me, no delayed expansion necessary:

@echo off
echo ^<html^> 
echo ^<body^>
echo Hello
echo ^</body^>
echo ^</html^>

It writes output like this:

Press any key to continue . . .

Java 32-bit vs 64-bit compatibility

Add a paramter as below in you in configuration while creating the exe

I hope it helps.



How do I restart a service on a remote machine in Windows?

Well, if you have Visual Studio (I know it's in 2005, not sure about earlier versions though), you can add the remote machine to your "Server Explorer" tag. At that point, you'll have access to the SERVICES that are running, or can be ran, from that machine (as well as event logs, and queues, and a couple other interesting things).

Need table of key codes for android and presenter

Complete list of key codes

Some of the other lists here are incomplete. The complete list can be found in the KeyEvent source code or documentation. The source code is ordered by integer value so I will use that here.

(Repetitive text removed to save space, all key codes are public static final int.)

/** Unknown key code. */
/** Soft Left key.
 * Usually situated below the display on phones and used as a multi-function
 * feature key for selecting a software defined function shown on the bottom left
 * of the display. */
/** Soft Right key.
 * Usually situated below the display on phones and used as a multi-function
 * feature key for selecting a software defined function shown on the bottom right
 * of the display. */
/** Home key.
 * This key is handled by the framework and is never delivered to applications. */
/** Back key. */
/** Call key. */
/** End Call key. */
/** '0' key. */
KEYCODE_0 = 7;
/** '1' key. */
KEYCODE_1 = 8;
/** '2' key. */
KEYCODE_2 = 9;
/** '3' key. */
KEYCODE_3 = 10;
/** '4' key. */
KEYCODE_4 = 11;
/** '5' key. */
KEYCODE_5 = 12;
/** '6' key. */
KEYCODE_6 = 13;
/** '7' key. */
KEYCODE_7 = 14;
/** '8' key. */
KEYCODE_8 = 15;
/** '9' key. */
KEYCODE_9 = 16;
/** '*' key. */
/** '#' key. */
/** Directional Pad Up key.
 * May also be synthesized from trackball motions. */
/** Directional Pad Down key.
 * May also be synthesized from trackball motions. */
/** Directional Pad Left key.
 * May also be synthesized from trackball motions. */
/** Directional Pad Right key.
 * May also be synthesized from trackball motions. */
/** Directional Pad Center key.
 * May also be synthesized from trackball motions. */
/** Volume Up key.
 * Adjusts the speaker volume up. */
/** Volume Down key.
 * Adjusts the speaker volume down. */
/** Power key. */
/** Camera key.
 * Used to launch a camera application or take pictures. */
/** Clear key. */
/** 'A' key. */
/** 'B' key. */
/** 'C' key. */
/** 'D' key. */
/** 'E' key. */
/** 'F' key. */
/** 'G' key. */
/** 'H' key. */
/** 'I' key. */
/** 'J' key. */
/** 'K' key. */
/** 'L' key. */
/** 'M' key. */
/** 'N' key. */
/** 'O' key. */
/** 'P' key. */
/** 'Q' key. */
/** 'R' key. */
/** 'S' key. */
/** 'T' key. */
/** 'U' key. */
/** 'V' key. */
/** 'W' key. */
/** 'X' key. */
/** 'Y' key. */
/** 'Z' key. */
/** ',' key. */
/** '.' key. */
/** Left Alt modifier key. */
/** Right Alt modifier key. */
/** Left Shift modifier key. */
/** Right Shift modifier key. */
/** Tab key. */
/** Space key. */
/** Symbol modifier key.
 * Used to enter alternate symbols. */
/** Explorer special function key.
 * Used to launch a browser application. */
/** Envelope special function key.
 * Used to launch a mail application. */
/** Enter key. */
/** Backspace key.
 * Deletes characters before the insertion point, unlike {@link #KEYCODE_FORWARD_DEL}. */
/** '`' (backtick) key. */
/** '-'. */
/** '=' key. */
/** '[' key. */
/** ']' key. */
/** '\' key. */
/** ';' key. */
/** ''' (apostrophe) key. */
/** '/' key. */
/** '@' key. */
/** Number modifier key.
 * Used to enter numeric symbols.
 * This key is not Num Lock; it is more like {@link #KEYCODE_ALT_LEFT} and is
 * interpreted as an ALT key by {@link android.text.method.MetaKeyKeyListener}. */
/** Headset Hook key.
 * Used to hang up calls and stop media. */
/** Camera Focus key.
 * Used to focus the camera. */
KEYCODE_FOCUS = 80; // *Camera* focus
/** '+' key. */
/** Menu key. */
/** Notification key. */
/** Search key. */
/** Play/Pause media key. */
/** Stop media key. */
/** Play Next media key. */
/** Play Previous media key. */
/** Rewind media key. */
/** Fast Forward media key. */
/** Mute key.
 * Mutes the microphone, unlike {@link #KEYCODE_VOLUME_MUTE}. */
/** Page Up key. */
/** Page Down key. */
/** Picture Symbols modifier key.
 * Used to switch symbol sets (Emoji, Kao-moji). */
KEYCODE_PICTSYMBOLS = 94; // switch symbol-sets (Emoji,Kao-moji)
/** Switch Charset modifier key.
 * Used to switch character sets (Kanji, Katakana). */
KEYCODE_SWITCH_CHARSET = 95; // switch char-sets (Kanji,Katakana)
/** A Button key.
 * On a game controller, the A button should be either the button labeled A
 * or the first button on the bottom row of controller buttons. */
/** B Button key.
 * On a game controller, the B button should be either the button labeled B
 * or the second button on the bottom row of controller buttons. */
/** C Button key.
 * On a game controller, the C button should be either the button labeled C
 * or the third button on the bottom row of controller buttons. */
/** X Button key.
 * On a game controller, the X button should be either the button labeled X
 * or the first button on the upper row of controller buttons. */
/** Y Button key.
 * On a game controller, the Y button should be either the button labeled Y
 * or the second button on the upper row of controller buttons. */
/** Z Button key.
 * On a game controller, the Z button should be either the button labeled Z
 * or the third button on the upper row of controller buttons. */
/** L1 Button key.
 * On a game controller, the L1 button should be either the button labeled L1 (or L)
 * or the top left trigger button. */
/** R1 Button key.
 * On a game controller, the R1 button should be either the button labeled R1 (or R)
 * or the top right trigger button. */
/** L2 Button key.
 * On a game controller, the L2 button should be either the button labeled L2
 * or the bottom left trigger button. */
/** R2 Button key.
 * On a game controller, the R2 button should be either the button labeled R2
 * or the bottom right trigger button. */
/** Left Thumb Button key.
 * On a game controller, the left thumb button indicates that the left (or only)
 * joystick is pressed. */
/** Right Thumb Button key.
 * On a game controller, the right thumb button indicates that the right
 * joystick is pressed. */
/** Start Button key.
 * On a game controller, the button labeled Start. */
/** Select Button key.
 * On a game controller, the button labeled Select. */
/** Mode Button key.
 * On a game controller, the button labeled Mode. */
/** Escape key. */
/** Forward Delete key.
 * Deletes characters ahead of the insertion point, unlike {@link #KEYCODE_DEL}. */
/** Left Control modifier key. */
/** Right Control modifier key. */
/** Caps Lock key. */
/** Scroll Lock key. */
/** Left Meta modifier key. */
/** Right Meta modifier key. */
/** Function modifier key. */
/** System Request / Print Screen key. */
/** Break / Pause key. */
/** Home Movement key.
 * Used for scrolling or moving the cursor around to the start of a line
 * or to the top of a list. */
/** End Movement key.
 * Used for scrolling or moving the cursor around to the end of a line
 * or to the bottom of a list. */
/** Insert key.
 * Toggles insert / overwrite edit mode. */
/** Forward key.
 * Navigates forward in the history stack. Complement of {@link #KEYCODE_BACK}. */
/** Play media key. */
/** Pause media key. */
/** Close media key.
 * May be used to close a CD tray, for example. */
/** Eject media key.
 * May be used to eject a CD tray, for example. */
/** Record media key. */
/** F1 key. */
KEYCODE_F1 = 131;
/** F2 key. */
KEYCODE_F2 = 132;
/** F3 key. */
KEYCODE_F3 = 133;
/** F4 key. */
KEYCODE_F4 = 134;
/** F5 key. */
KEYCODE_F5 = 135;
/** F6 key. */
KEYCODE_F6 = 136;
/** F7 key. */
KEYCODE_F7 = 137;
/** F8 key. */
KEYCODE_F8 = 138;
/** F9 key. */
KEYCODE_F9 = 139;
/** F10 key. */
KEYCODE_F10 = 140;
/** F11 key. */
KEYCODE_F11 = 141;
/** F12 key. */
KEYCODE_F12 = 142;
/** Num Lock key.
 * This is the Num Lock key; it is different from {@link #KEYCODE_NUM}.
 * This key alters the behavior of other keys on the numeric keypad. */
/** Numeric keypad '0' key. */
/** Numeric keypad '1' key. */
/** Numeric keypad '2' key. */
/** Numeric keypad '3' key. */
/** Numeric keypad '4' key. */
/** Numeric keypad '5' key. */
/** Numeric keypad '6' key. */
/** Numeric keypad '7' key. */
/** Numeric keypad '8' key. */
/** Numeric keypad '9' key. */
/** Numeric keypad '/' key (for division). */
/** Numeric keypad '*' key (for multiplication). */
/** Numeric keypad '-' key (for subtraction). */
/** Numeric keypad '+' key (for addition). */
/** Numeric keypad '.' key (for decimals or digit grouping). */
/** Numeric keypad ',' key (for decimals or digit grouping). */
/** Numeric keypad Enter key. */
/** Numeric keypad '=' key. */
/** Numeric keypad '(' key. */
/** Numeric keypad ')' key. */
/** Volume Mute key.
 * Mutes the speaker, unlike {@link #KEYCODE_MUTE}.
 * This key should normally be implemented as a toggle such that the first press
 * mutes the speaker and the second press restores the original volume. */
/** Info key.
 * Common on TV remotes to show additional information related to what is
 * currently being viewed. */
/** Channel up key.
 * On TV remotes, increments the television channel. */
/** Channel down key.
 * On TV remotes, decrements the television channel. */
/** Zoom in key. */
/** Zoom out key. */
/** TV key.
 * On TV remotes, switches to viewing live TV. */
/** Window key.
 * On TV remotes, toggles picture-in-picture mode or other windowing functions. */
/** Guide key.
 * On TV remotes, shows a programming guide. */
/** DVR key.
 * On some TV remotes, switches to a DVR mode for recorded shows. */
/** Bookmark key.
 * On some TV remotes, bookmarks content or web pages. */
/** Toggle captions key.
 * Switches the mode for closed-captioning text, for example during television shows. */
/** Settings key.
 * Starts the system settings activity. */
/** TV power key.
 * On TV remotes, toggles the power on a television screen. */
/** TV input key.
 * On TV remotes, switches the input on a television screen. */
/** Set-top-box power key.
 * On TV remotes, toggles the power on an external Set-top-box. */
/** Set-top-box input key.
 * On TV remotes, switches the input mode on an external Set-top-box. */
/** A/V Receiver power key.
 * On TV remotes, toggles the power on an external A/V Receiver. */
/** A/V Receiver input key.
 * On TV remotes, switches the input mode on an external A/V Receiver. */
/** Red "programmable" key.
 * On TV remotes, acts as a contextual/programmable key. */
/** Green "programmable" key.
 * On TV remotes, actsas a contextual/programmable key. */
/** Yellow "programmable" key.
 * On TV remotes, acts as a contextual/programmable key. */
/** Blue "programmable" key.
 * On TV remotes, acts as a contextual/programmable key. */
/** App switch key.
 * Should bring up the application switcher dialog. */
/** Generic Game Pad Button #1.*/
/** Generic Game Pad Button #2.*/
/** Generic Game Pad Button #3.*/
/** Generic Game Pad Button #4.*/
/** Generic Game Pad Button #5.*/
/** Generic Game Pad Button #6.*/
/** Generic Game Pad Button #7.*/
/** Generic Game Pad Button #8.*/
/** Generic Game Pad Button #9.*/
/** Generic Game Pad Button #10.*/
/** Generic Game Pad Button #11.*/
/** Generic Game Pad Button #12.*/
/** Generic Game Pad Button #13.*/
/** Generic Game Pad Button #14.*/
/** Generic Game Pad Button #15.*/
/** Generic Game Pad Button #16.*/
/** Language Switch key.
 * Toggles the current input language such as switching between English and Japanese on
 * a QWERTY keyboard. On some devices, the same function may be performed by
 * pressing Shift+Spacebar. */
/** Manner Mode key.
 * Toggles silent or vibrate mode on and off to make the device behave more politely
 * in certain settings such as on a crowded train. On some devices, the key may only
 * operate when long-pressed. */
/** 3D Mode key.
 * Toggles the display between 2D and 3D mode. */
/** Contacts special function key.
 * Used to launch an address book application. */
/** Calendar special function key.
 * Used to launch a calendar application. */
/** Music special function key.
 * Used to launch a music player application. */
/** Calculator special function key.
 * Used to launch a calculator application. */
/** Japanese full-width / half-width key. */
/** Japanese alphanumeric key. */
/** Japanese non-conversion key. */
/** Japanese conversion key. */
/** Japanese katakana / hiragana key. */
/** Japanese Yen key. */
/** Japanese Ro key. */
/** Japanese kana key. */
/** Assist key.
 * Launches the global assist activity. Not delivered to applications. */
/** Brightness Down key.
 * Adjusts the screen brightness down. */
/** Brightness Up key.
 * Adjusts the screen brightness up. */
/** Audio Track key.
 * Switches the audio tracks. */
/** Sleep key.
 * Puts the device to sleep. Behaves somewhat like {@link #KEYCODE_POWER} but it
 * has no effect if the device is already asleep. */
/** Wakeup key.
 * Wakes up the device. Behaves somewhat like {@link #KEYCODE_POWER} but it
 * has no effect if the device is already awake. */
/** Pairing key.
 * Initiates peripheral pairing mode. Useful for pairing remote control
 * devices or game controllers, especially if no other input mode is
 * available. */
/** Media Top Menu key.
 * Goes to the top of media menu. */
/** '11' key. */
KEYCODE_11 = 227;
/** '12' key. */
KEYCODE_12 = 228;
/** Last Channel key.
 * Goes to the last viewed channel. */
/** TV data service key.
 * Displays data services like weather, sports. */
/** Voice Assist key.
 * Launches the global voice assist activity. Not delivered to applications. */
/** Radio key.
 * Toggles TV service / Radio service. */
/** Teletext key.
 * Displays Teletext service. */
/** Number entry key.
 * Initiates to enter multi-digit channel nubmber when each digit key is assigned
 * for selecting separate channel. Corresponds to Number Entry Mode (0x1D) of CEC
 * User Control Code. */
/** Analog Terrestrial key.
 * Switches to analog terrestrial broadcast service. */
/** Digital Terrestrial key.
 * Switches to digital terrestrial broadcast service. */
/** Satellite key.
 * Switches to digital satellite broadcast service. */
/** BS key.
 * Switches to BS digital satellite broadcasting service available in Japan. */
/** CS key.
 * Switches to CS digital satellite broadcasting service available in Japan. */
/** BS/CS key.
 * Toggles between BS and CS digital satellite services. */
/** Toggle Network key.
 * Toggles selecting broacast services. */
/** Antenna/Cable key.
 * Toggles broadcast input source between antenna and cable. */
/** HDMI #1 key.
 * Switches to HDMI input #1. */
/** HDMI #2 key.
 * Switches to HDMI input #2. */
/** HDMI #3 key.
 * Switches to HDMI input #3. */
/** HDMI #4 key.
 * Switches to HDMI input #4. */
/** Composite #1 key.
 * Switches to composite video input #1. */
/** Composite #2 key.
 * Switches to composite video input #2. */
/** Component #1 key.
 * Switches to component video input #1. */
/** Component #2 key.
 * Switches to component video input #2. */
/** VGA #1 key.
 * Switches to VGA (analog RGB) input #1. */
/** Audio description key.
 * Toggles audio description off / on. */
/** Audio description mixing volume up key.
 * Louden audio description volume as compared with normal audio volume. */
/** Audio description mixing volume down key.
 * Lessen audio description volume as compared with normal audio volume. */
/** Zoom mode key.
 * Changes Zoom mode (Normal, Full, Zoom, Wide-zoom, etc.) */
/** Contents menu key.
 * Goes to the title list. Corresponds to Contents Menu (0x0B) of CEC User Control
 * Code */
/** Media context menu key.
 * Goes to the context menu of media contents. Corresponds to Media Context-sensitive
 * Menu (0x11) of CEC User Control Code. */
/** Timer programming key.
 * Goes to the timer recording menu. Corresponds to Timer Programming (0x54) of
 * CEC User Control Code. */
/** Help key. */
/** Navigate to previous key.
 * Goes backward by one item in an ordered collection of items. */
/** Navigate to next key.
 * Advances to the next item in an ordered collection of items. */
/** Navigate in key.
 * Activates the item that currently has focus or expands to the next level of a navigation
 * hierarchy. */
/** Navigate out key.
 * Backs out one level of a navigation hierarchy or collapses the item that currently has
 * focus. */
/** Primary stem key for Wear
 * Main power/reset button on watch. */
/** Generic stem key 1 for Wear */
/** Generic stem key 2 for Wear */
/** Generic stem key 3 for Wear */
/** Directional Pad Up-Left */
/** Directional Pad Down-Left */
/** Directional Pad Up-Right */
/** Directional Pad Down-Right */
/** Skip forward media key. */
/** Skip backward media key. */
/** Step forward media key.
 * Steps media forward, one frame at a time. */
/** Step backward media key.
 * Steps media backward, one frame at a time. */
/** put device to sleep unless a wakelock is held. */
/** Cut key. */
/** Copy key. */
/** Paste key. */
/** Consumed by the system for navigation up */
/** Consumed by the system for navigation down */
/** Consumed by the system for navigation left*/
/** Consumed by the system for navigation right */


  • Currently the last key code is KEYCODE_SYSTEM_NAVIGATION_RIGHT, which is 283 (but check the source code to make sure this is still true). So you could loop through them like this:

    for (int keyCode = 0; keyCode <= 283; keyCode++) {
  • Most input to EditText (or a custom view that accepts keyboard input) from an Input Method Editor (IME) is done using an Input Connection, so many key codes are not sent at all in this case. See this answer.

Most efficient way to increment a Map value in Java

The Functional Java library's TreeMap datastructure has an update method in the latest trunk head:

public TreeMap<K, V> update(final K k, final F<V, V> f)

Example usage:

import static;
import static fj.function.Integers.add;
import static fj.pre.Ord.stringOrd;

public class TreeMap_Update
  {public static void main(String[] a)
    {TreeMap<String, Integer> map = empty(stringOrd);
     map = map.set("foo", 1);
     map = map.update("foo", add.f(1));

This program prints "2".

What are some examples of commonly used practices for naming git branches?

A successful Git branching model by Vincent Driessen has good suggestions. A picture is below. If this branching model appeals to you consider the flow extension to git. Others have commented about flow

Driessen's model includes

  • A master branch, used only for release. Typical name master.

  • A "develop" branch off of that branch. That's the one used for most main-line work. Commonly named develop.

  • Multiple feature branches off of the develop branch. Name based on the name of the feature. These will be merged back into develop, not into the master or release branches.

  • Release branch to hold candidate releases, with only bug fixes and no new features. Typical name rc1.1.

Hotfixes are short-lived branches for changes that come from master and will go into master without development branch being involved.

enter image description here

Extracting just Month and Year separately from Pandas Datetime column

If you want new columns showing year and month separately you can do this:

df['year'] = pd.DatetimeIndex(df['ArrivalDate']).year
df['month'] = pd.DatetimeIndex(df['ArrivalDate']).month


df['year'] = df['ArrivalDate'].dt.year
df['month'] = df['ArrivalDate'].dt.month

Then you can combine them or work with them just as they are.

Gradle Build Android Project "Could not resolve all dependencies" error

As Peter says, they won't be in Maven Central

from the Android SDK Manager download the 'Android Support Repository' and a Maven repo of the support libraries will be downloaded to your Android SDK directory (see 'extras' folder)

to deploy the libraries to your local .m2 repository you can use maven-android-sdk-deployer

2017 edit:

you can now reference the Google online M2 repo

repositories {

Valid values for android:fontFamily and what they map to?

Where do these values come from? The documentation for android:fontFamily does not list this information in any place

These are indeed not listed in the documentation. But they are mentioned here under the section 'Font families'. The document lists every new public API for Android Jelly Bean 4.1.

In the styles.xml file in the application I'm working on somebody listed this as the font family, and I'm pretty sure it's wrong:

Yes, that's wrong. You don't reference the font file, you have to use the font name mentioned in the linked document above. In this case it should have been this:

<item name="android:fontFamily">sans-serif</item>

Like the linked answer already stated, 12 variants are possible:

Added in Android Jelly Bean (4.1) - API 16 :

Regular (default):

<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">normal</item> 


<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">italic</item>


<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">bold</item>


<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">bold|italic</item>


<item name="android:fontFamily">sans-serif-light</item>
<item name="android:textStyle">normal</item>


<item name="android:fontFamily">sans-serif-light</item>
<item name="android:textStyle">italic</item>

Thin :

<item name="android:fontFamily">sans-serif-thin</item>
<item name="android:textStyle">normal</item>

Thin-italic :

<item name="android:fontFamily">sans-serif-thin</item>
<item name="android:textStyle">italic</item>

Condensed regular:

<item name="android:fontFamily">sans-serif-condensed</item>
<item name="android:textStyle">normal</item>

Condensed italic:

<item name="android:fontFamily">sans-serif-condensed</item>
<item name="android:textStyle">italic</item>

Condensed bold:

<item name="android:fontFamily">sans-serif-condensed</item>
<item name="android:textStyle">bold</item>

Condensed bold-italic:

<item name="android:fontFamily">sans-serif-condensed</item>
<item name="android:textStyle">bold|italic</item>

Added in Android Lollipop (v5.0) - API 21 :


<item name="android:fontFamily">sans-serif-medium</item>
<item name="android:textStyle">normal</item>


<item name="android:fontFamily">sans-serif-medium</item>
<item name="android:textStyle">italic</item>


<item name="android:fontFamily">sans-serif-black</item>
<item name="android:textStyle">italic</item>

For quick reference, this is how they all look like:

How to pass multiple values to single parameter in stored procedure

This can not be done easily. There's no way to make an NVARCHAR parameter take "more than one value". What I've done before is - as you do already - make the parameter value like a list with comma-separated values. Then, split this string up into its parts in the stored procedure.

Splitting up can be done using string functions. Add every part to a temporary table. Pseudo-code for this could be:

WHILE LEN(@PortfolioID) > 0
    IF NOT <@PortfolioID contains Comma>
        INSERT INTO #TempTable VALUES CAST(@PortfolioID as INT)
        SET @PortfolioID = ''
         INSERT INTO #Temptable VALUES CAST(<Part until next comma> AS INT)
         SET @PortfolioID = <Everything after the next comma>

Then, change your condition to

WHERE PortfolioId IN (SELECT ID FROM #TempTable)

You may be interested in the documentation for multi value parameters in SSRS, which states:

You can define a multivalue parameter for any report parameter that you create. However, if you want to pass multiple parameter values back to a data source by using the query, the following requirements must be satisfied:

The data source must be SQL Server, Oracle, Analysis Services, SAP BI NetWeaver, or Hyperion Essbase.

The data source cannot be a stored procedure. Reporting Services does not support passing a multivalue parameter array to a stored procedure.

The query must use an IN clause to specify the parameter.

This I found here.