Programs & Examples On #Preon

Preon aims to provide a framework for dealing with binary encoded data; or more specifically, it aims to deal with situations in which bytes are considered to be overkill.

iOS - Ensure execution on main thread

This will do it:

[[NSOperationQueue mainQueue] addOperationWithBlock:^ {

   //Your code goes in here
   NSLog(@"Main Thread Code");


Hope this helps!

Extract directory path and filename

Using bash "here string":

$ fspec="/exp/home1/abc.txt" 
$ tr  "/"  "\n"  <<< $fspec | tail -1
$ filename=$(tr  "/"  "\n"  <<< $fspec | tail -1)
$ echo $filename

The benefit of the "here string" is that it avoids the need/overhead of running an echo command. In other words, the "here string" is internal to the shell. That is:

$ tr <<< $fspec

as opposed to:

$ echo $fspec | tr

React Native fetch() Network Request Failed

This worked for me, android uses a special type of IP address then port number

import { Platform } from 'react-native';

export const baseUrl = Platform.OS === 'android' ?

Can you put two conditions in an xslt test attribute?

Maybe this is a no-brainer for the xslt-professional, but for me at beginner/intermediate level, this got me puzzled. I wanted to do exactly the same thing, but I had to test a responsetime value from an xml instead of a plain number. Following this thread, I tried this:

<xsl:when test="responsetime/@value &gt;= 5000 and responsetime/@value &lt;= 8999"> 

which generated an error. This works:

<xsl:when test="number(responsetime/@value) &gt;= 5000 and number(responsetime/@value) &lt;= 8999">

Don't really understand why it doesn't work without number(), though. Could it be that without number() the value is treated as a string and you can't compare numbers with a string?

Anyway, hope this saves someone a lot of searching...

how to parse xml to java object?

JAXB is an ideal solution. But you do not necessarily need xsd and xjc for that. More often than not you don't have an xsd but you know what your xml is. Simply analyze your xml, e.g.,

<customer id="100">

Create necessary model class(es):

public class Customer {

    String name;
    int age;
    int id;

    public String getName() {
        return name;

    public void setName(String name) { = name;

    public int getAge() {
        return age;

    public void setAge(int age) {
        this.age = age;

    public int getId() {
        return id;

    public void setId(int id) { = id;


Try to unmarshal:

JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Customer customer = (Customer) jaxbUnmarshaller.unmarshal(new File("C:\\file.xml"));

Check results, fix bugs!

Ignoring NaNs with str.contains


java.lang.UnsatisfiedLinkError no *****.dll in java.library.path

I had the same problem and the error was due to a rename of the dll. It could happen that the library name is also written somewhere inside the dll. When I put back its original name I was able to load using System.loadLibrary

Oracle query to fetch column names

On Several occasions, we would need comma separated list of all the columns from a table in a schema. In such cases we can use this generic function which fetches the comma separated list as a string.

    p_schema_name IN VARCHAR2,
    p_table_name  IN VARCHAR2)
  v_string VARCHAR2(4000);
  INTO v_string
  WHERE OWNER    = p_schema_name
  AND table_name = p_table_name;
  RETURN v_string;

So, simply calling the function from the query yields a row with all the columns.

select cols('HR','EMPLOYEES') FROM DUAL;


Note: LISTAGG will fail if the combined length of all columns exceed 4000 characters which is rare. For most cases , this will work.

simple custom event

This is an easy way to create custom events and raise them. You create a delegate and an event in the class you are throwing from. Then subscribe to the event from another part of your code. You have already got a custom event argument class so you can build on that to make other event argument classes. N.B: I have not compiled this code.

public partial class Form1 : Form
    private TestClass _testClass;
    public Form1()
        _testClass = new TestClass();
        _testClass.OnUpdateStatus += new TestClass.StatusUpdateHandler(UpdateStatus);

    private void UpdateStatus(object sender, ProgressEventArgs e)

    private void SetStatus(string status)
        label1.Text = status;

    private void button1_Click_1(object sender, EventArgs e)


public class TestClass
    public delegate void StatusUpdateHandler(object sender, ProgressEventArgs e);
    public event StatusUpdateHandler OnUpdateStatus;

    public static void Func()
        //time consuming code
        // time consuming code

    private void UpdateStatus(string status)
        // Make sure someone is listening to event
        if (OnUpdateStatus == null) return;

        ProgressEventArgs args = new ProgressEventArgs(status);
        OnUpdateStatus(this, args);

public class ProgressEventArgs : EventArgs
    public string Status { get; private set; }

    public ProgressEventArgs(string status)
        Status = status;

Network usage top/htop on Linux

jnettop is another candidate.

edit: it only shows the streams, not the owner processes.

jQuery attr() change img src

  1. Function imageMorph will create a new img element therefore the id is removed. Changed to

    $("#wrapper > img")

  2. You should use live() function for click event if you want you rocket lanch again.

Updated demo:

ASP.NET MVC - passing parameters to the controller

public ActionResult ViewNextItem(int? id) makes the id integer a nullable type, no need for string<->int conversions.

How to get .pem file from .key and .crt files?

this is the best option to create .pem file

openssl pkcs12 -in MyPushApp.p12 -out MyPushApp.pem -nodes -clcerts

Algorithm to convert RGB to HSV and HSV to RGB in range 0-255 for both

I created a possibly faster implementation by using 0-1 range for RGBS and V and 0-6 range for Hue (avoiding the division), and grouping the cases into two categories:

#include <math.h>
#include <float.h>

void fromRGBtoHSV(float rgb[], float hsv[])
//    for(int i=0; i<3; ++i)
//        rgb[i] = max(0.0f, min(1.0f, rgb[i]));

     hsv[0] = 0.0f;
     hsv[2] = max(rgb[0], max(rgb[1], rgb[2]));
     const float delta = hsv[2] - min(rgb[0], min(rgb[1], rgb[2]));

     if (delta < FLT_MIN)
         hsv[1] = 0.0f;
         hsv[1] = delta / hsv[2];
         if (rgb[0] >= hsv[2])
             hsv[0] = (rgb[1] - rgb[2]) / delta;
             if (hsv[0] < 0.0f)
                 hsv[0] += 6.0f;
         else if (rgb[1] >= hsv[2])
             hsv[0] = 2.0f + (rgb[2] - rgb[0]) / delta;
             hsv[0] = 4.0f + (rgb[0] - rgb[1]) / delta;

void fromHSVtoRGB(const float hsv[], float rgb[])
    if(hsv[1] < FLT_MIN)
        rgb[0] = rgb[1] = rgb[2] = hsv[2];
        const float h = hsv[0];
        const int i = (int)h;
        const float f = h - i;
        const float p = hsv[2] * (1.0f - hsv[1]);

        if (i & 1) {
            const float q = hsv[2] * (1.0f - (hsv[1] * f));
            switch(i) {
            case 1:
                rgb[0] = q;
                rgb[1] = hsv[2];
                rgb[2] = p;
            case 3:
                rgb[0] = p;
                rgb[1] = q;
                rgb[2] = hsv[2];
                rgb[0] = hsv[2];
                rgb[1] = p;
                rgb[2] = q;
            const float t = hsv[2] * (1.0f - (hsv[1] * (1.0f - f)));
            switch(i) {
            case 0:
                rgb[0] = hsv[2];
                rgb[1] = t;
                rgb[2] = p;
            case 2:
                rgb[0] = p;
                rgb[1] = hsv[2];
                rgb[2] = t;
                rgb[0] = t;
                rgb[1] = p;
                rgb[2] = hsv[2];

For 0-255 range just * 255.0f + 0.5f and assign it to an unsigned char (or divide by 255.0 to get the opposite).

document.getelementbyId will return null if element is not defined?

console.log(document.getElementById('xx') ) evaluates to null.

document.getElementById('xx') !=null evaluates to false

You should use document.getElementById('xx') !== null as it is a stronger equality check.

Getting Error:JRE_HOME variable is not defined correctly when trying to run startup.bat of Apache-Tomcat

Got the solution and it's working fine. Set the environment variables as:

  • CATALINA_HOME=C:\Program Files\Java\apache-tomcat-7.0.59\apache-tomcat-7.0.59 (path where your Apache Tomcat is)
  • JAVA_HOME=C:\Program Files\Java\jdk1.8.0_25; (path where your JDK is)
  • JRE_Home=C:\Program Files\Java\jre1.8.0_25; (path where your JRE is)

Cannot instantiate the type List<Product>

Interfaces can not be directly instantiated, you should instantiate classes that implements such Interfaces.

Try this:

NameValuePair[] params = new BasicNameValuePair[] {
        new BasicNameValuePair("param1", param1),
        new BasicNameValuePair("param2", param2),

How do you deploy Angular apps?

You are actually here touching two questions in one.

The first one is How to host your application?.
And as @toskv mentioned its really too broad question to be answered and depends on numerous different things.

The second one is How do you prepare the deployment version of the application?.
You have several options here:

  1. Deploy as it is. Just that - no minification, concatenation, name mangling, etc. Transpile all your ts project copy all your resulting js/css/... sources + dependencies to the hosting server and you are good to go.
  2. Deploy using special bundling tools, like webpack or systemjs builder.
    They come with all the possibilities that are lacking in #1.
    You can pack all your app code into just a couple of js/css/... files that you reference in your HTML. systemjs builder even allows you to get rid of the need to include systemjs as part of your deployment package.

  3. You can use ng deploy as of Angular 8 to deploy your app from your CLI. ng deploy will need to be used in conjunction with your platform of choice (such as @angular/fire). You can check the official docs to see what works best for you here

Yes you will most likely need to deploy systemjs and bunch of other external libraries as part of your package. And yes you will be able to bundle them into just couple of js files you reference from your HTML page.

You do not have to reference all your compiled js files from the page though - systemjs as a module loader will take care of that.

I know it sounds muddy - to help get you started with the #2 here are two really good sample applications:

SystemJS builder: angular2 seed

WebPack: angular2 webpack starter

What is the difference between Hibernate and Spring Data JPA

There are 3 different things we are using here :

  1. JPA : Java persistence api which provide specification for persisting, reading, managing data from your java object to relations in database.
  2. Hibernate: There are various provider which implement jpa. Hibernate is one of them. So we have other provider as well. But if using jpa with spring it allows you to switch to different providers in future.
  3. Spring Data JPA : This is another layer on top of jpa which spring provide to make your life easy.

So lets understand how spring data jpa and spring + hibernate works-

Spring Data JPA:

Let's say you are using spring + hibernate for your application. Now you need to have dao interface and implementation where you will be writing crud operation using SessionFactory of hibernate. Let say you are writing dao class for Employee class, tomorrow in your application you might need to write similiar crud operation for any other entity. So there is lot of boilerplate code we can see here.

Now Spring data jpa allow us to define dao interfaces by extending its repositories(crudrepository, jparepository) so it provide you dao implementation at runtime. You don't need to write dao implementation anymore.Thats how spring data jpa makes your life easy.

Way to go from recursion to iteration

Even using stack will not convert a recursive algorithm into iterative. Normal recursion is function based recursion and if we use stack then it becomes stack based recursion. But its still recursion.

For recursive algorithms, space complexity is O(N) and time complexity is O(N). For iterative algorithms, space complexity is O(1) and time complexity is O(N).

But if we use stack things in terms of complexity remains same. I think only tail recursion can be converted into iteration.

How do I discover memory usage of my application in Android?

Yes, you can get memory info programmatically and decide whether to do memory intensive work.

Get VM Heap Size by calling:


Get Allocated VM Memory by calling:

Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();

Get VM Heap Size Limit by calling:


Get Native Allocated Memory by calling:


I made an app to figure out the OutOfMemoryError behavior and monitor memory usage.

You can get the source code at


     Count(Distinct user_id) As countUsers
   , Count(site_id) As countVisits
   , site_id As site
 From cp_visits
 Where ts >= DATE_SUB(NOW(), INTERVAL 1 DAY)
 Group By site_id

How to reload/refresh an element(image) in jQuery

with one line with no worries about hardcoding the image src into the javascript (thanks to jeerose for the ideas:

$("#myimg").attr("src", $("#myimg").attr("src")+"?timestamp=" + new Date().getTime());

Using Google maps API v3 how do I get LatLng with a given address?

I don't think location.LatLng is working, however this works:

results[0], results[0].geometry.location.lng()

Found it while exploring Get Lat Lon source code.

Ellipsis for overflow text in dropdown boxes

CSS file

.selectDD {
 overflow: hidden;
 white-space: nowrap;
 text-overflow: ellipsis;     

JS file

$(document).ready(function () {

Android: upgrading DB version and adding new table

1. About onCreate() and onUpgrade()

onCreate(..) is called whenever the app is freshly installed. onUpgrade is called whenever the app is upgraded and launched and the database version is not the same.

2. Incrementing the db version

You need a constructor like:

MyOpenHelper(Context context) {
   super(context, "dbname", null, 2); // 2 is the database version

IMPORTANT: Incrementing the app version alone is not enough for onUpgrade to be called!

3. Don't forget your new users!

Don't forget to add


to your onCreate() method as well or newly installed apps will lack the table.

4. How to deal with multiple database changes over time

When you have successive app upgrades, several of which have database upgrades, you want to be sure to check oldVersion:

onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
   switch(oldVersion) {
   case 1:
       // we want both updates, so no break statement here...
   case 2:

This way when a user upgrades from version 1 to version 3, they get both updates. When a user upgrades from version 2 to 3, they just get the revision 3 update... After all, you can't count on 100% of your user base to upgrade each time you release an update. Sometimes they skip an update or 12 :)

5. Keeping your revision numbers under control while developing

And finally... calling

adb uninstall <yourpackagename>

totally uninstalls the app. When you install again, you are guaranteed to hit onCreate which keeps you from having to keep incrementing the database version into the stratosphere as you develop...

PyCharm import external library

Update (2018-01-06): This answer is obsolete. Modern versions of PyCharm provide Paths via Settings ? Project Interpreter ? ? ? Show All ? Show paths button.

PyCharm Professional Edition has the Paths tab in Python Interpreters settings, but Community Edition apparently doesn't have it.

As a workaround, you can create a symlink for your imported library under your project's root.

For example:

    third_party -> /some/other/directory/third_party

Why can't I find SQL Server Management Studio after installation?

It appears that SQL Server 2008 R2 can be downloaded with or without the management tools. I honestly have NO IDEA why someone would not want the management tools. But either way, the options are here:

and the one for 64 bit WITH the management tools (management studio) is here:

From the first link I presented, the 3rd and 4th include the management studio for 32 and 64 bit respectively.

Invalid use side-effecting operator Insert within a function

There is an exception (I'm using SQL 2014) when you are only using Insert/Update/Delete on Declared-Tables. These Insert/Update/Delete statements cannot contain an OUTPUT statement. The other restriction is that you are not allowed to do a MERGE, even into a Declared-Table. I broke up my Merge statements, that didn't work, into Insert/Update/Delete statements that did work.

The reason I didn't convert it to a stored-procedure is that the table-function was faster (even without the MERGE) than the stored-procedure. This is despite the stored-procedure allowing me to use Temp-Tables that have statistics. I needed the table-function to be very fast, since it is called 20-K times/day. This table function never updates the database.

I also noticed that the NewId() and RAND() SQL functions are not allowed in a function.

How to specify Memory & CPU limit in docker compose version 3

Docker Compose does not support the deploy key. It's only respected when you use your version 3 YAML file in a Docker Stack.

This message is printed when you add the deploy key to you docker-compose.yml file and then run docker-compose up -d

WARNING: Some services (database) use the 'deploy' key, which will be ignored. Compose does not support 'deploy' configuration - use docker stack deploy to deploy to a swarm.

The documentation ( says:

Specify configuration related to the deployment and running of services. This only takes effect when deploying to a swarm with docker stack deploy, and is ignored by docker-compose up and docker-compose run.

XPath to select element based on childs child value

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

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

to either

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


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

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

How to read appSettings section in the web.config file?

You should add System.configuration dll as reference and use System.Configuration.ConfigurationManager.AppSettings["configFile"].ToString

Don't forget to add usingstatement at the beginning. Hope it will help.

How to overlay density plots in R?

That's how I do it in base (it's actually mentionned in the first answer comments but I'll show the full code here, including legend as I can not comment yet...)

First you need to get the info on the max values for the y axis from the density plots. So you need to actually compute the densities separately first

dta_A <- density(VarA, na.rm = TRUE)
dta_B <- density(VarB, na.rm = TRUE)

Then plot them according to the first answer and define min and max values for the y axis that you just got. (I set the min value to 0)

plot(dta_A, col = "blue", main = "2 densities on one plot"), 
     ylim = c(0, max(dta_A$y,dta_B$y)))  
lines(dta_B, col = "red")

Then add a legend to the top right corner

legend("topright", c("VarA","VarB"), lty = c(1,1), col = c("blue","red"))

How to get xdebug var_dump to show full object/array

I know this is late but it might be of some use:

echo "<pre>";
echo "</pre>";

How can I wrap or break long text/word in a fixed width span?

By default a span is an inline element... so that's not the default behavior.

You can make the span behave that way by adding display: block; to your CSS.

span {
    display: block;
    width: 100px;

Python Iterate Dictionary by Index

You can iterate over keys and get values by keys:

for key in dict.iterkeys():
    print key, dict[key]

You can iterate over keys and corresponding values:

for key, value in dict.iteritems():
    print key, value

You can use enumerate if you want indexes (remember that dictionaries don't have an order):

>>> for index, key in enumerate(dict):
...     print index, key
0 orange
1 mango
2 apple

Parsing CSV files in C#, with header

Single source file solution for straightforward parsing needs, useful. Deals with all the nasty edge cases. Such as new line normalization and handling new lines in quoted string literals. Your welcome!

If you CSV file has a header you just read out the column names (and compute column indexes) from the first row. Simple as that.

Note that Dump is a LINQPad method, you might want to remove that if you are not using LINQPad.

void Main()
    var file1 = "a,b,c\r\nx,y,z";

    var file2 = "a,\"b\",c\r\nx,\"y,z\"";

    var file3 = "a,\"b\",c\r\nx,\"y\r\nz\"";

    var file4 = "\"\"\"\"";

static class CSV
    public struct Record
        public readonly string[] Row;

        public string this[int index] => Row[index];

        public Record(string[] row)
            Row = row;

    public static List<Record> ParseText(string text)
        return Parse(new StringReader(text));

    public static List<Record> ParseFile(string fn)
        using (var reader = File.OpenText(fn))
            return Parse(reader);

    public static List<Record> Parse(TextReader reader)
        var data = new List<Record>();

        var col = new StringBuilder();
        var row = new List<string>();
        for (; ; )
            var ln = reader.ReadLine();
            if (ln == null) break;
            if (Tokenize(ln, col, row))
                data.Add(new Record(row.ToArray()));

        return data;

    public static bool Tokenize(string s, StringBuilder col, List<string> row)
        int i = 0;

        if (col.Length > 0)
            col.AppendLine(); // continuation

            if (!TokenizeQuote(s, ref i, col, row))
                return false;

        while (i < s.Length)
            var ch = s[i];
            if (ch == ',')
                col.Length = 0;
            else if (ch == '"')
                if (!TokenizeQuote(s, ref i, col, row))
                    return false;

        if (col.Length > 0)
            col.Length = 0;

        return true;

    public static bool TokenizeQuote(string s, ref int i, StringBuilder col, List<string> row)
        while (i < s.Length)
            var ch = s[i];
            if (ch == '"')
                // escape sequence
                if (i + 1 < s.Length && s[i + 1] == '"')
                return true;
        return false;

Contain form within a bootstrap popover?

Either replace double quotes around type="text" with single quotes, Like

"<form><input type='text'/></form>"


replace double quotes wrapping data-content with singe quotes, Like

data-content='<form><input type="text"/></form>'

How do I get whole and fractional parts from double in JSP/Java?

[Edit: The question originally asked how to get the mantissa and exponent.]

Where n is the number to get the real mantissa/exponent:

exponent = int(log(n))
mantissa = n / 10^exponent

Or, to get the answer you were looking for:

exponent = int(n)
mantissa = n - exponent

These are not Java exactly but should be easy to convert.

How do I check whether input string contains any spaces?

If you really want a regex, you can use this one:

str.matches(".*([ \t]).*")

In the sense that everything matching this regex is not a valid xml tag name:

if(str.matches(".*([ \t]).*")) 
      print "the input string is not valid"

Using node.js as a simple web server

if you have node installed on you PC probably you have the NPM, if you don't need NodeJS stuff, you can use the serve package for this:

1 - Install the package on your PC:

npm install -g serve

2 - Serve your static folder:

serve <path> 
d:> serve d:\StaticSite

It will show you which port your static folder is being served, just navigate to the host like:


What does on_delete do on Django models?

The on_delete method is used to tell Django what to do with model instances that depend on the model instance you delete. (e.g. a ForeignKey relationship). The on_delete=models.CASCADE tells Django to cascade the deleting effect i.e. continue deleting the dependent models as well.

Here's a more concrete example. Assume you have an Author model that is a ForeignKey in a Book model. Now, if you delete an instance of the Author model, Django would not know what to do with instances of the Book model that depend on that instance of Author model. The on_delete method tells Django what to do in that case. Setting on_delete=models.CASCADE will instruct Django to cascade the deleting effect i.e. delete all the Book model instances that depend on the Author model instance you deleted.

Note: on_delete will become a required argument in Django 2.0. In older versions it defaults to CASCADE.

Here's the entire official documentation.

ASP.NET MVC Return Json Result?

It should be :

public async Task<ActionResult> GetSomeJsonData()
    var model = // ... get data or build model etc.

    return Json(new { Data = model }, JsonRequestBehavior.AllowGet); 

or more simply:

return Json(model, JsonRequestBehavior.AllowGet); 

I did notice that you are calling GetResources() from another ActionResult which wont work. If you are looking to get JSON back, you should be calling GetResources() from ajax directly...

Should I use past or present tense in git commit messages?

does it matter? people are generally smart enough to interpret messages correctly, if they aren't you probably shouldn't let them access your repository anyway!

Change the location of an object programmatically

When the parent panel has locked property set to true, we could not change the location property and the location property will act like read only by that time.

How do you use the Immediate Window in Visual Studio?

The Immediate window is used to debug and evaluate expressions, execute statements, print variable values, and so forth. It allows you to enter expressions to be evaluated or executed by the development language during debugging.

To display Immediate Window, choose Debug >Windows >Immediate or press Ctrl-Alt-I

enter image description here

Here is an example with Immediate Window:

int Sum(int x, int y) { return (x + y);}
void main(){
int a, b, c;
a = 5;
b = 7;
c = Sum(a, b);
char temp = getchar();}

add breakpoint

enter image description here

call commands

enter image description here

Finding the source code for built-in Python functions?

Quite an unknown resource is the Python Developer Guide.

In a (somewhat) recent GH issue, a new chapter was added for to address the question you're asking: CPython Source Code Layout. If something should change, that resource will also get updated.

exception.getMessage() output with class name

My guess is that you've got something in method1 which wraps one exception in another, and uses the toString() of the nested exception as the message of the wrapper. I suggest you take a copy of your project, and remove as much as you can while keeping the problem, until you've got a short but complete program which demonstrates it - at which point either it'll be clear what's going on, or we'll be in a better position to help fix it.

Here's a short but complete program which demonstrates RuntimeException.getMessage() behaving correctly:

public class Test {
    public static void main(String[] args) {
        try {
        } catch (Exception e) {
            System.out.println("Error: " + e.getMessage());

    private static void failingMethod() {
        throw new RuntimeException("Just the message");


Error: Just the message

Split data frame string column into multiple columns

To add to the options, you could also use my splitstackshape::cSplit function like this:

cSplit(before, "type", "_and_")
#    attr type_1 type_2
# 1:    1    foo    bar
# 2:   30    foo  bar_2
# 3:    4    foo    bar
# 4:    6    foo  bar_2

Markdown open a new window link

Using sed

If one would like to do this systematically for all external links, CSS is no option. However, one could run the following sed command once the (X)HTML has been created from Markdown:

sed -i 's|href="http|target="_blank" href="http|g' index.html

This can be further automated in a single workflow when a Makefile with build instructions is employed.

PS: This answer was written at a time when extension link_attributes was not yet available in Pandoc.

Interface defining a constructor signature?

You can't. It's occasionally a pain, but you wouldn't be able to call it using normal techniques anyway.

In a blog post I've suggested static interfaces which would only be usable in generic type constraints - but could be really handy, IMO.

One point about if you could define a constructor within an interface, you'd have trouble deriving classes:

public class Foo : IParameterlessConstructor
    public Foo() // As per the interface

public class Bar : Foo
    // Yikes! We now don't have a parameterless constructor...
    public Bar(int x)

How can I pause setInterval() functions?

The following code, provides a precision way to pause resume a timer.

How it works:

When the timer is resumed after a pause, it generates a correction cycle using a single timeout, that will consider the pause offset (exact time when the timer was paused between cycles). After the correction cycle finishes, it schedules the following cycles with a regular setInteval, and continues normally the cycle execution.

This allows to pause/resume the timer, without losing the sync.

Code :

function Timer(_fn_callback_ , _timer_freq_){_x000D_
    let RESUME_CORRECTION_RATE = 2;_x000D_
    let _timer_statusCode_;_x000D_
    let _timer_clockRef_;_x000D_
    let _time_ellapsed_;        // will store the total time ellapsed_x000D_
    let _time_pause_;           // stores the time when timer is paused_x000D_
    let _time_lastCycle_;       // stores the time of the last cycle_x000D_
    let _isCorrectionCycle_;_x000D_
     * execute in each clock cycle_x000D_
    const nextCycle = function(){_x000D_
        // calculate deltaTime_x000D_
        let _time_delta_        = new Date() - _time_lastCycle_;_x000D_
        _time_lastCycle_    = new Date();_x000D_
        _time_ellapsed_   += _time_delta_;_x000D_
        // if its a correction cicle (caused by a pause,_x000D_
        // destroy the temporary timeout and generate a definitive interval_x000D_
        if( _isCorrectionCycle_ ){_x000D_
            clearTimeout( _timer_clockRef_ );_x000D_
            clearInterval( _timer_clockRef_ );_x000D_
            _timer_clockRef_    = setInterval(  nextCycle , _timer_freq_  );_x000D_
            _isCorrectionCycle_ = false;_x000D_
        // execute callback_x000D_
        _fn_callback_.apply( timer, [ timer ] );_x000D_
    // initialize timer_x000D_
    _time_ellapsed_     = 0;_x000D_
    _time_lastCycle_     = new Date();_x000D_
    _timer_statusCode_   = 1;_x000D_
    _timer_clockRef_     = setInterval(  nextCycle , _timer_freq_  );_x000D_
    // timer public API_x000D_
    const timer = {_x000D_
        get statusCode(){ return _timer_statusCode_ },_x000D_
        get timestamp(){_x000D_
            let abstime;_x000D_
            if( _timer_statusCode_=== 1 ) abstime = _time_ellapsed_ + ( new Date() - _time_lastCycle_ );_x000D_
            else if( _timer_statusCode_=== 2 ) abstime = _time_ellapsed_ + ( _time_pause_ - _time_lastCycle_ );_x000D_
            return abstime || 0;_x000D_
        pause : function(){_x000D_
            if( _timer_statusCode_ !== 1 ) return this;_x000D_
            // stop timers_x000D_
            clearTimeout( _timer_clockRef_ );_x000D_
            clearInterval( _timer_clockRef_ );_x000D_
            // set new status and store current time, it will be used on_x000D_
            // resume to calculate how much time is left for next cycle_x000D_
            // to be triggered_x000D_
            _timer_statusCode_ = 2;_x000D_
            _time_pause_       = new Date();_x000D_
            return this;_x000D_
        resume: function(){_x000D_
            if( _timer_statusCode_ !== 2 ) return this;_x000D_
            _timer_statusCode_  = 1;_x000D_
            _isCorrectionCycle_ = true;_x000D_
            const delayEllapsedTime = _time_pause_ - _time_lastCycle_;_x000D_
            _time_lastCycle_    = new Date( new Date() - (_time_pause_ - _time_lastCycle_) );_x000D_
            _timer_clockRef_ = setTimeout(  nextCycle , _timer_freq_ - delayEllapsedTime - RESUME_CORRECTION_RATE);_x000D_
            return this;_x000D_
        } _x000D_
    return timer;_x000D_
let myTimer = Timer( x=> console.log(x.timestamp), 1000);
<input type="button" onclick="myTimer.pause()" value="pause">_x000D_
<input type="button" onclick="myTimer.resume()" value="resume">

Code source :

This Timer is a modified and simplified version of advanced-timer, a js library created by myself, with many more functionalities.

The full library and documentation is available in NPM and GITHUB

linq query to return distinct field values from a list of objects

If just want to use Linq, you can override Equals and GetHashCode methods.

Product class:

public class Product
    public string ProductName { get; set; }
    public int Id { get; set; }

    public override bool Equals(object obj)
        if (!(obj is Product))
            return false;

        var other = (Product)obj;
        return Id == other.Id;

    public override int GetHashCode()
        return Id.GetHashCode();

Main Method:

static void Main(string[] args)

        var products = new List<Product>
            new Product{ ProductName="Product 1",Id = 1},
            new Product{ ProductName="Product 2",Id = 2},
            new Product{ ProductName="Product 4",Id = 5},
            new Product{ ProductName="Product 3",Id = 3},
            new Product{ ProductName="Product 4",Id = 4},
            new Product{ ProductName="Product 6",Id = 4},
            new Product{ ProductName="Product 6",Id = 4},

        var itemsDistinctByProductName = products.Distinct().ToList();

        foreach (var product in itemsDistinctByProductName)
            Console.WriteLine($"Product Id : {product.Id} ProductName : {product.ProductName} ");


Responsive background image in div full width

I also tried this style for ionic hybrid app background. this is also having style for background blur effect.

.bg-image {
   position: absolute;
   background: url(../img/bglogin.jpg) no-repeat;
   height: 100%;
   width: 100%;
   background-size: cover;
   bottom: 0px;
   margin: 0 auto;
   background-position: 50%;

  -webkit-filter: blur(5px);
  -moz-filter: blur(5px);
  -o-filter: blur(5px);
  -ms-filter: blur(5px);
  filter: blur(5px);


What's the best way to trim std::string?

It is so annoying that I

  • have to google it
  • find out that I have to use rocket science
  • that there is no simple trim/toupper function in string

For me this is the fastest way to solve it:

CString tmp(line.c_str());
tmp = tmp.Trim().MakeLower();
string buffer = tmp;

Ok, it is cool that I can use lambda ops, iterators, and all the stuff. But I only need to deal with a string instead of a character...

MAX function in where clause mysql

Do you want the first and last name of the row with the largest id?

If so (and you were missing a FROM clause):

SELECT firstname, lastname, id
FROM foo

HTML for the Pause symbol in audio and video control

There is no character encoded for use as a pause symbol, though various characters or combinations of characters may look more or less like a pause symbol, depending on font.

In a discussion in the public Unicode mailing list in 2005, a suggestion was made to use two copies of the U+275A HEAVY VERTICAL BAR character: ??. But the adequacy of the result depends on font; for example, the glyph might have been designed so that the bars are too much apart. – The list discussion explains why a pause symbol had not been encoded, and this has not changed.

Thus, the best option is to use an image. If you need to use the symbol in text, it is best to create it in a suitably large size (say 60 by 60 pixels) and scale it down to text size with CSS (e.g., setting height: 0.8em on the img element).

500 Error on AppHarbor but downloaded build works on my machine

Just a wild guess: (not much to go on) but I have had similar problems when, for example, I was using the IIS rewrite module on my local machine (and it worked fine), but when I uploaded to a host that did not have that add-on module installed, I would get a 500 error with very little to go on - sounds similar. It drove me crazy trying to find it.

So make sure whatever options/addons that you might have and be using locally in IIS are also installed on the host.

Similarly, make sure you understand everything that is being referenced/used in your web.config - that is likely the problem area.

Export P7b file with all the certificate chain into CER file

-print_certs is the option you want to use to list all of the certificates in the p7b file, you may need to specify the format of the p7b file you are reading.

You can then redirect the output to a new file to build the concatenated list of certificates.

Open the file in a text editor, you will either see Base64 (PEM) or binary data (DER).

openssl pkcs7 -inform DER -outform PEM -in certificate.p7b -print_certs > certificate_bundle.cer

When is it appropriate to use UDP instead of TCP?

Network communication for video games is almost always done over UDP.

Speed is of utmost importance and it doesn't really matter if updates are missed since each update contains the complete current state of what the player can see.

Jenkins restrict view of jobs per user

I use combination of several plugins - for the basic assignment of roles and permission I use Role Strategy Plugin.

When I need to split some role depending on parameters (e.g. everybody with job-runner is able to run jobs, but user only user UUU is allowed to run the deployment job to deploy on machine MMM), I use Python Plugin and define a python script as first build step and end with sys.exit(-1) when the job is forbidden to be run with the given combination of parameters.

Build User Vars Plugin provides me the information about the user executing the job as environment variables.


import os
import sys

print os.environ["BUILD_USER"], "deploying to", os.environ["target_host"]

# only some users are allowed to deploy to servers "MMM"
mmm_users = ["UUU"]

if os.environ["target_host"] != "MMM" or os.environ["BUILD_USER"] in mmm_users:
    print "access granted"
    print "access denied"

onchange equivalent in angular2

You can use:

<input (input)="saverange()>

Install a .NET windows service without InstallUtil.exe

Yes, that is fully possible (i.e. I do exactly this); you just need to reference the right dll (System.ServiceProcess.dll) and add an installer class...

Here's an example:

public sealed class MyServiceInstallerProcess : ServiceProcessInstaller
    public MyServiceInstallerProcess()
        this.Account = ServiceAccount.NetworkService;

public sealed class MyServiceInstaller : ServiceInstaller
    public MyServiceInstaller()
        this.Description = "Service Description";
        this.DisplayName = "Service Name";
        this.ServiceName = "ServiceName";
        this.StartType = System.ServiceProcess.ServiceStartMode.Automatic;

static void Install(bool undo, string[] args)
        Console.WriteLine(undo ? "uninstalling" : "installing");
        using (AssemblyInstaller inst = new AssemblyInstaller(typeof(Program).Assembly, args))
            IDictionary state = new Hashtable();
            inst.UseNewContext = true;
                if (undo)
                catch { }
    catch (Exception ex)

Pan & Zoom Image

I also tried this answer but was not entirely happy with the result. I kept googling around and finally found a Nuget Package that helped me to manage the result I wanted, anno 2021. I would like to share it with the former developers of Stack Overflow.

I used this Nuget Package Gu.WPF.Geometry found via this Github Repository. All credits for develoment should go to Johan Larsson, the owner of this package.

How I used it? I wanted to have the commands as buttons below the zoombox, as shown here in MachineLayoutControl.xaml .

       <ResourceDictionary Source="Resources/ResourceDictionaries/AllResourceDictionariesCombined.xaml" />

   <Grid Margin="0">
           <RowDefinition Height="*" />
           <RowDefinition Height="Auto" />

           Style="{StaticResource Border_Head}"
               Visibility="{Binding Zoombox_Visibility}">
               <ContentControl Content="{Binding Viewing_Canvas}" />
                   CommandTarget="{Binding ElementName=ImageBox}"
                   Content="Zoom In"
                   Style="{StaticResource StyleForResizeButtons}" />

                   CommandTarget="{Binding ElementName=ImageBox}"
                   Content="Zoom Out"
                   Style="{StaticResource StyleForResizeButtons}" />

                   CommandTarget="{Binding ElementName=ImageBox}"
                   Content="See Full Machine"
                   Style="{StaticResource StyleForResizeButtons}" />

                   CommandTarget="{Binding ElementName=ImageBox}"
                   Content="Zoom To Machine Width"
                   Style="{StaticResource StyleForResizeButtons}" />


In the underlying Viewmodel, I had the following relevant code:

public Visibility Zoombox_Visibility { get => movZoombox_Visibility; set { movZoombox_Visibility = value; OnPropertyChanged(nameof(Zoombox_Visibility)); } }
public Canvas Viewing_Canvas { get => mdvViewing_Canvas; private set => mdvViewing_Canvas = value; }

Also, I wanted that immediately on loading, the Uniform to Fill Command was executed, this is something that I managed to do in the code-behind MachineLayoutControl.xaml.cs . You see that I only set the Zoombox to visible if the command is executed, to avoid "flickering" when the usercontrol is loading.

    public partial class MachineLayoutControl : UserControl
        #region Constructors

        public MachineLayoutControl()
            Loaded += MyWindow_Loaded;

        #endregion Constructors

        #region EventHandlers

        private void MyWindow_Loaded(object sender, RoutedEventArgs e)
               new Action(() =>
                   ZoomCommands.Uniform.Execute(null, ImageBox);
                   ((MachineLayoutControlViewModel)DataContext).Zoombox_Visibility = Visibility.Visible;

        #endregion EventHandlers


Get SELECT's value and text in jQuery

<select id="ddlViewBy">
    <option value="value">text</option>


var txt = $("#ddlViewBy option:selected").text();
var val = $("#ddlViewBy option:selected").val();

JS Fiddle DEMO

Printing tuple with string formatting in Python

Talk is cheap, show you the code:

>>> tup = (10, 20, 30)
>>> i = 50
>>> print '%d      %s'%(i,tup)
50  (10, 20, 30)
>>> print '%s'%(tup,)
(10, 20, 30)

Why do I need an IoC container as opposed to straightforward DI code?

You would need an IoC container if you needed to centralize the configuration of your dependencies so that they may be easily swapped out en mass. This makes the most sense in TDD, where many dependencies are swapped out, but where there is little interdependence between the dependencies. This is done at the cost of obfuscating the flow of control of object construction to some degree, so having a well organized and reasonably documented configuration is important. It is also good to have a reason to do this, otherwise, it is mere abstraction gold-plating. I have seen it done so poorly that it was dragged down to being the equivalent to a goto statement for constructors.

How do I check what version of Python is running my script?

The simplest way

Just type python in your terminal and you can see the version as like following

desktop:~$ python
Python 2.7.6 (default, Jun 22 2015, 18:00:18) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.

Unix command to check the filesize

You can use:ls -lh, then you will get a list of file information

Difference between "\n" and Environment.NewLine

You might get into trouble when you try to display multi-line message separated with "\r\n".

It is always a good practice to do things in a standard way, and use Environment.NewLine

Close Bootstrap modal on form submit

I am using rails and ajax too and I had the same problem. just run this code


that worked for me but I am trying to also fix it without using jQuery.

Retrofit 2: Get JSON from Response body

add dependency for retrofit2

compile ''
compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'

create class for base url

public class ApiClient     
public static final String BASE_URL = "base_url";

private static Retrofit retrofit = null;

public static Retrofit getClient() {
    if (retrofit==null) {
        retrofit = new Retrofit.Builder()
    return retrofit;


after that create class model to get value

public class ApprovalModel {

private String approvalName;
public String getApprovalName() {
    return approvalName;

create interface class

public interface ApiInterface { 
Call<CompanyDetailsResponse> getCompanyDetails();

after that in main class

            final ProgressDialog mProgressDialog = new ProgressDialog(mContext);

            ApiInterface apiService =

            Call<CompanyDetailsResponse> call = apiService.getCompanyDetails();
            call.enqueue(new Callback<CompanyDetailsResponse>() {
                public void onResponse(Call<CompanyDetailsResponse>call, Response<CompanyDetailsResponse> response) {
                    if(response!=null && response.isSuccessful()) {
                        List<CompanyDetails> companyList = response.body().getCompanyDetailsList();

                        if (companyList != null&&companyList.size()>0) {
                            for (int i = 0; i < companyList.size(); i++) {
                                Log.d(TAG, "" + companyList.get(i));
                         //get values
                            //show alert not get value
                        //show error message


                public void onFailure(Call<CompanyDetailsResponse>call, Throwable t) {
                    // Log error here since request failed
                    Log.e(TAG, t.toString());
            //network error alert box


XOR operation with two strings in java

This solution is compatible with Android (I've tested and used it myself). Thanks to @user467257 whose solution I adapted this from.

import android.util.Base64;

public class StringXORer {

public String encode(String s, String key) {
    return new String(Base64.encode(xorWithKey(s.getBytes(), key.getBytes()), Base64.DEFAULT));

public String decode(String s, String key) {
    return new String(xorWithKey(base64Decode(s), key.getBytes()));

private byte[] xorWithKey(byte[] a, byte[] key) {
    byte[] out = new byte[a.length];
    for (int i = 0; i < a.length; i++) {
        out[i] = (byte) (a[i] ^ key[i%key.length]);
    return out;

private byte[] base64Decode(String s) {
    return Base64.decode(s,Base64.DEFAULT);

private String base64Encode(byte[] bytes) {
    return new String(Base64.encode(bytes,Base64.DEFAULT));


How to unlock android phone through ADB

Below commands works both when screen is on and off

To lock the screen:

adb shell input keyevent 82 && adb shell input keyevent 26 && adb shell input keyevent 26

To lock the screen and turn it off

adb shell input keyevent 82 && adb shell input keyevent 26

To unlock the screen without pass

adb shell input keyevent 82 && adb shell input keyevent 66

To unlock the screen that has pass 1234

adb shell input keyevent 82 && adb shell input text 1234 && adb shell input keyevent 66

Where is the file in a Spring Boot project?

You can also create the file manually.

SpringApplication will load properties from files in the following locations and add them to the Spring Environment:

  • A /config subdirectory of the current directory.
  • The current directory
  • A classpath /config package
  • The classpath root

The list is ordered by precedence (properties defined in locations higher in the list override those defined in lower locations). (From the Spring boot features external configuration doc page)

So just go ahead and create it

Angular JS break ForEach

Use Return to break the loop.

angular.forEach([0,1,2], function(count){
  if(count == 1) {

How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ?

A picture is worth a thousand words:

PHP Double Equals == equality chart:

enter image description here

PHP Triple Equals === Equality chart:

enter image description here

Source code to create these images:

Guru Meditation

Those who wish to keep their sanity, read no further because none of this will make any sense, except to say that this is how the insanity-fractal, of PHP was designed.

  1. NAN != NAN but NAN == true.

  2. == will convert left and right operands to numbers if left is a number. So 123 == "123foo", but "123" != "123foo"

  3. A hex string in quotes is occasionally a float, and will be surprise cast to float against your will, causing a runtime error.

  4. == is not transitive because "0"== 0, and 0 == "" but "0" != ""

  5. PHP Variables that have not been declared yet are false, even though PHP has a way to represent undefined variables, that feature is disabled with ==.

  6. "6" == " 6", "4.2" == "4.20", and "133" == "0133" but 133 != 0133. But "0x10" == "16" and "1e3" == "1000" exposing that surprise string conversion to octal will occur both without your instruction or consent, causing a runtime error.

  7. False == 0, "", [] and "0".

  8. If you add 1 to number and they are already holding their maximum value, they do not wrap around, instead they are cast to infinity.

  9. A fresh class is == to 1.

  10. False is the most dangerous value because False is == to most of the other variables, mostly defeating it's purpose.


If you are using PHP, Thou shalt not use the double equals operator because if you use triple equals, the only edge cases to worry about are NAN and numbers so close to their datatype's maximum value, that they are cast to infinity. With double equals, anything can be surprise == to anything or, or can be surprise casted against your will and != to something of which it should obviously be equal.

Anywhere you use == in PHP is a bad code smell because of the 85 bugs in it exposed by implicit casting rules that seem designed by millions of programmers programming by brownian motion.

How do I make HttpURLConnection use a proxy?

For Java 1.8 and higher you must set -Djdk.http.auth.tunneling.disabledSchemes= to make proxies with Basic Authorization working with https.

Html code as IFRAME source rather than a URL

iframe srcdoc: This attribute contains HTML content, which will override src attribute. If a browser does not support the srcdoc attribute, it will fall back to the URL in the src attribute.

Let's understand it with an example

    srcdoc="<h1 style='text-align:center; color:#9600fa'>Welcome to iframes</h1>"

Original content is taken from iframes.

android asynctask sending callbacks to ui

I felt the below approach is very easy.

I have declared an interface for callback

public interface AsyncResponse {
    void processFinish(Object output);

Then created asynchronous Task for responding all type of parallel requests

 public class MyAsyncTask extends AsyncTask<Object, Object, Object> {

    public AsyncResponse delegate = null;//Call back interface

    public MyAsyncTask(AsyncResponse asyncResponse) {
        delegate = asyncResponse;//Assigning call back interfacethrough constructor

    protected Object doInBackground(Object... params) {

    //My Background tasks are written here

      return {resutl Object}


    protected void onPostExecute(Object result) {


Then Called the asynchronous task when clicking a button in activity Class.

public class MainActivity extends Activity {

    public void onCreate(Bundle savedInstanceState) {

        Button mbtnPress = (Button) findViewById(;

        mbtnPress.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {

                MyAsyncTask asyncTask =new MyAsyncTask(new AsyncResponse() {

                    public void processFinish(Object output) {
                        Log.d("Response From Asynchronous task:", (String) output);          
                        mbtnPress.setText((String) output);
                asyncTask.execute(new Object[] { "Youe request to aynchronous task class is giving here.." });



combining two data frames of different lengths

Just my 2 cents. This code combines two matrices or data.frames into one. If one data structure have lower number of rows then missing rows will be added with NA values.

combine.df <- function(x, y) {
    rows.x <- nrow(x)
    rows.y <- nrow(y)
    if (rows.x > rows.y) {
        diff <- rows.x - rows.y <- matrix(NA, diff, ncol(y))
        colnames( <- colnames(y)
        cbind(x, rbind(y,
    } else {
        diff <- rows.y - rows.x <- matrix(NA, diff, ncol(x))
        colnames( <- colnames(x)
        cbind(rbind(x,, y)

df1 <- data.frame(1:10, row.names = 1:10)
df2 <- data.frame(1:5, row.names = 10:14)
combine.df(df1, df2)

Latex Remove Spaces Between Items in List

You could do something like this:




  \item foo
  \item bar
  \item baz

Less space:

  \item foo
  \item bar
  \item baz


xxxxxx.exe is not a valid Win32 application

There are at least two solutions:

  1. You need Visual Studio 2010 installed, then from Visual Studio 2010, View -> Solution Explorer -> Right Click on your project -> Choose Properties from the context menu, you'll get the windows "your project name" Property Pages -> Configuration Properties -> General -> Platform toolset, choose "Visual Studio 2010 (v100)".
  2. You need the Visual Studio 2012 Update 1 described in Windows XP Targeting with C++ in Visual Studio 2012

How to insert a line break before an element using CSS

Try the following:

#restart::before {
  content: '';
  display: block;

How can a divider line be added in an Android RecyclerView?

I think you are using Fragments to have RecyclerView

Simply add these lines after creating your RecyclerView and LayoutManager Objects

DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(),

Thats it!

It supports both HORIZONTAL and VERTICAL orientations.

Tooltip on image

Using javascript, you can set tooltips for all the images on the page.

<!DOCTYPE html>
    <img src="" alt="Food">
    <img src="" alt="Pizza">
     //image objects
     var imageEls = document.getElementsByTagName("img");
     for(var i=0;i<imageEls.length;i++){
        //imageEls[i].title="Title of your choice";

Difference between webdriver.get() and webdriver.navigate()


In the below code I navigated to 3 different URLs and when the execution comes to navigate command, it navigated back to facebook home page.

public class FirefoxInvoke {
                public static void browserInvoke()
                    System.setProperty("webdriver.gecko.driver", "gecko-driver-path");
                WebDriver driver=new FirefoxDriver();

                public static void main(String[] args) {
                    // TODO Auto-generated method stub



In below code, I have used navigate() instead of get(), but both the snippets(Case-1 and Case-2) are working exactly the same, just the case-2 execution time is less than of case-1

public class FirefoxInvoke {
                public static void browserInvoke()
                    System.setProperty("webdriver.gecko.driver", "gecko-driver-path");
                WebDriver driver=new FirefoxDriver();

                public static void main(String[] args) {
                    // TODO Auto-generated method stub

  • So the main difference between get() and navigate() is, both are performing the same task but with the use of navigate() you can move back() or forward() in your session's history.
  • navigate() is faster than get() because navigate() does not wait for the page to load fully or completely.

Double array initialization in Java

double m[][] declares an array of arrays, so called multidimensional array.

m[0] points to an array in the size of four, containing 0*0,1*0,2*0,3*0. Simple math shows the values are actually 0,0,0,0.

Second line is also array in the size of four, containing 0,1,2,3.

And so on...

I guess this mutiple format in you book was to show that 0*0 is row 0 column 0, 0*1 is row 0 column 1, and so on.

iOS detect if user is on an iPad

This is part of UIDevice as of iOS 3.2, e.g.:

[UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPad

How can I use jQuery in Greasemonkey?

If you are using chrome you have to opt for an alternative as Chromium does not support @require.

Source: The Chromium Project - User scripts

More details and alternatives on How can I use jQuery in Greasemonkey scripts in Google Chrome?

PHP Array to CSV

This is a simple solution that exports an array to csv string:

function array2csv($data, $delimiter = ',', $enclosure = '"', $escape_char = "\\")
    $f = fopen('php://memory', 'r+');
    foreach ($data as $item) {
        fputcsv($f, $item, $delimiter, $enclosure, $escape_char);
    return stream_get_contents($f);

$list = array (
    array('aaa', 'bbb', 'ccc', 'dddd'),
    array('123', '456', '789'),
    array('"aaa"', '"bbb"')

How to restart a windows service using Task Scheduler

Instead of using a bat file, you can simply create a Scheduled Task. Most of the time you define just one action. In this case, create two actions with the NET command. The first one to stop the service, the second one to start the service. Give them a STOP and START argument, followed by the service name.

In this example we restart the Printer Spooler service.

NET STOP "Print Spooler" 
NET START "Print Spooler"

enter image description here

enter image description here

Note: unfortunately NET RESTART <service name> does not exist.

ERROR 2003 (HY000): Can't connect to MySQL server on '' (111)

I just have this problem.... running in Win7 and wamp server ... after reading this

Found that Antivirus Firewall has caused the problem.

How to write :hover using inline style?

Not gonna happen with CSS only

Inline javascript

<a href='index.html' 
    Click Me

In a working draft of the CSS2 spec it was declared that you could use pseudo-classes inline like this:

<a href=""
   style="{color: blue; background: white}  /* a+=0 b+=0 c+=0 */
      :visited {color: green}           /* a+=0 b+=1 c+=0 */
      :hover {background: yellow}       /* a+=0 b+=1 c+=0 */
      :visited:hover {color: purple}    /* a+=0 b+=2 c+=0 */

but it was never implemented in the release of the spec as far as I know.

Best way to detect when a user leaves a web page?

Thanks to Service Workers, it is possible to implement a solution similar to Adam's purely on the client-side, granted the browser supports it. Just circumvent heartbeat requests:

// The delay should be longer than the heartbeat by a significant enough amount that there won't be false positives
const liveTimeoutDelay = 10000
let liveTimeout = null

global.self.addEventListener('fetch', event => {
  liveTimeout = setTimeout(() => {
    console.log('User left page')
    // handle page leave
  }, liveTimeoutDelay)
  // Forward any events except for hearbeat events
  if (event.request.url.endsWith('/heartbeat')) {
      new global.Response('Still here')

x86 Assembly on a Mac

Don't forget that unlike Windows, all Unix based system need to have the source before destination unlike Windows

On Windows its:

mov $source , %destination

but on the Mac its the other way around.

sed: print only matching group

The cut command is designed for this exact situation. It will "cut" on any delimiter and then you can specify which chunks should be output.

For instance: echo "foo bar <foo> bla 1 2 3.4" | cut -d " " -f 6-7

Will result in output of: 2 3.4

-d sets the delimiter

-f selects the range of 'fields' to output, in this case, it's the 6th through 7th chunks of the original string. You can also specify the range as a list, such as 6,7.

What is the proper declaration of main in C++?

The main function must be declared as a non-member function in the global namespace. This means that it cannot be a static or non-static member function of a class, nor can it be placed in a namespace (even the unnamed namespace).

The name main is not reserved in C++ except as a function in the global namespace. You are free to declare other entities named main, including among other things, classes, variables, enumerations, member functions, and non-member functions not in the global namespace.

You can declare a function named main as a member function or in a namespace, but such a function would not be the main function that designates where the program starts.

The main function cannot be declared as static or inline. It also cannot be overloaded; there can be only one function named main in the global namespace.

The main function cannot be used in your program: you are not allowed to call the main function from anywhere in your code, nor are you allowed to take its address.

The return type of main must be int. No other return type is allowed (this rule is in bold because it is very common to see incorrect programs that declare main with a return type of void; this is probably the most frequently violated rule concerning the main function).

There are two declarations of main that must be allowed:

int main()               // (1)
int main(int, char*[])   // (2)

In (1), there are no parameters.

In (2), there are two parameters and they are conventionally named argc and argv, respectively. argv is a pointer to an array of C strings representing the arguments to the program. argc is the number of arguments in the argv array.

Usually, argv[0] contains the name of the program, but this is not always the case. argv[argc] is guaranteed to be a null pointer.

Note that since an array type argument (like char*[]) is really just a pointer type argument in disguise, the following two are both valid ways to write (2) and they both mean exactly the same thing:

int main(int argc, char* argv[])
int main(int argc, char** argv)

Some implementations may allow other types and numbers of parameters; you'd have to check the documentation of your implementation to see what it supports.

main() is expected to return zero to indicate success and non-zero to indicate failure. You are not required to explicitly write a return statement in main(): if you let main() return without an explicit return statement, it's the same as if you had written return 0;. The following two main() functions have the same behavior:

int main() { }
int main() { return 0; }

There are two macros, EXIT_SUCCESS and EXIT_FAILURE, defined in <cstdlib> that can also be returned from main() to indicate success and failure, respectively.

The value returned by main() is passed to the exit() function, which terminates the program.

Note that all of this applies only when compiling for a hosted environment (informally, an environment where you have a full standard library and there's an OS running your program). It is also possible to compile a C++ program for a freestanding environment (for example, some types of embedded systems), in which case startup and termination are wholly implementation-defined and a main() function may not even be required. If you're writing C++ for a modern desktop OS, though, you're compiling for a hosted environment.

Consider marking event handler as 'passive' to make the page more responsive

Also encounter this in select2 dropdown plugin in Laravel. Changing the value as suggested by Alfred Wallace from

this.element.addEventListener(t, e, !1)


this.element.addEventListener(t, e, { passive: true} )

solves the issue. Why he has a down vote, I don't know but it works for me.

How to refresh page on back button click?

A more recent solution is using the The PerformanceNavigation interface:

if(!!window.performance && window.performance.navigation.type === 2)

Where the value 2 means "The page was accessed by navigating into the history".

View browser support here:

Reload the site when reached via browsers back button

Convert string to title case with JavaScript

Here's my version, IMO it's easy to understand and elegant too.

var str = "foo bar baz"_x000D_
str.split(' ')_x000D_
   .map(w => w[0].toUpperCase() + w.substr(1).toLowerCase())_x000D_
   .join(' ')_x000D_
// returns "Foo Bar Baz"

Save a list to a .txt file

If you have more then 1 dimension array

with open("file.txt", 'w') as output:
    for row in values:
        output.write(str(row) + '\n')

Code to write without '[' and ']'

with open("file.txt", 'w') as file:
        for row in values:
            s = " ".join(map(str, row))


You didn't join the table in your query.

Your original query will always return nothing unless there are no records at all in eotm_dyn, in which case it will return everything.

Assuming these tables should be joined on employeeID, use the following:

FROM    employees e
        SELECT  null 
        FROM    eotm_dyn d
        WHERE   d.employeeID =

You can join these tables with a LEFT JOIN keyword and filter out the NULL's, but this will likely be less efficient than using NOT EXISTS.

Firefox "ssl_error_no_cypher_overlap" error

Given what you've tried and the error messages, I'd say this was more to do with the exact cipher algorithm used rather than the TLS/SSL version. Are you using a non-Sun JRE by any chance, or a different vendor's security implementation? Try a different JRE/OS to test your server if you can. Failing that you might just be able to see what's going on with Wireshark (with a filter of 'tcp.port == 443').

Play local (hard-drive) video file with HTML5 video tag?

That will be possible only if the HTML file is also loaded with the file protocol from the local user's harddisk.

If the HTML page is served by HTTP from a server, you can't access any local files by specifying them in a src attribute with the file:// protocol as that would mean you could access any file on the users computer without the user knowing which would be a huge security risk.

As Dimitar Bonev said, you can access a file if the user selects it using a file selector on their own. Without that step, it's forbidden by all browsers for good reasons. Thus, while his answer might prove useful for many people, it loosens the requirement from the code in the original question.

PHP foreach loop through multidimensional array

If you mean the first and last entry of the array when talking about a.first and a.last, it goes like this:

foreach ($arr_nav as $inner_array) {
    echo reset($inner_array); //apple, orange, pear
    echo end($inner_array); //My Apple, View All Oranges, A Pear

arrays in PHP have an internal pointer which you can manipulate with reset, next, end. Retrieving keys/values works with key and current, but using each might be better in many cases..

How to convert HTML to PDF using iText

You can do it with the HTMLWorker class (deprecated) like this:

import com.itextpdf.text.html.simpleparser.HTMLWorker;
try {
    String k = "<html><body> This is my Project </body></html>";
    OutputStream file = new FileOutputStream(new File("C:\\Test.pdf"));
    Document document = new Document();
    PdfWriter.getInstance(document, file);;
    HTMLWorker htmlWorker = new HTMLWorker(document);
    htmlWorker.parse(new StringReader(k));
} catch (Exception e) {

or using the XMLWorker, (download from this jar) using this code:

import com.itextpdf.tool.xml.XMLWorkerHelper;
try {
    String k = "<html><body> This is my Project </body></html>";
    OutputStream file = new FileOutputStream(new File("C:\\Test.pdf"));
    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, file);;
    InputStream is = new ByteArrayInputStream(k.getBytes());
    XMLWorkerHelper.getInstance().parseXHtml(writer, document, is);
} catch (Exception e) {

jQuery - Create hidden form element on the fly

The same as David's, but without attr()

$('<input>', {
    type: 'hidden',
    id: 'foo',
    name: 'foo',
    value: 'bar'

Why call super() in a constructor?

It simply calls the default constructor of the superclass.

No such keg: /usr/local/Cellar/git

Os X Mojave 10.14 has:

Error: The Command Line Tools header package must be installed on Mojave.

Solution. Go to


location and install the package manually. And brew will start working and we can run:

brew uninstall --force git
brew cleanup --force -s git
brew prune
brew install git

Removing carriage return and new-line from the end of a string in c#

If you are using multiple platforms you are safer using this method.


It will account for different newline and carriage-return characters.

SMTP Connect() failed. Message was not sent.Mailer error: SMTP Connect() failed

I know its been a while since this question but I had the exact problem and solved it by disabling SMTP_BLOCK on csf.conf (we use CSF for a firewall).

To disable just edit csf.conf and disable SMTP_BLOCK like so:

# Block outgoing SMTP except for root, exim and mailman (forces scripts/users
# to use the exim/sendmail binary instead of sockets access). This replaces the
# protection as WHM > Tweak Settings > SMTP Tweaks
# This option uses the iptables ipt_owner/xt_owner module and must be loaded
# for it to work. It may not be available on some VPS platforms
# Note: Run /etc/csf/ to check whether this option will function on
# this server
# SMTP_BLOCK = "1" --> this will cause phpmailer Connection timed out (110)

Toggle visibility property of div

According to the jQuery docs, calling toggle() without parameters will toggle visibility.


how to toggle attr() in jquery

$("form > .form-group > i").click(function(){
    $('#icon').toggleClass('fa-eye fa-eye-slash');

    } else {

How to change the buttons text using javascript

I know this question has been answered but I also see there is another way missing which I would like to cover it.There are multiple ways to achieve this.

1- innerHTML

document.getElementById("ShowButton").innerHTML = 'Show Filter';

You can insert HTML into this. But the disadvantage of this method is, it has cross site security attacks. So for adding text, its better to avoid this for security reasons.

2- innerText

document.getElementById("ShowButton").innerText = 'Show Filter';

This will also achieve the result but its heavy under the hood as it requires some layout system information, due to which the performance decreases. Unlike innerHTML, you cannot insert the HTML tags with this. Check Performance Here

3- textContent

document.getElementById("ShowButton").textContent = 'Show Filter';

This will also achieve the same result but it doesn't have security issues like innerHTML as it doesn't parse HTML like innerText. Besides, it is also light due to which performance increases.

So if a text has to be added like above, then its better to use textContent.

How can I wait for set of asynchronous callback functions?

Checking in from 2015: We now have native promises in most recent browser (Edge 12, Firefox 40, Chrome 43, Safari 8, Opera 32 and Android browser 4.4.4 and iOS Safari 8.4, but not Internet Explorer, Opera Mini and older versions of Android).

If we want to perform 10 async actions and get notified when they've all finished, we can use the native Promise.all, without any external libraries:

function asyncAction(i) {
    return new Promise(function(resolve, reject) {
        var result = calculateResult();
        if (result.hasError()) {
            return reject(result.error);
        return resolve(result);

var promises = [];
for (var i=0; i < 10; i++) {

Promise.all(promises).then(function AcceptHandler(results) {
}, function ErrorHandler(error) {

How to do a redirect to another route with react-router?

1) react-router > V5 useHistory hook:

If you have React >= 16.8 and functional components you can use the useHistory hook from react-router.

import React from 'react';
import { useHistory } from 'react-router-dom';

const YourComponent = () => {
    const history = useHistory();

    const handleClick = () => {

    return (
            <button onClick={handleClick} type="button" />

export default YourComponent;

2) react-router > V4 withRouter HOC:

As @ambar mentioned in the comments, React-router has changed their code base since their V4. Here are the documentations - official, withRouter

import React, { Component } from 'react';
import { withRouter } from "react-router-dom";

class YourComponent extends Component {
    handleClick = () => {

    render() {
        return (
                <button onClick={this.handleClick} type="button">

export default withRouter(YourComponent);

3) React-router < V4 with browserHistory

You can achieve this functionality using react-router BrowserHistory. Code below:

import React, { Component } from 'react';
import { browserHistory } from 'react-router';

export default class YourComponent extends Component {
    handleClick = () => {

    render() {
        return (
                <button onClick={this.handleClick} type="button">

4) Redux connected-react-router

If you have connected your component with redux, and have configured connected-react-router all you have to do is this.props.history.push("/new/url"); ie, you don't need withRouter HOC to inject history to the component props.

// reducers.js
import { combineReducers } from 'redux';
import { connectRouter } from 'connected-react-router';

export default (history) => combineReducers({
    router: connectRouter(history),
    ... // rest of your reducers

// configureStore.js
import { createBrowserHistory } from 'history';
import { applyMiddleware, compose, createStore } from 'redux';
import { routerMiddleware } from 'connected-react-router';
import createRootReducer from './reducers';
export const history = createBrowserHistory();

export default function configureStore(preloadedState) {
    const store = createStore(
        createRootReducer(history), // root reducer with router state
                routerMiddleware(history), // for dispatching history actions
                // ... other middlewares ...

    return store;

// set up other redux requirements like for eg. in index.js
import { Provider } from 'react-redux';
import { Route, Switch } from 'react-router';
import { ConnectedRouter } from 'connected-react-router';
import configureStore, { history } from './configureStore';
const store = configureStore(/* provide initial state if any */)

    <Provider store={store}>
        <ConnectedRouter history={history}>
            <> { /* your usual react-router v4/v5 routing */ }
                    <Route exact path="/yourPath" component={YourComponent} />

// YourComponent.js
import React, { Component } from 'react';
import { connect } from 'react-redux';

class YourComponent extends Component {
    handleClick = () => {

    render() {
        return (
            <button onClick={this.handleClick} type="button">


export default connect(mapStateToProps = {}, mapDispatchToProps = {})(YourComponent);

ignoring any 'bin' directory on a git project

The .gitignore of your dream seems to be:


on the top level.

Is it possible to declare a public variable in vba and assign a default value?

Sure you know, but if its a constant then const MyVariable as Integer = 123 otherwise your out of luck; the variable must be assigned an initial value elsewhere.

You could:

public property get myIntegerThing() as integer
    myIntegerThing= 123
end property

In a Class module then globally create it;

public cMyStuff as new MyStuffClass

So cMyStuff.myIntegerThing is available immediately.

How to create an executable .exe file from a .m file

It used to be possible to compile Matlab to C with older versions of Matlab. Check out other tools that Matlab comes with.

Newest Matlab code can be exported as a Java's jar or a .Net Dll, etc. You can then write an executable against that library - it will be obfuscated by the way. The users will have to install a freely available Matlab Runtime.

Like others mentioned, mcc / mcc.exe is what you want to convert matlab code to C code.

Jackson Vs. Gson

I did this research the last week and I ended up with the same 2 libraries. As I'm using Spring 3 (that adopts Jackson in its default Json view 'JacksonJsonView') it was more natural for me to do the same. The 2 lib are pretty much the same... at the end they simply map to a json file! :)

Anyway as you said Jackson has a + in performance and that's very important for me. The project is also quite active as you can see from their web page and that's a very good sign as well.

How to get child element by ID in JavaScript?

Here is a pure JavaScript solution (without jQuery)

var _Utils = function ()
    this.findChildById = function (element, childID, isSearchInnerDescendant) // isSearchInnerDescendant <= true for search in inner childern 
        var retElement = null;
        var lstChildren = isSearchInnerDescendant ? Utils.getAllDescendant(element) : element.childNodes;

        for (var i = 0; i < lstChildren.length; i++)
            if (lstChildren[i].id == childID)
                retElement = lstChildren[i];

        return retElement;

    this.getAllDescendant = function (element, lstChildrenNodes)
        lstChildrenNodes = lstChildrenNodes ? lstChildrenNodes : [];

        var lstChildren = element.childNodes;

        for (var i = 0; i < lstChildren.length; i++) 
            if (lstChildren[i].nodeType == 1) // 1 is 'ELEMENT_NODE'
                lstChildrenNodes = Utils.getAllDescendant(lstChildren[i], lstChildrenNodes);

        return lstChildrenNodes;
var Utils = new _Utils;

Example of use:

var myDiv = document.createElement("div");
myDiv.innerHTML = "<table id='tableToolbar'>" +
                        "<tr>" +
                            "<td>" +
                                "<div id='divIdToSearch'>" +
                                "</div>" +
                            "</td>" +
                        "</tr>" +

var divToSearch = Utils.findChildById(myDiv, "divIdToSearch", true);

Why is conversion from string constant to 'char*' valid in C but invalid in C++

It's valid in C for historical reasons. C traditionally specified that the type of a string literal was char * rather than const char *, although it qualified it by saying that you're not actually allowed to modify it.

When you use a cast, you're essentially telling the compiler that you know better than the default type matching rules, and it makes the assignment OK.

How can I change the app display name build with Flutter?

UPDATE: From the comments this answer seems to be out of date

The Flutter documentation points out where you can change the display name of your application for both Android and iOS. This may be what you are looking for:

For Android

It seems you have already found this in the AndroidManifest.xml as the application entry.

Review the default App Manifest file AndroidManifest.xml located in /android/app/src/main/ and verify the values are correct, especially:

application: Edit the application tag to reflect the final name of the app.

For iOS

See the Review Xcode project settings section:

Navigate to your target’s settings in Xcode:

In Xcode, open Runner.xcworkspace in your app’s ios folder.

To view your app’s settings, select the Runner project in the Xcode project navigator. Then, in the main view sidebar, select the Runner target.

Select the General tab. Next, you’ll verify the most important settings:

Display Name: the name of the app to be displayed on the home screen and elsewhere.

How and where to use ::ng-deep?

Use ::ng-deep with caution. I used it throughout my app to set the material design toolbar color to different colors throughout my app only to find that when the app was in testing the toolbar colors step on each other. Come to find out it is because these styles becomes global, see this article Here is a working code solution that doesn't bleed into other components.

<mat-toolbar #subbar>

export class BypartSubBarComponent implements AfterViewInit {
  @ViewChild('subbar', { static: false }) subbar: MatToolbar;
    private renderer: Renderer2) { }
  ngAfterViewInit() {
      this.subbar._elementRef.nativeElement, 'backgroundColor', 'red');


What is the difference between "Class.forName()" and "Class.forName().newInstance()"?

Class.forName()-->forName() is the static method of Class class it returns Class class object used for reflection not user class object so you can only call Class class methods on it like getMethods(), getConstructors() etc.

If you care about only running static block of your(Runtime given) class and only getting information of methods,constructors,Modifier etc of your class you can do with this object which you get using Class.forName()

But if you want to access or call your class method (class which you have given at runtime) then you need to have its object so newInstance method of Class class do it for you.It create new instance of the class and return it to you .You just need to type-cast it to your class.

ex-: suppose Employee is your class then

Class a=Class.forName(args[0]); 

//args[0]=cmd line argument to give class at  runtime. 

Employee ob1=a.newInstance();

a.newInstance() is similar to creating object using new Employee().

now you can access all your class visible fields and methods.

How to use OKHTTP to make a post request?

You can make it like this:

    MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    RequestBody body = RequestBody.create(JSON, "{"jsonExample":"value"}");

    OkHttpClient client = new OkHttpClient();

    Request request = new Request.Builder()
            .addHeader("Authorization", "header value") //Notice this request has header if you don't need to send a header just erase this part

    Call call = client.newCall(request);

    call.enqueue(new Callback() {
        public void onFailure(Request request, IOException e) {

            Log.e("HttpService", "onFailure() Request was: " + request);


        public void onResponse(Response r) throws IOException {

            response = r.body().string();

            Log.e("response ", "onResponse(): " + response );


How to find the UpgradeCode and ProductCode of an installed application in Windows 7

If you have msi installer open it with Orca (tool from Microsoft), table Property (rows UpgradeCode, ProductCode, Product version etc) or table Upgrade column Upgrade Code.

Try to find instller via registry: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall find required subkey and watch value InstallSource. Maybe along the way you'll be able to find the MSI file.

NavigationBar bar, tint, and title text color in iOS 8

To do this job in storyboard (Interface Builder Inspector)

With help of IBDesignable, we can add more options to Interface Builder Inspector for UINavigationController and tweak them on storyboard. First, add the following code to your project.

@IBDesignable extension UINavigationController {
    @IBInspectable var barTintColor: UIColor? {
        set {
            navigationBar.barTintColor = newValue
        get {
            guard  let color = navigationBar.barTintColor else { return nil }
            return color

    @IBInspectable var tintColor: UIColor? {
        set {
            navigationBar.tintColor = newValue
        get {
            guard  let color = navigationBar.tintColor else { return nil }
            return color

    @IBInspectable var titleColor: UIColor? {
        set {
            guard let color = newValue else { return }
            navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: color]
        get {
            return navigationBar.titleTextAttributes?["NSForegroundColorAttributeName"] as? UIColor

Then simply set the attributes for UINavigationController on storyboard.

enter image description here

How to Add Incremental Numbers to a New Column Using Pandas

For a pandas DataFrame whose index starts at 0 and increments by 1 (i.e., the default values) you can just do:

df.insert(0, 'New_ID', df.index + 880)

if you want New_ID to be the first column. Otherwise this if you don't mind it being at the end:

df['New_ID'] = df.index + 880

Transparent background in JPEG image

JPEG can't support transparency because it uses RGB color space. If you want transparency use a format that supports alpha values. Example PNG is an image format that uses RGBA color space where (r = red, g = green, b = blue, a = alpha value). Alpha value is used as an opacity measure, 0% is fully transparent and 100% is completely opaque. pixel.

How to create a new figure in MATLAB?

While doing "figure(1), figure(2),..." will solve the problem in most cases, it will not solve them in all cases. Suppose you have a bunch of MATLAB figures on your desktop and how many you have open varies from time to time before you run your code. Using the answers provided, you will overwrite these figures, which you may not want. The easy workaround is to just use the command "figure" before you plot.

Example: you have five figures on your desktop from a previous script you ran and you use



You just plotted over the figures on your desktop. However the code



just created figures 6 and 7 with your desired plots and left your previous plots 1-5 alone.

copy db file with adb pull results in 'permission denied' error

This answer ended up working for me:

Backup to a file, pull the backup, and then convert it to a tarball and extract it.

adb backup  -f myAndroidBackup.ab  com.corp.appName

dd if=myAndroidBackup.ab bs=1 skip=24 | python -c "import zlib,sys;sys.stdout.write(zlib.decompress(" | tar -xvf - 

Disabling Minimize & Maximize On WinForm?

How to make form minimize when closing was already answered, but how to remove the minimize and maximize buttons wasn't.
FormBorderStyle: FixedDialog
MinimizeBox: false
MaximizeBox: false

How to convert CharSequence to String?

You can directly use String.valueOf()


Though this is same as toString() it does a null check on the charSequence before actually calling toString.

This is useful when a method can return either a charSequence or null value.

WPF: Create a dialog / prompt

Great answer of Josh, all credit to him, I slightly modified it to this however:

MyDialog Xaml

    <StackPanel Margin="5,5,5,5">
        <TextBlock Name="TitleTextBox" Margin="0,0,0,10" />
        <TextBox Name="InputTextBox" Padding="3,3,3,3" />
        <Grid Margin="0,10,0,0">
                <ColumnDefinition Width="*"/>
                <ColumnDefinition Width="*"/>
            <Button Name="BtnOk" Content="OK" Grid.Column="0" Margin="0,0,5,0" Padding="8" Click="BtnOk_Click" />
            <Button Name="BtnCancel" Content="Cancel" Grid.Column="1" Margin="5,0,0,0" Padding="8" Click="BtnCancel_Click" />

MyDialog Code Behind

    public MyDialog()

    public MyDialog(string title,string input)
        TitleText = title;
        InputText = input;

    public string TitleText
        get { return TitleTextBox.Text; }
        set { TitleTextBox.Text = value; }

    public string InputText
        get { return InputTextBox.Text; }
        set { InputTextBox.Text = value; }

    public bool Canceled { get; set; }

    private void BtnCancel_Click(object sender, System.Windows.RoutedEventArgs e)
        Canceled = true;

    private void BtnOk_Click(object sender, System.Windows.RoutedEventArgs e)
        Canceled = false;

And call it somewhere else

var dialog = new MyDialog("test", "hello");
dialog.Closing += (sender,e) =>
    var d = sender as MyDialog;

Prepend text to beginning of string

If you want to use the version of Javascript called ES 2015 (aka ES6) or later, you can use template strings introduced by ES 2015 and recommended by some guidelines (like Airbnb's style guide):

const after = "test";
const mystr = `This is: ${after}`;

Why does CreateProcess give error 193 (%1 is not a valid Win32 app)

Let me add an example here:

I'm trying to build Alluxio on windows platform and got the same issue, it's because the pom.xml contains below step:

            <id>Check that there are no Windows line endings</id>

The .sh file is not executable on windows so the error throws.

Comment it out if you do want build Alluxio on windows.

Gradle - Could not target platform: 'Java SE 8' using tool chain: 'JDK 7 (1.7)'

The following worked for me:

  1. Go to the top right corner of IntelliJ -> click the icon
  2. In the Project Structure window -> Select project -> In the Project SDK, choose the correct version -> Click Apply -> Click Okay

Centering image and text in R Markdown for a PDF report

The simple solution given by Jonathan works with a modification to cheat Pandoc. Instead of direct Latex commands such as


you can define your own commands in the YAML header:

- \newcommand{\bcenter}{\begin{center}}
- \newcommand{\ecenter}{\end{center}}

And then you use:

Text and more

This works for me for centering a whole document with many code chunks and markdown commands in between.

javascript code to check special characters

You could also do it this way.

specialRegex = /[^A-Z a-z0-9]/ specialRegex.test('test!') // evaluates to true Because if its not a capital letter, lowercase letter, number, or space, it could only be a special character

Loop through JSON in EJS

JSON.stringify returns a String. So, for example:

var data = [
    { id: 1, name: "bob" },
    { id: 2, name: "john" },
    { id: 3, name: "jake" },


will return the equivalent of:


as a String value.

So when you have

<% for(var i=0; i<JSON.stringify(data).length; i++) {%>

what that ends up looking like is:

<% for(var i=0; i<"[{\"id\":1,\"name\":\"bob\"},{\"id\":2,\"name\":\"john\"},{\"id\":3,\"name\":\"jake\"}]".length; i++) {%>

which is probably not what you want. What you probably do want is something like this:

<% for(var i=0; i < data.length; i++) { %>
     <td><%= data[i].id %></td>
     <td><%= data[i].name %></td>
<% } %>

This will output the following table (using the example data from above):


How to compare two JSON objects with the same elements in a different order equal?

Another way could be to use json.dumps(X, sort_keys=True) option:

import json
a, b = json.dumps(a, sort_keys=True), json.dumps(b, sort_keys=True)
a == b # a normal string comparison

This works for nested dictionaries and lists.

How to read a .properties file which contains keys that have a period character using Shell script


I have tried like this .Please review and update me whether it is right approach or not.

function pause(){
   read -p "$*"


if [ -f "$file" ]
    echo "$file found."

dbUser=`sed '/^\#/d' $file | grep 'db.uat.user'  | tail -n 1 | cut -d "=" -f2- | sed 's/^[[:space:]]*//;s/[[:space:]]*$//'`
dbPass=`sed '/^\#/d' $file | grep 'db.uat.passwd'  | tail -n 1 | cut -d "=" -f2- | sed 's/^[[:space:]]*//;s/[[:space:]]*$//'`

echo database user = $dbUser
echo database pass = $dbPass

    echo "$file not found."

Retrieving the COM class factory for component with CLSID {XXXX} failed due to the following error: 80040154

For anyone using VSTO, the problem for me was a missing reference to the office assembly. It would also appear if you were trying to instantiate certain VSTO objects manually.

Adding options to a <select> using jQuery?

Based on dule's answer for appending a collection of items, a one-liner will also work wonders:

let cities = {'ny':'New York','ld':'London','db':'Dubai','pk':'Beijing','tk':'Tokyo','nd':'New Delhi'};_x000D_
for(let c in cities){$('#selectCity').append($('<option>',{value: c,text: cities[c]}))}
<script src=""></script>_x000D_
<select  id="selectCity"></select>

Both object values and indexes are assigned to the options. This solution works even in the old jQuery (v1.4)!

Install Chrome extension form outside the Chrome Web Store

For Windows, you can also whitelist your extension through Windows policies. The full steps are details in this answer, but there are quicker steps:

  1. Create the registry key HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome\ExtensionInstallWhitelist.
  2. For each extension you want to whitelist, add a string value whose name should be a sequence number (starting at 1) and value is the extension ID.

For instance, in order to whitelist 2 extensions with ID aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa and bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb, create a string value with name 1 and value aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, and a second value with name 2 and value bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb. This can be sum up by this registry file:

Windows Registry Editor Version 5.00



EDIT: actually, Chromium docs also indicate how to do it for other OS.

Inserting Image Into BLOB Oracle 10g

You should do something like this:

1) create directory object what would point to server-side accessible folder

CREATE DIRECTORY image_files AS '/data/images'

2) Place your file into OS folder directory object points to

3) Give required access privileges to Oracle schema what will load data from file into table:

GRANT READ ON DIRECTORY image_files TO scott

4) Use BFILENAME, EMPTY_BLOB functions and DBMS_LOB package (example NOT tested - be care) like in below:

  l_blob BLOB; 
  v_src_loc  BFILE := BFILENAME('IMAGE_FILES', 'myimage.png');
  v_amount   INTEGER;
  INSERT INTO esignatures  
  VALUES (100, 'BOB', empty_blob()) RETURN iblob INTO l_blob; 
  v_amount := DBMS_LOB.GETLENGTH(v_src_loc);
  DBMS_LOB.LOADFROMFILE(l_blob, v_src_loc, v_amount);

After this you get the content of your file in BLOB column and can get it back using Java for example.

edit: One letter left missing: it should be LOADFROMFILE.

How do I update a GitHub forked repository?

As a complement to this answer, I was looking for a way to update all remote branches of my cloned repo (origin) from upstream branches in one go. This is how I did it.

This assumes you have already configured an upstream remote pointing at the source repository (where origin was forked from) and have synced it with git fetch upstream.

Then run:

for branch in $(git ls-remote --heads upstream|sed 's#^.*refs/heads/##'); do git push origin refs/remotes/upstream/$branch:refs/heads/$branch; done

The first part of this command lists all heads in the upstream remote repo and removes the SHA-1 followed by refs/heads/ branch name prefix.

Then for each of these branches, it pushes the local copy of the upstream remote tracking branch (refs/remotes/upstream/<branch> on local side) directly to the remote branch on origin (refs/heads/<branch> on remote side).

Any of these branch sync commands may fail for one of two reasons: either the upstream branch have been rewritten, or you have pushed commits on that branch to your fork. In the first case where you haven't committed anything to the branch on your fork it is safe to push forcefully (Add the -f switch; i.e. git push -f in the command above). In the other case this is normal as your fork branch have diverged and you can't expect the sync command to work until your commits have been merged back into upstream.

Javascript Src Path

Piece of cake!

<SCRIPT LANGUAGE="JavaScript" SRC="/clock.js"></SCRIPT>

How do you do a ‘Pause’ with PowerShell 2.0?

In addition to Michael Sorens' answer:

<6> ReadKey in a new process

Start-Process PowerShell {[void][System.Console]::ReadKey($true)} -Wait -NoNewWindow
  • Advantage: Accepts any key but properly excludes Shift, Alt, Ctrl modifier keys.
  • Advantage: Works in PS-ISE.


PYTHONPATH is an environment variable those content is added to the sys.path where Python looks for modules. You can set it to whatever you like.

However, do not mess with PYTHONPATH. More often than not, you are doing it wrong and it will only bring you trouble in the long run. For example, virtual environments could do strange things…

I would suggest you learned how to package a Python module properly, maybe using this easy setup. If you are especially lazy, you could use cookiecutter to do all the hard work for you.

When & why to use delegates?

A delegate is a simple class that is used to point to methods with a specific signature, becoming essentially a type-safe function pointer. A delegate's purpose is to facilitate a call back to another method (or methods), after one has been completed, in a structured way.

While it could be possible to create an extensive set of code to perform this functionality, you don’t need too. You can use a delegate.

Creating a delegate is easy to do. Identify the class as a delegate with the "delegate" keyword. Then specify the signature of the type.

CSS background-size: cover replacement for Mobile Safari

I've had this issue on a lot of mobile views I've recently built.

My solution is still a pure CSS Fallback as three great methods, the latter two are fall backs for when CSS3's cover doesn't work.


<img src="images/bg.jpg" id="bg" alt="">


#bg {
  position: fixed; 
  top: 0; 
  left: 0; 

  /* Preserve aspect ratio */
  min-width: 100%;
  min-height: 100%;

How Can I Truncate A String In jQuery?

  function truncateString(str, length) {
     return str.length > length ? str.substring(0, length - 3) + '...' : str

Export and Import all MySQL databases at one time

All the answers I see on this question can have problems with the character sets in some databases due to the problem of redirecting the exit of mysqldump to a file within the shell operator >.

To solve this problem you should do the backup with a command like this

mysqldump -u root -p --opt --all-databases -r backup.sql

To do a good BD restore without any problem with character sets. Obviously you can change the default-character-set as you need.

mysql -uroot -p --default-character-set=utf8
mysql> SET names 'utf8';
mysql> SOURCE backup.sql;

comparing strings in vb

If String.Compare(string1,string2,True) Then

    'perform operation


Change table header color using bootstrap

Try This:

table.table tr th{background-color:blue !important; font-color:white !important;}

hope this helps..

How to reliably open a file in the same directory as a Python script

To quote from the Python documentation:

As initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter. If the script directory is not available (e.g. if the interpreter is invoked interactively or if the script is read from standard input), path[0] is the empty string, which directs Python to search modules in the current directory first. Notice that the script directory is inserted before the entries inserted as a result of PYTHONPATH.

sys.path[0] is what you are looking for.

How Big can a Python List Get?

I'd say you're only limited by the total amount of RAM available. Obviously the larger the array the longer operations on it will take.

How to downgrade the installed version of 'pip' on windows?

pip itself is just a normal python package. Thus you can install pip with pip.

Of cource, you don't want to affect the system's pip, install it inside a virtualenv.

pip install pip==1.2.1

iPhone is not available. Please reconnect the device

Download the support file for the iOS version of your device from this link and follow the instructions.

Link to the GitHub

Uncaught TypeError: undefined is not a function on loading jquery-min.js

I had this problem recently with the jQuery Validation plug-in, using Squishit, also getting the js error:

"undefined is not a function"

I fixed it by changing the reference to the unminified jquery.validate.js file, rather than jquery.validate.min.js.

         ... more files

I think that the minified version of certain files, when further compressed using Squishit, for example, might in some cases not deal with missing semi-colons and the like, as @Dustin suggests, so you might have to experiment with which files you can doubly compress, and which you just leave to Squishit or whatever you're bundling with.

Why doesn't Java offer operator overloading?

Sometimes it would be nice to have operator overloading, friend classes and multiple inheritance.

However I still think it was a good decision. If Java would have had operator overloading then we could never be sure of operator meanings without looking through source code. At present that's not necessary. And I think your example of using methods instead of operator overloading is also quite readable. If you want to make things more clear you could always add a comment above hairy statements.

// a = b + c
Complex a, b, c; a = b.add(c);

Running Google Maps v2 on the Android emulator

I have already replied to this question in an answer to Stack Overflow question Trouble using Google sign-in button in emulator. It only works for Android 4.2.2, but lets you use the "Intel Atom (x86)" in AVD.

I think that it is easy to make it work for other versions of Android. Just find the correct files.

windows batch file rename

@echo off
pushd "pathToYourFolder" || exit /b
for /f "eol=: delims=" %%F in ('dir /b /a-d *_*.jpg') do (
  for /f "tokens=1* eol=_ delims=_" %%A in ("%%~nF") do ren "%%F" "%%~nB_%%A%%~xF"

Note: The name is split at the first occurrence of _. If a file is named "part1_part2_part3.jpg", then it will be renamed to "part2_part3_part1.jpg"

Clear text from textarea with selenium

It is general syntax

driver.find_element_by_id('Locator value').clear();
driver.find_element_by_name('Locator value').clear();

how to calculate binary search complexity

Here a more mathematical way of seeing it, though not really complicated. IMO much clearer as informal ones:

The question is, how many times can you divide N by 2 until you have 1? This is essentially saying, do a binary search (half the elements) until you found it. In a formula this would be this:

1 = N / 2x

multiply by 2x:

2x = N

now do the log2:

log2(2x)    = log2 N
x * log2(2) = log2 N
x * 1         = log2 N

this means you can divide log N times until you have everything divided. Which means you have to divide log N ("do the binary search step") until you found your element.

How to save traceback / sys.exc_info() values in a variable?

The object can be used as a parameter in Exception.with_traceback() function:

except Exception as e:
    tb = sys.exc_info()

Large WCF web service request failing with (400) HTTP Bad Request

For what it is worth, an additional consideration when using .NET 4.0 is that if a valid endpoint is not found in your configuration, a default endpoint will be automatically created and used.

The default endpoint will use all default values so if you think you have a valid service configuration with a large value for maxReceivedMessageSize etc., but there is something wrong with the configuration, you would still get the 400 Bad Request since a default endpoint would be created and used.

This is done silently so it is hard to detect. You will see messages to this effect (e.g. 'No Endpoint found for Service, creating Default Endpoint' or similar) if you turn on tracing on the server but there is no other indication (to my knowledge).

Python urllib2: Receive JSON response from url

Though I guess it has already answered I would like to add my little bit in this

import json
import urllib2
class Website(object):
    def __init__(self,name): = name 
    def dump(self): urllib2.urlopen(

    def convJSON(self):
         data=  json.load(self.dump())
     print data

domain = Website("")

Note : object passed to json.load() should support .read() , therefore urllib2.urlopen( would not work . Doamin passed should be provided with protocol in this case http

Multiline text in JLabel

Type the content (i.e., the "text" property field) inside a <html></html> tag. So you can use <br> or<P> to insert a newline.

For example:

String labelContent = "<html>Twinkle, twinkle, little star,<BR>How I wonder what you are.<BR>Up above the world so high,<BR>Like a diamond in the sky.</html>";

It will display as follows:

Twinkle, twinkle, little star,
How I wonder what you are.
Up above the world so high,
Like a diamond in the sky.

Where is the visual studio HTML Designer?

The default HTML editor (for static HTML) doesn't have a design view. To set the default editor to the Web forms editor which does have a design view,

  1. Right click any HTML file in the Solution Explorer in Visual Studio and click on Open with
  2. Select the HTML (web forms) editor
  3. Click on Set as default
  4. Click on the OK button

Once you have done that, all you need to do is click on design or split view as shown below:

Screenshot showing the location of said options

Finding all positions of substring in a larger string in C#

It could be done in efficient time complexity using KMP algorithm in O(N + M) where N is the length of text and M is the length of the pattern.

This is the implementation and usage:

static class StringExtensions
    public static IEnumerable<int> AllIndicesOf(this string text, string pattern)
        if (string.IsNullOrEmpty(pattern))
            throw new ArgumentNullException(nameof(pattern));
        return Kmp(text, pattern);

    private static IEnumerable<int> Kmp(string text, string pattern)
        int M = pattern.Length;
        int N = text.Length;

        int[] lps = LongestPrefixSuffix(pattern);
        int i = 0, j = 0; 

        while (i < N)
            if (pattern[j] == text[i])
            if (j == M)
                yield return i - j;
                j = lps[j - 1];

            else if (i < N && pattern[j] != text[i])
                if (j != 0)
                    j = lps[j - 1];

    private static int[] LongestPrefixSuffix(string pattern)
        int[] lps = new int[pattern.Length];
        int length = 0;
        int i = 1;

        while (i < pattern.Length)
            if (pattern[i] == pattern[length])
                lps[i] = length;
                if (length != 0)
                    length = lps[length - 1];
                    lps[i] = length;
        return lps;

and this is an example of how to use it:

static void Main(string[] args)
        string text = "this is a test";
        string pattern = "is";
        foreach (var index in text.AllIndicesOf(pattern))
            Console.WriteLine(index); // 2 5

How do I set up a private Git repository on GitHub? Is it even possible?

On January 7th 2019, GitHub announced free and unlimited private repositories for all GitHub users, paying or not. When creating a new repository, you can simply select the Private option.

How to edit default dark theme for Visual Studio Code?

As far as the themes, VS Code is every bit as editable as Sublime. You can edit any of the default themes that come with VS code. You just have to know where to find the theme files.

Side note: I love the Monokai theme. However, all I wanted to change about it was the background. I don't like the dark grayish background. Instead, I think the contrast is WAY better with a solid black background. The code pops out much more.

Anyways, I hunted for the theme file and found it (in windows) at:

c:\Program Files (x86)\Microsoft VS Code\resources\app\extensions\theme-monokai\themes\

In that folder I found the Monokai.tmTheme file and modified the first background key as follows:


There are a few 'background' key in the theme file, make sure you edit the correct one. The one I edited was at the very top. Line 12 I think.

How to compile Go program consisting of multiple files?

Yup! That's very straight forward and that's where the package strategy comes into play. there are three ways to my knowledge. folder structure:

GOPATH/src/ abc/ myproject/ adapter/ main.go pkg1 pkg2 warning: adapter can contain package main only and sun directories

  1. navigate to "adapter" folder. Run:
    go build main.go
  1. navigate to "adapter" folder. Run:
    go build main.go
  1. navigate to GOPATH/src recognize relative path to package main, here "myproject/adapter". Run:
    go build myproject/adapter

exe file will be created at the directory you are currently at.

How to reset (clear) form through JavaScript?

Try this :

$('#resetBtn').on('click', function(e){

How to access static resources when mapping a global front controller servlet on /*

Add the folders which you don't want to trigger servlet processing to the <static-files> section of your appengine-web.xml file.

I just did this and looks like things are starting to work ok. Here's my structure:


/pages/<.jsp files>


I added "/pages/**" and "/css/**" to the <static-files> section and I can now forward to a .jsp file from inside a servlet doGet without causing an infinite loop.

npm start error with create-react-app

As Dan said correctly,

If you see this:

npm ERR! [email protected] start: `react-scripts start`
npm ERR! spawn ENOENT

It just means something went wrong when dependencies were installed the first time.

But I got something slightly different because running npm install -g npm@latest to update npm might sometimes leave you with this error:

npm ERR! code ETARGET
npm ERR! notarget No matching version found for npm@lates
npm ERR! notarget In most cases you or one of your dependencies are requesting
npm ERR! notarget a package version that doesn't exist.

so, instead of running npm install -g npm@latest, I suggest running the below steps:

 npm i -g npm //which will also update npm
 rm -rf node_modules/ && npm cache clean // to remove the existing modules and clean the cache.
 npm install //to re-install the project dependencies.

This should get you back on your feet.

MySQL Results as comma separated list

In my case i have to concatenate all the account number of a person who's mobile number is unique. So i have used the following query to achieve that.

SELECT GROUP_CONCAT(AccountsNo) as Accounts FROM `tblaccounts` GROUP BY MobileNumber

Query Result is below:


accessing a file using [NSBundle mainBundle] pathForResource: ofType:inDirectory:

Are you attempting to do this inside of an XCTest and on the verge of smashing your laptop? This is the thread for you: Why can't code inside unit tests find bundle resources?

List of standard lengths for database fields

Just looking though my email archives, there are a number of pretty long "first" names (of course what is meant by first is variable by culture). One example is Krishnamurthy - which is 13 letters long. A good guess might be 20 to 25 letters based on this. Email should be much longer since you might have [email protected]. Also, gmail and some other mail programs allow you to use [email protected] where "sometag" is anything you want to put there so that you can use it to sort incoming emails. I frequently run into web forms that don't allow me to put in my full email address without considering any tags. So, if you need a fixed email field maybe something like [email protected] in characters for a total of 90 characters (if I did my math right!).

RadioGroup: How to check programmatically

In your layout you can add android:checked="true" to CheckBox you want to be selected.

Or programmatically, you can use the setChecked method defined in the checkable interface:

RadioButton b = (RadioButton) findViewById(; b.setChecked(true);

How to connect to MySQL Database?

You must to download MySQLConnection NET from here.

Then you need add MySql.Data.DLL to MSVisualStudio like this:

  1. Open menu project
  2. Add
  3. Reference
  4. Browse to C:\Program Files (x86)\MySQL\MySQL Connector Net 8.0.12\Assemblies\v4.5.2
  5. Add MySql.Data.dll

If you want to know more visit: enter link description here

To use in the code you must import the library:

using MySql.Data.MySqlClient;

An example with connectio to Mysql database (NO SSL MODE) by means of Click event:

using System;
using System.Windows;
using MySql.Data.MySqlClient;

namespace Deportes_WPF

public partial class Login : Window
    private MySqlConnection connection;
    private string server;
    private string database;
    private string user;
    private string password;
    private string port;
    private string connectionString;
    private string sslM;

    public Login()

        server = "server_name";
        database = "database_name";
        user = "user_id";
        password = "password";
        port = "3306";
        sslM = "none";

        connectionString = String.Format("server={0};port={1};user id={2}; password={3}; database={4}; SslMode={5}", server, port, user, password, database, sslM);

        connection = new MySqlConnection(connectionString);

    private void conexion()

            MessageBox.Show("successful connection");

        catch (MySqlException ex)
            MessageBox.Show(ex.Message + connectionString);

    private void btn1_Click(object sender, RoutedEventArgs e)


How do you compare two version Strings in Java?

Using Java 8 Stream to replace leading zeroes in components. This code passed all tests on

public int compareVersion(String A, String B) {
    List<String> strList1 ="\\."))
                                           .map(s -> s.replaceAll("^0+(?!$)", ""))
    List<String> strList2 ="\\."))
                                           .map(s -> s.replaceAll("^0+(?!$)", ""))
    int len1 = strList1.size();
    int len2 = strList2.size();
    int i = 0;
    while(i < len1 && i < len2){
        if (strList1.get(i).length() > strList2.get(i).length()) return 1;
        if (strList1.get(i).length() < strList2.get(i).length()) return -1;
        int result = new Long(strList1.get(i)).compareTo(new Long(strList2.get(i)));
        if (result != 0) return result;
    while (i < len1){
        if (!strList1.get(i++).equals("0")) return 1;
    while (i < len2){
        if (!strList2.get(i++).equals("0")) return -1;
    return 0;

Parse JSON from HttpURLConnection object

This function will be used get the data from url in form of HttpResponse object.

public HttpResponse getRespose(String url, String your_auth_code){
HttpClient client = new DefaultHttpClient();
HttpPost postForGetMethod = new HttpPost(url);
postForGetMethod.addHeader("Content-type", "Application/JSON");
postForGetMethod.addHeader("Authorization", your_auth_code);
return client.execute(postForGetMethod);

Above function is called here and we receive a String form of the json using the Apache library Class.And in following statements we try to make simple pojo out of the json we received.

String jsonString     =     
EntityUtils.toString(getResponse("    blah","Your_auth_if_you_need_one").getEntity(), "UTF-8");
final GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(JsonJavaModel .class, new    CustomJsonDeserialiser());
final Gson gson = gsonBuilder.create();
JsonElement json = new JsonParser().parse(jsonString);
JsonJavaModel pojoModel = gson.fromJson(
                    jsonElementForJavaObject, JsonJavaModel.class);

This is a simple java model class for incomming json. public class JsonJavaModel{ String content; String title; } This is a custom deserialiser:

public class CustomJsonDeserialiserimplements JsonDeserializer<JsonJavaModel>         {

public JsonJavaModel deserialize(JsonElement json, Type type,
                                 JsonDeserializationContext arg2) throws    JsonParseException {
    final JsonJavaModel jsonJavaModel= new JsonJavaModel();
    JsonObject object = json.getAsJsonObject();

    try {
     jsonJavaModel.content = object.get("Content").getAsString()
     jsonJavaModel.title = object.get("Title").getAsString()

    } catch (Exception e) {

    return jsonJavaModel;

Include Gson library and org.apache.http.util.EntityUtils;

Add custom message to thrown exception while maintaining stack trace in Java

Following code is a simple example that worked for me.Let me call the function main as parent function and divide as child function.
Basically i am throwing a new exception with my custom message (for the parent's call) if an exception occurs in child function by catching the Exception in the child first.

class Main {
    public static void main(String args[]) {
            long ans=divide(0);
        catch(Exception e){
            System.out.println("got exception:"+e.getMessage());


    public static long divide(int num) throws Exception{
        long x=-1;
        try {
        catch (Exception e){
            throw new Exception("Error occured in divide for number:"+num+"Error:"+e.getMessage());
        return x;

the last line return x will not run if error occurs somewhere in between.

How to get a DOM Element from a JQuery Selector

If you need to interact directly with the DOM element, why not just use document.getElementById since, if you are trying to interact with a specific element you will probably know the id, as assuming that the classname is on only one element or some other option tends to be risky.

But, I tend to agree with the others, that in most cases you should learn to do what you need using what jQuery gives you, as it is very flexible.

UPDATE: Based on a comment: Here is a post with a nice explanation:[email protected]/msg04461.html

$(this).attr("checked") ? $(this).val() : 0

This will return the value if it's checked, or 0 if it's not.

$(this).val() is just reaching into the dom and getting the attribute "value" of the element, whether or not it's checked.

How to rotate x-axis tick labels in Pandas barplot

The question is clear but the title is not as precise as it could be. My answer is for those who came looking to change the axis label, as opposed to the tick labels, which is what the accepted answer is about. (The title has now been corrected).

for ax in plt.gcf().axes:
    plt.xlabel(ax.get_xlabel(), rotation=90)

How to center a Window in Java?

The order of the calls is important:

first -


second -


Python Hexadecimal

Another solution is:

>>> "".join(list(hex(255))[2:])

Probably an archaic answer, but functional.

Android Studio Gradle Configuration with name 'default' not found

One other potential cause of this precise error: I found this error was resolved by commenting some unused libraries in build.gradle dependencies section. Make sure these paths and such are all correct.

I'd look real close at your compile project(':android-ColorPickerPreference') entry in the build.gradle - try commenting out the related code and this line in build.gradle and see if that compiles - then go from there resolving the path or library issue.

How to get the changes on a branch in Git

This is similar to the answer I posted on: Preview a Git push

Drop these functions into your Bash profile:

  • gbout - git branch outgoing
  • gbin - git branch incoming

You can use this like:

  • If on master: gbin branch1 <-- this will show you what's in branch1 and not in master
  • If on master: gbout branch1 <-- this will show you what's in master that's not in branch 1

This will work with any branch.

function parse_git_branch {
  git branch --no-color 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/\1/'

function gbin {
    echo branch \($1\) has these commits and \($(parse_git_branch)\) does not
    git log ..$1 --no-merges --format='%h | Author:%an | Date:%ad | %s' --date=local

function gbout {
    echo branch \($(parse_git_branch)\) has these commits and \($1\) does not
    git log $1.. --no-merges --format='%h | Author:%an | Date:%ad | %s' --date=local

Date format Mapping to JSON Jackson

Since Jackson v2.0, you can use @JsonFormat annotation directly on Object members;

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm a z")
private Date date;

Properties order in Margin

<object Margin="left,top,right,bottom"/>
- or - 
<object Margin="left,top"/>
- or - 
<object Margin="thicknessReference"/>

See here: