Programs & Examples On #Xmp

The Adobe Extensible Metadata Platform (XMP) is a standard, created by Adobe Systems Inc., for processing and storing standardized and proprietary information relating to the contents of a file.

Getting Image from API in Angular 4/5+?

angular 5 :

 getImage(id: string): Observable<Blob> {
    return this.httpClient.get('http://myip/image/'+id, {responseType: "blob"});

How to programmatically set the SSLContext of a JAX-WS client?

This one was a hard nut to crack, so for the record:

To solve this, it required a custom KeyManager and a SSLSocketFactory that uses this custom KeyManager to access the separated KeyStore. I found the base code for this KeyStore and SSLFactory on this excellent blog entry: how-to-dynamically-select-a-certificate-alias-when-invoking-web-services

Then, the specialized SSLSocketFactory needs to be inserted into the WebService context:

service = getWebServicePort(getWSDLLocation());
BindingProvider bindingProvider = (BindingProvider) service; 
bindingProvider.getRequestContext().put("", getCustomSocketFactory()); 

Where the getCustomSocketFactory() returns a SSLSocketFactory created using the method mentioned above. This would only work for JAX-WS RI from the Sun-Oracle impl built into the JDK, given that the string indicating the SSLSocketFactory property is proprietary for this implementation.

At this stage, the JAX-WS service communication is secured through SSL, but if you are loading the WSDL from the same secure server () then you'll have a bootstrap problem, as the HTTPS request to gather the WSDL will not be using the same credentials than the Web Service. I worked around this problem by making the WSDL locally available (file:///...) and dynamically changing the web service endpoint: (a good discussion on why this is needed can be found in this forum)

bindingProvider.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, webServiceLocation); 

Now the WebService gets bootstrapped and is able to communicate through SSL with the server counterpart using a named (alias) Client-Certificate and mutual authentication. ?

How to convert a .eps file to a high quality 1024x1024 .jpg?

For vector graphics, ImageMagick has both a render resolution and an output size that are independent of each other.

Try something like

convert -density 300 image.eps -resize 1024x1024 image.jpg

Which will render your eps at 300dpi. If 300 * width > 1024, then it will be sharp. If you render it too high though, you waste a lot of memory drawing a really high-res graphic only to down sample it again. I don't currently know of a good way to render it at the "right" resolution in one IM command.

The order of the arguments matters! The -density X argument needs to go before image.eps because you want to affect the resolution that the input file is rendered at.

This is not super obvious in the manpage for convert, but is hinted at:


convert [input-option] input-file [output-option] output-file

Position absolute and overflow hidden

An absolutely positioned element is actually positioned regarding a relative parent, or the nearest found relative parent. So the element with overflow: hidden should be between relative and absolute positioned elements:

<div class="relative-parent">
  <div class="hiding-parent">
    <div class="child"></div>

.relative-parent {
.hiding-parent {
.child {

Which port(s) does XMPP use?

According to Wikipedia:

5222 TCP     XMPP client connection (RFC 6120)        Official  
5223 TCP     XMPP client connection over SSL          Unofficial
5269 TCP     XMPP server connection (RFC 6120)        Official
5298 TCP UDP XMPP JEP-0174: Link-Local Messaging /    Official
             XEP-0174: Serverless Messaging
8010 TCP     XMPP File transfers                      Unofficial    

The port numbers are defined in RFC 6120 § 14.7.

How to Load RSA Private Key From File

Two things. First, you must base64 decode the mykey.pem file yourself. Second, the openssl private key format is specified in PKCS#1 as the RSAPrivateKey ASN.1 structure. It is not compatible with java's PKCS8EncodedKeySpec, which is based on the SubjectPublicKeyInfo ASN.1 structure. If you are willing to use the bouncycastle library you can use a few classes in the bouncycastle provider and bouncycastle PKIX libraries to make quick work of this.


import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMKeyPair;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;

// ...   

String keyPath = "mykey.pem";
BufferedReader br = new BufferedReader(new FileReader(keyPath));
Security.addProvider(new BouncyCastleProvider());
PEMParser pp = new PEMParser(br);
PEMKeyPair pemKeyPair = (PEMKeyPair) pp.readObject();
KeyPair kp = new JcaPEMKeyConverter().getKeyPair(pemKeyPair);
samlResponse.sign(Signature.getInstance("SHA1withRSA").toString(), kp.getPrivate(), certs);

Is there a WebSocket client implemented for Python?

Ridiculously easy to use.

 sudo pip install websocket-client

Sample client code:


from websocket import create_connection
ws = create_connection("ws://localhost:8080/websocket")
print "Sending 'Hello, World'..."
ws.send("Hello, World")
print "Sent"
print "Receiving..."
result =  ws.recv()
print "Received '%s'" % result

Sample server code:

import websocket
import thread
import time

def on_message(ws, message):
    print message

def on_error(ws, error):
    print error

def on_close(ws):
    print "### closed ###"

def on_open(ws):
    def run(*args):
        for i in range(30000):
            ws.send("Hello %d" % i)
        print "thread terminating..."
    thread.start_new_thread(run, ())

if __name__ == "__main__":
    ws = websocket.WebSocketApp("ws://",
                                on_message = on_message,
                                on_error = on_error,
                                on_close = on_close)
    ws.on_open = on_open


What is the ellipsis (...) for in this method signature?

It means that the method accepts a variable number of arguments ("varargs") of type JID. Within the method, recipientJids is presented.

This is handy for cases where you've a method that can optionally handle more than one argument in a natural way, and allows you to write calls which can pass one, two or three parameters to the same method, without having the ugliness of creating an array on the fly.

It also enables idioms such as sprintf from C; see String.format(), for example.

Preventing multiple clicks on button

Disable pointer events in the first line of your callback, and then resume them on the last line.

element.on('click', function() {
  element.css('pointer-events', 'none'); 
  //do all of your stuff
  element.css('pointer-events', 'auto');   

Get commit list between tags in git

If your team uses descriptive commit messages (eg. "Ticket #12345 - Update dependencies") on this project, then generating changelog since the latest tag can de done like this:

git log --no-merges --pretty=format:"%s" 'old-tag^' > /path/to/
  • --no-merges omits the merge commits from the list
  • old-tag^ refers to the previous commit earlier than the tagged one. Useful if you want to see the tagged commit at the bottom of the list by any reason. (Single quotes needed only for iTerm on mac OS).

What is mutex and semaphore in Java ? What is the main difference?

Unfortunately everyone has missed the most important difference between the semaphore and the mutex; the concept of "ownership".

Semaphores have no notion of ownership, this means that any thread can release a semaphore (this can lead to many problems in itself but can help with "death detection"). Whereas a mutex does have the concept of ownership (i.e. you can only release a mutex you have acquired).
Ownership is incredibly important for safe programming of concurrent systems. I would always recommend using mutex in preference to a semaphore (but there are performance implications).

Mutexes also may support priority inheritance (which can help with the priority inversion problem) and recursion (eliminating one type of deadlock).

It should also be pointed out that there are "binary" semaphores and "counting/general" semaphores. Java's semaphore is a counting semaphore and thus allows it to be initialized with a value greater than one (whereas, as pointed out, a mutex can only a conceptual count of one). The usefulness of this has been pointed out in other posts.

So to summarize, unless you have multiple resources to manage, I would always recommend the mutex over the semaphore.

CSS display:table-row does not expand when width is set to 100%

If you're using display:table-row etc., then you need proper markup, which includes a containing table. Without it your original question basically provides the equivalent bad markup of:

<tr style="width:100%">
    <td style="float:right">Name</td>

Where's the table in the above? You can't just have a row out of nowhere (tr must be contained in either table, thead, tbody, etc.)

Instead, add an outer element with display:table, put the 100% width on the containing element. The two inside cells will automatically go 50/50 and align the text right on the second cell. Forget floats with table elements. It'll cause so many headaches.


<div class="view-table">
    <div class="view-row">
        <div class="view-type">Type</div>
        <div class="view-name">Name</div>                


.view-row > div
    display: table-cell;

Get all inherited classes of an abstract class

This is such a common problem, especially in GUI applications, that I'm surprised there isn't a BCL class to do this out of the box. Here's how I do it.

public static class ReflectiveEnumerator
    static ReflectiveEnumerator() { }

    public static IEnumerable<T> GetEnumerableOfType<T>(params object[] constructorArgs) where T : class, IComparable<T>
        List<T> objects = new List<T>();
        foreach (Type type in 
            .Where(myType => myType.IsClass && !myType.IsAbstract && myType.IsSubclassOf(typeof(T))))
            objects.Add((T)Activator.CreateInstance(type, constructorArgs));
        return objects;

A few notes:

  • Don't worry about the "cost" of this operation - you're only going to be doing it once (hopefully) and even then it's not as slow as you'd think.
  • You need to use Assembly.GetAssembly(typeof(T)) because your base class might be in a different assembly.
  • You need to use the criteria type.IsClass and !type.IsAbstract because it'll throw an exception if you try to instantiate an interface or abstract class.
  • I like forcing the enumerated classes to implement IComparable so that they can be sorted.
  • Your child classes must have identical constructor signatures, otherwise it'll throw an exception. This typically isn't a problem for me.

babel-loader jsx SyntaxError: Unexpected token

Since the answer above still leaves some people in the dark, here's what a complete webpack.config.js might look like:

var path = require('path');_x000D_
var config = {_x000D_
    entry: path.resolve(__dirname, 'app/main.js'),_x000D_
    output: {_x000D_
        path: path.resolve(__dirname, 'build'),_x000D_
        filename: 'bundle.js'_x000D_
    module: {_x000D_
        loaders: [{_x000D_
            test: /\.jsx?$/,_x000D_
            loader: 'babel',_x000D_
                presets:['es2015', 'react']_x000D_
module.exports = config;

How to make java delay for a few seconds?

Use Thread.sleep(2000); //2000 for 2 seconds

Create Setup/MSI installer in Visual Studio 2017

Other answers posted here for this question did not work for me using the latest Visual Studio 2017 Enterprise edition (as of 2018-09-18).

Instead, I used this method:

  1. Close all but one instance of Visual Studio.
  2. In the running instance, access the menu Tools->Extensions and Updates.
  3. In that dialog, choose Online->Visual Studio Marketplace->Tools->Setup & Deployment.
  4. From the list that appears, select Microsoft Visual Studio 2017 Installer Projects.

Once installed, close and restart Visual Studio. Go to File->New Project and search for the word Installer. You'll know you have the correct templates installed if you see a list that looks something like this:

enter image description here

How to pass a null variable to a SQL Stored Procedure from code

    SQLParam = cmd.Parameters.Add("@RetailerID", SqlDbType.Int, 4)
    If p_RetailerID.Length = 0 Or p_RetailerID = "0" Then
        SQLParam.Value = DBNull.Value
        SQLParam.Value = p_RetailerID
    End If

Unit tests vs Functional tests


To answer the question: Unit Testing is a subtype of Functional Testing.

There are two big groups: Functional and Non-Functional Testing. The best (non-exhaustive) illustration that I found is this one (source:

enter image description here

(1) Unit Testing: testing of small snippets of code (functions/methods). It may be considered as (white-box) functional testing.

When functions are put together, you create a module = a standalone piece, possibly with a User Interface that can be tested (Module Testing). Once you have at least two separate modules, then you glue them together and then comes:

(2) Integration Testing: when you put two or more pieces of (sub)modules or (sub)systems together and see if they play nicely together.

Then you integrate the 3rd module, then the 4th and 5th in whatever order you or your team see fit, and once all the jigsaw pieces are placed together, comes

(3) System Testing: testing SW as a whole. This is pretty much "Integration testing of all pieces together".

If that's OK, then comes

(4) Acceptance Testing: did we build what the customer asked for actually? Of course, Acceptance Testing should be done throughout the lifecycle, not just at the last stage, where you realise that the customer wanted a sportscar and you built a van.

enter image description here

Java NIO: What does IOException: Broken pipe mean?

You should assume the socket was closed on the other end. Wrap your code with a try catch block for IOException.

You can use isConnected() to determine if the SocketChannel is connected or not, but that might change before your write() invocation finishes. Try calling it in your catch block to see if in fact this is why you are getting the IOException.

How to read and write into file using JavaScript?

In the context of browser, Javascript can READ user-specified file. See Eric Bidelman's blog for detail about reading file using File API. However, it is not possible for browser-based Javascript to WRITE the file system of local computer without disabling some security settings because it is regarded as a security threat for any website to change your local file system arbitrarily.

Saying that, there are some ways to work around it depending what you are trying to do:

  1. If it is your own site, you can embed a Java Applet in the web page. However, the visitor has to install Java on local machine and will be alerted about the security risk. The visitor has to allow the applet to be loaded. An Java Applet is like an executable software that has complete access to the local computer.

  2. Chrome supports a file system which is a sandboxed portion of the local file system. See this page for details. This provides possibly for you to temporarily save things locally. However, this is not supported by other browsers.

  3. If you are not limited to browser, Node.js has a complete file system interface. See here for its file system documentation. Note that Node.js can run not only on servers, but also any client computer including windows. The javascript test runner Karma is based on Node.js. If you just like to program in javascript on the local computer, this is an option.

PHP: Split string into array, like explode with no delimiter

Try this:

$str = '123456789';
$char_array = preg_split('//', $str, -1, PREG_SPLIT_NO_EMPTY);

What is the best way to initialize a JavaScript Date to midnight?

Adding usefulness to @Dan's example, I had the need to find the next midday or midnight.

var d = new Date();
if(d.getHours() < 12) {
   d.setHours(12,0,0,0); // next midnight/midday is midday
} else {
   d.setHours(24,0,0,0); // next midnight/midday is midnight

This allowed me to set a frequency cap for an event, only allowing it to happen once in the morning and once in the afternoon for any visitor to my site. The date captured was used to set the expiration of the cookie.

Initialise numpy array of unknown length

Build a Python list and convert that to a Numpy array. That takes amortized O(1) time per append + O(n) for the conversion to array, for a total of O(n).

    a = []
    for x in y:
    a = np.array(a)

How to kill all processes matching a name?

try kill -s 9 `ps -ef |grep "Nov 11" |grep -v grep | awk '{print $2}'` To kill processes of November 11 or kill -s 9 `ps -ef |grep amarok|grep -v grep | awk '{print $2}'` To kill processes that contain the word amarok

Angular2 use [(ngModel)] with [ngModelOptions]="{standalone: true}" to link to a reference to model's property

Using @angular/forms when you use a <form> tag it automatically creates a FormGroup.

For every contained ngModel tagged <input> it will create a FormControl and add it into the FormGroup created above; this FormControl will be named into the FormGroup using attribute name.


<form #f="ngForm">
    <input type="text" [(ngModel)]="firstFieldVariable" name="firstField">
    <span>{{ f.controls['firstField']?.value }}</span>

Said this, the answer to your question follows.

When you mark it as standalone: true this will not happen (it will not be added to the FormGroup).


Git: add vs push vs commit

I find this image very meaningful :

enter image description here

(from : Oliver Steele -My Git Workflow (2008) )

Populate a Drop down box from a mySQL table in PHP

Below is the code for drop down using MySql and PHP:

$sql="Select PcID from PC"
echo "<select name=\"pcid\">"; 
echo "<option size =30 ></option>";
while($row = mysql_fetch_array($q)) 
echo "<option value='".$row['PcID']."'>".$row['PcID']."</option>"; 
echo "</select>";

PHP Call to undefined function

Please check that you have <?PHP at the top of your code. If you forget it, this error will appear.

how to install apk application from my pc to my mobile android

C:\Program Files (x86)\LG Electronics\LG PC Suite\adb>adb install com.lge.filemanager-15052-v3.1.15052.apk
* daemon not running. starting it now on port 5037 *
* daemon started successfully *
2683 KB/s (3159508 bytes in 1.150s)
pkg: /data/local/tmp/com.lge.filemanager-15052-v3.1.15052.apk

C:\Program Files (x86)\LG Electronics\LG PC Suite\adb>

We can use the adb.exe which is there in PC suit, it worked for me. Thanks Chethan

SQL Server command line backup statement

Seba Illingworth's code, In case you need time in your file name (it gives 2014-02-21_1035)

echo off
set /p DATABASENAME=Enter database name:
For /f "tokens=2-4 delims=/ " %%a in ('date /t') do (set mydate=%%c-%%a-%%b)
For /f "tokens=1-2 delims=/:" %%a in ("%TIME%") do (set mytime=%%a%%b)

:: filename format Name-Date (eg MyDatabase-2009.5.19.bak)
set DATESTAMP=%mydate%_%mytime%


What's the right way to pass form element state to sibling/parent elements?

The first solution, with keeping the state in parent component, is the correct one. However, for more complex problems, you should think about some state management library, redux is the most popular one used with react.

Get filename and path from URI from mediastore

Just a simple update on the first answer: mActivity.managedQuery() is now deprecated. I've updated the code with the new method.

private String getRealPathFromURI(Uri contentUri) {
    String[] proj = { MediaStore.Images.Media.DATA };
    CursorLoader loader = new CursorLoader(mContext, contentUri, proj, null, null, null);
    Cursor cursor = loader.loadInBackground();
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    String result = cursor.getString(column_index);
    return result;

android dev source

java.util.Date format conversion yyyy-mm-dd to mm-dd-yyyy


instead of


because MM points Month, mm points minutes

SimpleDateFormat sm = new SimpleDateFormat("MM-dd-yyyy");
String strDate = sm.format(myDate);

how to attach url link to an image?


<style type="text/css">
#example {
    display: block;
    width: 30px;
    height: 10px;
    background: url(../images/example.png) no-repeat;
    text-indent: -9999px;

<a href="" id="example">See an example!</a>

More wordy, but it may benefit SEO, and it will look like nice simple text with CSS disabled.

JUnit test for System.out.println()

Slightly off topic, but in case some people (like me, when I first found this thread) might be interested in capturing log output via SLF4J, commons-testing's JUnit @Rule might help:

public class FooTest {
    public final ExpectedLogs logs = new ExpectedLogs() {{
        captureFor(Foo.class, LogLevel.WARN);

    public void barShouldLogWarning() {
        assertThat(logs.isEmpty(), is(true)); // Nothing captured yet.

        // Logic using the class you are capturing logs for:
        Foo foo = new Foo();
        assertThat(, is(not(nullValue())));

        // Assert content of the captured logs:
        assertThat(logs.isEmpty(), is(false));
        assertThat(logs.contains("Your warning message here"), is(true));


  • I developed this library since I could not find any suitable solution for my own needs.
  • Only bindings for log4j, log4j2 and logback are available at the moment, but I am happy to add more.

Create SQLite Database and table

The next link will bring you to a great tutorial, that helped me a lot!

How to SQLITE in C#

I nearly used everything in that article to create the SQLite database for my own C# Application.

Don't forget to download the SQLite.dll, and add it as a reference to your project. This can be done using NuGet and by adding the dll manually.

After you added the reference, refer to the dll from your code using the following line on top of your class:

using System.Data.SQLite;

You can find the dll's here:

SQLite DLL's

You can find the NuGet way here:


Up next is the create script. Creating a database file:


SQLiteConnection m_dbConnection = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;");

string sql = "create table highscores (name varchar(20), score int)";

SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);

sql = "insert into highscores (name, score) values ('Me', 9001)";

command = new SQLiteCommand(sql, m_dbConnection);


After you created a create script in C#, I think you might want to add rollback transactions, it is safer and it will keep your database from failing, because the data will be committed at the end in one big piece as an atomic operation to the database and not in little pieces, where it could fail at 5th of 10 queries for example.

Example on how to use transactions:

 using (TransactionScope tran = new TransactionScope())
     //Insert create script here.

     //Indicates that creating the SQLiteDatabase went succesfully, so the database can be committed.

How to remove responsive features in Twitter Bootstrap 3?

To inactivate the non-desktop styles you just have to change 4 lines of code in the variables.less file. Set the screen width breakpoints in the variables.less file like this:

// Media queries breakpoints
// --------------------------------------------------

// Extra small screen / phone
// Note: Deprecated @screen-xs and @screen-phone as of v3.0.1
@screen-xs:                  1px;
@screen-xs-min:              @screen-xs;
@screen-phone:               @screen-xs-min;

// Small screen / tablet
// Note: Deprecated @screen-sm and @screen-tablet as of v3.0.1
@screen-sm:                  2px;
@screen-sm-min:              @screen-sm;
@screen-tablet:              @screen-sm-min;

// Medium screen / desktop
// Note: Deprecated @screen-md and @screen-desktop as of v3.0.1
@screen-md:                  3px;
@screen-md-min:              @screen-md;
@screen-desktop:             @screen-md-min;

// Large screen / wide desktop
// Note: Deprecated @screen-lg and @screen-lg-desktop as of v3.0.1
@screen-lg:                  9999px;
@screen-lg-min:              @screen-lg;
@screen-lg-desktop:          @screen-lg-min;

This sets the min-width on the desktop style media query lower so that it applies to all screen widths. Thanks to 2calledchaos for the improvement! Some base styles are defined in the mobile styles, so we need to be sure to include them.

Edit: chris notes that you can set these variables in the online less compiler on the bootstrap site

Angular - "has no exported member 'Observable'"

In my case this error was happening because I had an old version of ng cli in my computer.

The problem was solved after running:

ng update

ng update @angular/cli

Downloading all maven dependencies to a directory NOT in repository?

Based on @Raghuram answer, I find a tutorial on Copying project dependencies, Just:

  1. Open your project pom.xml file and find this:

  2. Than replace the <plugins> ... </plugins> with:

  3. And call maven within the command line mvn dependency:copy-dependencies

After it finishes, it will create the folder target/dependency within all the jar's dependencies on the current directory where the pom.xml lives.

Javascript sleep/delay/wait function

The behavior exact to the one specified by you is impossible in JS as implemented in current browsers. Sorry.

Well, you could in theory make a function with a loop where loop's end condition would be based on time, but this would hog your CPU, make browser unresponsive and would be extremely poor design. I refuse to even write an example for this ;)

Update: My answer got -1'd (unfairly), but I guess I could mention that in ES6 (which is not implemented in browsers yet, nor is it enabled in Node.js by default), it will be possible to write a asynchronous code in a synchronous fashion. You would need promises and generators for that.

You can use it today, for instance in Node.js with harmony flags, using Q.spawn(), see this blog post for example (last example there).

Android: How to handle right to left swipe gestures

In order to have Click Listener, DoubleClick Listener, OnLongPress Listener, Swipe Left, Swipe Right, Swipe Up, Swipe Down on Single View you need to setOnTouchListener. i.e,

view.setOnTouchListener(new OnSwipeTouchListener(MainActivity.this) {

            public void onClick() {
                // your on click here

            public void onDoubleClick() {
                // your on onDoubleClick here

            public void onLongClick() {
                // your on onLongClick here

            public void onSwipeUp() {
                // your swipe up here

            public void onSwipeDown() {
                // your swipe down here.

            public void onSwipeLeft() {
                // your swipe left here.

            public void onSwipeRight() {
                // your swipe right here.


For this you need OnSwipeTouchListener class that implements OnTouchListener.

public class OnSwipeTouchListener implements View.OnTouchListener {

private GestureDetector gestureDetector;

public OnSwipeTouchListener(Context c) {
    gestureDetector = new GestureDetector(c, new GestureListener());

public boolean onTouch(final View view, final MotionEvent motionEvent) {
    return gestureDetector.onTouchEvent(motionEvent);

private final class GestureListener extends GestureDetector.SimpleOnGestureListener {

    private static final int SWIPE_THRESHOLD = 100;
    private static final int SWIPE_VELOCITY_THRESHOLD = 100;

    public boolean onDown(MotionEvent e) {
        return true;

    public boolean onSingleTapUp(MotionEvent e) {
        return super.onSingleTapUp(e);

    public boolean onDoubleTap(MotionEvent e) {
        return super.onDoubleTap(e);

    public void onLongPress(MotionEvent e) {

    // Determines the fling velocity and then fires the appropriate swipe event accordingly
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        boolean result = false;
        try {
            float diffY = e2.getY() - e1.getY();
            float diffX = e2.getX() - e1.getX();
            if (Math.abs(diffX) > Math.abs(diffY)) {
                if (Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
                    if (diffX > 0) {
                    } else {
            } else {
                if (Math.abs(diffY) > SWIPE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {
                    if (diffY > 0) {
                    } else {
        } catch (Exception exception) {
        return result;

public void onSwipeRight() {

public void onSwipeLeft() {

public void onSwipeUp() {

public void onSwipeDown() {

public void onClick() {


public void onDoubleClick() {


public void onLongClick() {


javax.el.PropertyNotFoundException: Property 'foo' not found on type com.example.Bean

I believe the id accessors don't match the bean naming conventions and that's why the exception is thrown. They should be as follows:

public Integer getId() { return id; }    
public void setId(Integer i){ id= i; }

Excel: Search for a list of strings within a particular string using array formulas?

In case others may find this useful: I found that by adding an initial empty cell to my list of search terms, a zero value will be returned instead of error.


NB: Column A has the search terms, B is the row number index.

store and retrieve a class object in shared preference

Yes .You can store and retrive the object using Sharedpreference

Detected both log4j-over-slf4j.jar AND slf4j-log4j12.jar on the class path, preempting StackOverflowError.

You asked if it is possible to change the circular dependency checking in those slf4j classes.

The simple answer is no.

  • It is unconditional ... as implemented.
  • It is implemented in a static initializer block ... so you can't override the implementation, and you can't stop it happening.

So the only way to change this would be to download the source code, modify the core classes to "fix" them, build and use them. That is probably a bad idea (in general) and probably not solution in this case; i.e. you risk triggering the stack overflow problem that the message warns about.


The real solution (as you identified in your Answer) is to use the right JARs. My understanding is that the circularity that was detected is real and potentially problematic ... and unnecessary.

XPath: Get parent node from child node

New, improved answer to an old, frequently asked question...

How could I get its parent? Result should be the store node.

Use a predicate rather than the parent:: or ancestor:: axis

Most answers here select the title and then traverse up to the targeted parent or ancestor (store) element. A simpler, direct approach is to select parent or ancestor element directly in the first place, obviating the need to traverse to a parent:: or ancestor:: axes:

//*[book/title = "50"]

Should the intervening elements vary in name:

//*[*/title = "50"]

Or, in name and depth:

//*[.//title = "50"]

Leave only two decimal places after the dot

Try This

public static string PreciseDecimalValue(double Value, int DigitsAfterDecimal)
            string PreciseDecimalFormat = "{0:0.0}";

            for (int count = 2; count <= DigitsAfterDecimal; count++)
                PreciseDecimalFormat = PreciseDecimalFormat.Insert(PreciseDecimalFormat.LastIndexOf('}'), "0");
            return String.Format(PreciseDecimalFormat, Value);

Save classifier to disk in scikit-learn

Classifiers are just objects that can be pickled and dumped like any other. To continue your example:

import cPickle
# save the classifier
with open('my_dumped_classifier.pkl', 'wb') as fid:
    cPickle.dump(gnb, fid)    

# load it again
with open('my_dumped_classifier.pkl', 'rb') as fid:
    gnb_loaded = cPickle.load(fid)

Edit: if you are using a sklearn Pipeline in which you have custom transformers that cannot be serialized by pickle (nor by joblib), then using Neuraxle's custom ML Pipeline saving is a solution where you can define your own custom step savers on a per-step basis. The savers are called for each step if defined upon saving, and otherwise joblib is used as default for steps without a saver.

Get a resource using getResource()

Instead of explicitly writing the class name you could use


Get product id and product type in magento?

you can get all product information from following code


    $product_data["special price"]=$_product->getFinalPrice();
    $product_data["color"]=$_product->getAttributeText('color'); //get cusom attribute value

    $storeId = Mage::app()->getStore()->getId();
    $summaryData = Mage::getModel('review/review_summary')->setStoreId($storeId)  ->load($_product->getId());


    if($_product->isSalable() ==1)

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

How do I request and receive user input in a .bat and use it to run a certain program?

Add quotation marks (" ") around the %INPUT% so it looks like this:

If "%INPUT%" == "y" goto yes
If "%INPUT%" == "n" goto no
If "%INPUT%" == "Y" goto yes
If "%INPUT%" == "N" goto no

Swift 2: Call can throw, but it is not marked with 'try' and the error is not handled

You have to catch the error just as you're already doing for your save() call and since you're handling multiple errors here, you can try multiple calls sequentially in a single do-catch block, like so:

func deleteAccountDetail() {
    let entityDescription = NSEntityDescription.entityForName("AccountDetail", inManagedObjectContext: Context!)
    let request = NSFetchRequest()
    request.entity = entityDescription

    do {
        let fetchedEntities = try self.Context!.executeFetchRequest(request) as! [AccountDetail]

        for entity in fetchedEntities {

        try self.Context!.save()
    } catch {

Or as @bames53 pointed out in the comments below, it is often better practice not to catch the error where it was thrown. You can mark the method as throws then try to call the method. For example:

func deleteAccountDetail() throws {
    let entityDescription = NSEntityDescription.entityForName("AccountDetail", inManagedObjectContext: Context!)
    let request = NSFetchRequest()

    request.entity = entityDescription

    let fetchedEntities = try Context.executeFetchRequest(request) as! [AccountDetail]

    for entity in fetchedEntities {

    try self.Context!.save()

How to write one new line in Bitbucket markdown?

Feb 3rd 2020:

  • Atlassian Bitbucket v5.8.3 local installation.
  • I wanted to add a new line around an horizontal line. --- did produce the line, but I could not get new lines to work with suggestions above.
  • note: I did not want to use the [space][space] suggestion, since my editor removes trailing spaces on save, and I like this feature on.

I ended up doing this:


Resulting in:

----------------- AN HORIZONTAL LINE ----------------

Remove trailing spaces automatically or with a shortcut

Have a look at the EditorConfig plugin.

By using the plugin you can have settings specific for various projects. Visual Studio Code also has IntelliSense built-in for .editorconfig files.

Pylint "unresolved import" error in Visual Studio Code

I have the same problem with python 3.8.5 using venv,vscode 1.48.2 I found my solution. In (env folder)/lib/site-packages does not contains the packages. I use this setting (.vscode/settings.json)

        "python.autoComplete.extraPaths": [
        "python.pythonPath": "env\\Scripts\\python.exe",
        "python.languageServer": "Microsoft"

UTF-8 text is garbled when form is posted as multipart/form-data

In case someone stumbled upon this problem when working on Grails (or pure Spring) web application, here is the post that helped me:

To set default encoding to UTF-8 (instead of the ISO-8859-1) for multipart requests, I added the following code in resources.groovy (Spring DSL):

multipartResolver(ContentLengthAwareCommonsMultipartResolver) {
    defaultEncoding = 'UTF-8'

Correct way to create rounded corners in Twitter Bootstrap

Without less, ans simply for a given div :

In a css :

.footer {
background-color: #ab0000;
padding-top: 40px;
padding-bottom: 10px;

In html :

 <div class="footer">

Maven compile: package does not exist

Not sure if there was file corruption or what, but after confirming proper pom configuration I was able to resolve this issue by deleting the jar from my local m2 repository, forcing Maven to download it again when I ran the tests.

msvcr110.dll is missing from computer error while installing PHP

Since link to this question shows up on very top of returned results when you search for "php MSVCR110.dll" (not to mention it got 100k+ views and growing), here're some additional notes that you may find handy in your quest to solve MSVCR110.dll mistery...

The approach described in the answer is valid not only for MSVCR110.dll case but also applies when you are looking for other versions, like newer MSVCR71.dll and I updated the answer to include VC15 even it's beyond scope of the original question.

On you can read:

VC9, VC11 and VC15

More recent versions of PHP are built with VC9, VC11 or VC15 (Visual Studio 2008, 2012 or 2015 compiler respectively) and include improvements in performance and stability.

The VC9 builds require you to have the Visual C++ Redistributable for Visual Studio 2008 SP1 x86 or x64 installed.

The VC11 builds require to have the Visual C++ Redistributable for Visual Studio 2012 x86 or x64 installed.

The VC15 builds require to have the Visual C++ Redistributable for Visual Studio 2015 x86 or x64 installed.

This is quite crucial as you not only need to get Visual C++ Redistributable installed but you also need the right version of it, and which one is right and correct, depends on what PHP build you are actually going to use. Pay attention to what version of PHP for Windows you are fetching, especially pay attention to this "VCxx" suffix, because if you install PHP that requires VC9 while having redistributables VC11 installed it is not going to work as run-time dependency is simply not fulfilled. Contrary to what some may think, you need exactly the version required, as newer (higher) releases does NOT cover older (lower) versions. so i.e. VC11 is not providing VC9 compatibility. Also VC15 is neither fulfilling VC11 nor VC9 dependency. It is just VC15 and NOTHING ELSE. Deal with it :)

For example, archive name php-5.6.4-nts-Win32-VC11-x86 tells us the following

enter image description here

  1. it provides PHP v5.6.4,
  2. PHP build is Non-Thread Safe (nts),
  3. it provides binaries for Windows (Win32),
  4. to run, Visual Studio 2012 redistributable (VC11) is required,
  5. binaries are 32-bit (x86),

Most searches I did lead to VC9 of redistributables, so in case of constant failures to make thing works, if possible, try installing different PHP build, to see if you by any chance do not face mismatching versions.

Download links

Note that you are using 32-bit version of PHP, so you need 32-bit redistributable (x86) even if your version of Windows is 64-bit!

  • VC9: Visual C++ Redistributable for Visual Studio 2008: x86 or x64
  • VC11: Visual C++ Redistributable for Visual Studio 2012: x86 or x64
  • VC15: Visual C++ Redistributable for Visual Studio 2015: x86 or x64
  • VC17: Visual C++ Redistributable for Visual Studio 2017: x86 or x64

Case insensitive string compare in LINQ-to-SQL

If you pass a string that is case-insensitive into LINQ-to-SQL it will get passed into the SQL unchanged and the comparison will happen in the database. If you want to do case-insensitive string comparisons in the database all you need to to do is create a lambda expression that does the comparison and the LINQ-to-SQL provider will translate that expression into a SQL query with your string intact.

For example this LINQ query:

from user in Users
where user.Email == "[email protected]"
select user

gets translated to the following SQL by the LINQ-to-SQL provider:

SELECT [t0].[Email]
FROM [User] AS [t0]
WHERE [t0].[Email] = @p0
-- note that "@p0" is defined as nvarchar(11)
-- and is passed my value of "[email protected]"

As you can see, the string parameter will be compared in SQL which means things ought to work just the way you would expect them to.

Submit form without page reloading

Submitting Form Without Reloading The Page And Get Result Of Submitted Data In The Same Page

Here's some of the code I found on the internet that solves this problem :


When the form is submitted, The action will be executed and target the specific iframe to reload.


<iframe name="content" style="">
<form action="iframe_content.php" method="post" target="content">
<input type="text" name="Name" value="">
<input type="submit" name="Submit" value="Submit">


if (isset($_POST['Submit'])){
$Name = $_POST['Name'];
echo $Name;

2.) AJAX


   <script src="">
    <script type="text/javascript">
    function clickButton(){
    var name=document.getElementById('name').value;
    var descr=document.getElementById('descr').value;
               'name' :name,
               'descr' :descr
            success: function (html) 
               alert('Data Send');
            return false;
    <form >
    <input type="" name="name" id="name">
    <input type="" name="descr" id="descr">
    <input type="submit" name="" value="submit" onclick="return clickButton();">
    <p id="msg"></p>


$name = $_POST['name'];
$descr = $_POST['descr'];

echo $name;
echo $descr;



How do I make WRAP_CONTENT work on a RecyclerView

This now works as they've made a release in version 23.2, as stated in this post. Quoting the official blogpost

This release brings an exciting new feature to the LayoutManager API: auto-measurement! This allows a RecyclerView to size itself based on the size of its contents. This means that previously unavailable scenarios, such as using WRAP_CONTENT for a dimension of the RecyclerView, are now possible. You’ll find all built in LayoutManagers now support auto-measurement.

Missing maven .m2 folder

On a Windows machine, the .m2 folder is expected to be located under ${user.home}. On Windows 7 and Vista this resolves to <root>\Users\<username> and on XP it is <root>\Documents and Settings\<username>\.m2. So you'd normally see it under c:\Users\Jonathan\.m2.

If you want to create a folder with a . prefix on Windows, you can simply do this on the command line.

  • Go to Start->Run
  • Type cmd and press Enter
  • At the command prompt type md c:\Users\Jonathan\.m2 (or equivalent for your ${user.home} value).

Note that you don't actually need the .m2 location unless you want to create a distinct user settings file, which is optional (see the Settings reference for more details).

If you don't need a separate user settings file and don't really want the local repository under your user home you can simply set the location of your repository to a different folder by modifying the global settings file (located in \conf\settings.xml).

The following snippet would set the local repository to c:\Maven\repository for example:

<settings xmlns=""

What is the difference between connection and read timeout for sockets?

  1. What is the difference between connection and read timeout for sockets?

The connection timeout is the timeout in making the initial connection; i.e. completing the TCP connection handshake. The read timeout is the timeout on waiting to read data1. If the server (or network) fails to deliver any data <timeout> seconds after the client makes a socket read call, a read timeout error will be raised.

  1. What does connection timeout set to "infinity" mean? In what situation can it remain in an infinitive loop? and what can trigger that the infinity-loop dies?

It means that the connection attempt can potentially block for ever. There is no infinite loop, but the attempt to connect can be unblocked by another thread closing the socket. (A Thread.interrupt() call may also do the trick ... not sure.)

  1. What does read timeout set to "infinity" mean? In what situation can it remain in an infinite loop? What can trigger that the infinite loop to end?

It means that a call to read on the socket stream may block for ever. Once again there is no infinite loop, but the read can be unblocked by a Thread.interrupt() call, closing the socket, and (of course) the other end sending data or closing the connection.

1 - It is not ... as one commenter thought ... the timeout on how long a socket can be open, or idle.

How can I get browser to prompt to save password?

You may attach the dialog to the form, so all those inputs are in a form. The other thing is make the password text field right after the username text field.

jQuery get html of container including the container itself

Simple solution with an example :

<div id="id_div">

Move this DIV to other DIV with id = "other_div_id"

$('#other_div_id').prepend( $('#id_div') );


Change jsp on button click

You could make those submit buttons and inside the servlet your are submitting the form to you could test the name of the button which was pressed and render the corresponding jsp page.

<input type="submit" value="Creazione Nuovo Corso" name="CreateCourse" />
<input type="submit" value="Gestione Autorizzazioni" name="AuthorizationManager" />

Inside the TrainerMenu servlet if request.getParameter("CreateCourse") is not empty then the first button was clicked and you could render the corresponding jsp.

mailto using javascript

You can use the simple mailto, see below for the simple markup.

<a href="mailto:[email protected]">Click here to mail</a>

Once clicked, it will open your Outlook or whatever email client you have set.

struct in class

You should define the struct out of the class like this:

#include <iostream>
using namespace std;
struct X
        int v;
class E
      X var;

int main(){

E object;

return 0;

Access the css ":after" selector with jQuery

You can't manipulate :after, because it's not technically part of the DOM and therefore is inaccessible by any JavaScript. But you can add a new class with a new :after specified.


.pageMenu .active.changed:after { 
/* this selector is more specific, so it takes precedence over the other :after */
    border-top-width: 22px;
    border-left-width: 22px;
    border-right-width: 22px;


$('.pageMenu .active').toggleClass('changed');

UPDATE: while it's impossible to directly modify the :after content, there are ways to read and/or override it using JavaScript. See "Manipulating CSS pseudo-elements using jQuery (e.g. :before and :after)" for a comprehensive list of techniques.

Printing object properties in Powershell

To print out object's properties and values in Powershell. Below examples work well for me.

$pool = Get-Item "IIS:\AppPools.NET v4.5"

$pool | Get-Member

   TypeName: Microsoft.IIs.PowerShell.Framework.ConfigurationElement#system.applicationHost/applicationPools#add

Name                        MemberType            Definition
----                        ----------            ----------
Recycle                     CodeMethod            void Recycle()
Start                       CodeMethod            void Start()
Stop                        CodeMethod            void Stop()
applicationPoolSid          CodeProperty          Microsoft.IIs.PowerShell.Framework.CodeProperty
state                       CodeProperty          Microsoft.IIs.PowerShell.Framework.CodeProperty
ClearLocalData              Method                void ClearLocalData()
Copy                        Method                void Copy(Microsoft.IIs.PowerShell.Framework.ConfigurationElement ...
Delete                      Method                void Delete()

$pool | Select-Object -Property * # You can omit -Property

name                        : .NET v4.5
queueLength                 : 1000
autoStart                   : True
enable32BitAppOnWin64       : False
managedRuntimeVersion       : v4.0
managedRuntimeLoader        : webengine4.dll
enableConfigurationOverride : True
managedPipelineMode         : Integrated
CLRConfigFile               :
passAnonymousToken          : True
startMode                   : OnDemand
state                       : Started
applicationPoolSid          : S-1-5-82-271721585-897601226-2024613209-625570482-296978595
processModel                : Microsoft.IIs.PowerShell.Framework.ConfigurationElement

Ubuntu, how do you remove all Python 3 but not 2

EDIT: As pointed out in recent comments, this solution may BREAK your system.

You most likely don't want to remove python3.

Please refer to the other answers for possible solutions.

Outdated answer (not recommended)

sudo apt-get remove 'python3.*'

Javascript: How to check if a string is empty?

If you want to know if it's an empty string use === instead of ==.

if(variable === "") {

This is because === will only return true if the values on both sides are of the same type, in this case a string.

for example: (false == "") will return true, and (false === "") will return false.

PHP string "contains"

You can use stristr() or strpos(). Both return false if nothing is found.

How to make a shape with left-top round rounded corner and left-bottom rounded corner?

While this question has been answered already (it's a bug that causes bottomLeftRadius and bottomRightRadius to be reversed), the bug has been fixed in android 3.1 (api level 12 - tested on the emulator).

So to make sure your drawables look correct on all platforms, you should put "corrected" versions of the drawables (i.e. where bottom left/right radii are actually correct in the xml) in the res/drawable-v12 folder of your app. This way all devices using an android version >= 12 will use the correct drawable files, while devices using older versions of android will use the "workaround" drawables that are located in the res/drawables folder.

bootstrap datepicker today as default

Perfect Picker with current date and basic settings

            autoclose: true,
            format: "yyyy-mm-dd",
            immediateUpdates: true,
            todayBtn: true,
            todayHighlight: true
        }).datepicker("setDate", "0");

When to use the JavaScript MIME type application/javascript instead of text/javascript?

application/javascript is the correct type to use but since it's not supported by IE6-8 you're going to be stuck with text/javascript. If you don't care about validity (HTML5 excluded) then just don't specify a type.

Internet Access in Ubuntu on VirtualBox

How did you configure networking when you created the guest? The easiest way is to set the network adapter to NAT, if you don't need to access the vm from another pc.

TypeError: unsupported operand type(s) for /: 'str' and 'str'

There is another error with the forwars=d slash.

if we get this : def get_x(r): return path/'train'/r['fname']
is the same as def get_x(r): return path + 'train' + r['fname']

The entity cannot be constructed in a LINQ to Entities query

you can add AsEnumerable to your collection like the follow :

public IQueryable<Product> GetProducts(int categoryID)
    return from p in db.Products.AsEnumerable()
           where p.CategoryID== categoryID
           select new Product { Name = p.Name};

regex pattern to match the end of a string

Something like this should work: /([^/]*)$

What language are you using? End-of-string regex signifiers can vary in different languages.

How do I change the UUID of a virtual disk?

The command fails because it has space in one of the folder name, i.e. 'VirtualBox VMs.

VBoxManage internalcommands sethduuid /home/user/VirtualBox VMs/drupal/drupal.vhd

If there is no space at folder name or file name, then the command will work even without quoting it, e.g. after changing 'VirtualBox VMs' into 'VBoxVMs'

VBoxManage internalcommands sethduuid /home/user/VBoxVMs/drupal/drupal.vhd

How do I link to part of a page? (hash?)

On 12 March 2020, a draft has been added by WICG for Text Fragments, and now you can link to text on a page as if you were searching for it by adding the following to the hash

#:~:text=<Text To Link to>

Working example on Chrome Version 81.0.4044.138:

Click on this link Should reload the page and highlight the link's text

Developing C# on Linux

Mono is a runtime environment that can run .NET applications and that works on both Windows and Linux. It includes a C# compiler.

As an IDE, you could use MonoDevelop, and I suppose there's something available for Eclipse, too.

Note that WinForms support on Mono is there, but somewhat lacking. Generally, Mono developers seem to prefer different GUI toolkits such as Gtk#.

Trying to retrieve first 5 characters from string in bash error?

That parameter expansion should work (what version of bash do you have?)

Here's another approach:


Permutation of array

According to wiki

Heap's algorithm generates all possible permutations of n objects. It was first proposed by B. R. Heap in 1963. The algorithm minimizes movement: it generates each permutation from the previous one by interchanging a single pair of elements; the other n-2 elements are not disturbed. In a 1977 review of permutation-generating algorithms, Robert Sedgewick concluded that it was at that time the most effective algorithm for generating permutations by computer.

So if we want to do it in recursive manner, Sudo code is bellow.

procedure generate(n : integer, A : array of any):
    if n = 1 then
        for i := 0; i < n - 1; i += 1 do
            generate(n - 1, A)
            if n is even then
                swap(A[i], A[n-1])
                swap(A[0], A[n-1])
            end if
        end for
        generate(n - 1, A)
    end if

java code:

public static void printAllPermutations(
        int n, int[] elements, char delimiter) {
    if (n == 1) {
        printArray(elements, delimiter);
    } else {
        for (int i = 0; i < n - 1; i++) {
            printAllPermutations(n - 1, elements, delimiter);
            if (n % 2 == 0) {
                swap(elements, i, n - 1);
            } else {
                swap(elements, 0, n - 1);
        printAllPermutations(n - 1, elements, delimiter);

private static void printArray(int[] input, char delimiter) {
    int i = 0;
    for (; i < input.length; i++) {

private static void swap(int[] input, int a, int b) {
    int tmp = input[a];
    input[a] = input[b];
    input[b] = tmp;

public static void main(String[] args) {
    int[] input = new int[]{0,1,2,3};
    printAllPermutations(input.length, input, ',');

Get the last non-empty cell in a column in Google Sheets

This will give the contents of the last cell:


This will give the address of the last cell:


This will give the row of the last cell:


Maybe you'd prefer a script. This script is way shorter than the huge one posted above by someone else:

Go to script editor and save this script:

function getLastRow(range){
  while(range.length>0 && range[range.length-1][0]=='') range.pop();
  return range.length;

One this is done you just need to enter this in a cell:


CSS performance relative to translateZ(0)

I can attest to the fact that -webkit-transform: translate3d(0, 0, 0); will mess with the new position: -webkit-sticky; property. With a left drawer navigation pattern that I was working on, the hardware acceleration I wanted with the transform property was messing with the fixed positioning of my top nav bar. I turned off the transform and the positioning worked fine.

Luckily, I seem to have had hardware acceleration on already, because I had -webkit-font-smoothing: antialiased on the html element. I was testing this behavior in iOS7 and Android.

Iterate through pairs of items in a Python list

Nearly verbatim from Iterate over pairs in a list (circular fashion) in Python:

def pairs(seq):
    i = iter(seq)
    prev = next(i)
    for item in i:
        yield prev, item
        prev = item

validation of input text field in html using javascript

If you are not using jQuery then I would simply write a validation method that you can be fired when the form is submitted. The method can validate the text fields to make sure that they are not empty or the default value. The method will return a bool value and if it is false you can fire off your alert and assign classes to highlight the fields that did not pass validation.


<form name="form1" method="" action="" onsubmit="return validateForm(this)">
<input type="text" name="name" value="Name"/><br />
<input type="text" name="addressLine01" value="Address Line 1"/><br />
<input type="submit"/>


function validateForm(form) {

    var nameField =;
    var addressLine01 = form.addressLine01;

    if (isNotEmpty(nameField)) {
        if(isNotEmpty(addressLine01)) {
            return true;
    return false;

function isNotEmpty(field) {

    var fieldData = field.value;

    if (fieldData.length == 0 || fieldData == "" || fieldData == fieldData) {

        field.className = "FieldError"; //Classs to highlight error
        alert("Please correct the errors in order to continue.");
        return false;
    } else {

        field.className = "FieldOk"; //Resets field back to default
        return true; //Submits form

The validateForm method assigns the elements you want to validate and then in this case calls the isNotEmpty method to validate if the field is empty or has not been changed from the default value. it continuously calls the inNotEmpty method until it returns a value of true or if the conditional fails for that field it will return false.

Give this a shot and let me know if it helps or if you have any questions. of course you can write additional custom methods to validate numbers only, email address, valid URL, etc.

If you use jQuery at all I would look into trying out the jQuery Validation plug-in. I have been using it for my last few projects and it is pretty nice. Check it out if you get a chance.

C# string reference type?

For curious minds and to complete the conversation: Yes, String is a reference type:

     string a = "Test";
     string b = a;
     fixed (char* p = a)
          p[0] = 'B';
     Console.WriteLine(a); // output: "Best"
     Console.WriteLine(b); // output: "Best"

But note that this change only works in an unsafe block! because Strings are immutable (From MSDN):

The contents of a string object cannot be changed after the object is created, although the syntax makes it appear as if you can do this. For example, when you write this code, the compiler actually creates a new string object to hold the new sequence of characters, and that new object is assigned to b. The string "h" is then eligible for garbage collection.

string b = "h";  
b += "ello";  

And keep in mind that:

Although the string is a reference type, the equality operators (== and !=) are defined to compare the values of string objects, not references.

Display Images Inline via CSS

Place this css in your page:

   #client_logos {
    display: inline-block;


<p><img class="alignnone" style="display: inline; margin: 0 10px;" title="heartica_logo" src="" alt="" width="150" height="50" /><img class="alignnone" style="display: inline; margin: 0 10px;" title="mouseflow_logo" src="" alt="" width="150" height="50" /><img class="alignnone" style="display: inline; margin: 0 10px;" title="mouseflow_logo" src="" alt="" width="150" height="50" /></p>


<div id="client_logos">
<img style="display: inline; margin: 0 5px;" title="heartica_logo" src="" alt="" width="150" height="50" />
<img style="display: inline; margin: 0 5px;" title="mouseflow_logo" src="" alt="" width="150" height="50" />
<img style="display: inline; margin: 0 5px;" title="piiholo_logo" src="" alt="" width="150" height="50" />

How to clear the cache in NetBeans

The NetBeans cachedir is a directory consisting of files that may become large, may change frequently, and can be deleted and recreated at any time. For example, the results of the Java classpath scan reside in the cachedir.

NetBeans 7.1 and older By default the userdir is inside a (hidden) directory called .netbeans stored in the user's home directory. The home directory is ${HOME} on Unix-like systems, and %USERPROFILE% (usually set to C:\Documents and Settings\) on Windows. The cachedir can be found in var/cache subfolder of the userdir. As the name suggests, the userdir is unique per user. For each version of NetBeans installed, the userdir will be a unique subdirectory such as .netbeans/. To find out your exact userdir location, go to the IDE's main menu, and choose Help > About. (Mac: NetBeans > About NetBeans). NetBeans 7.1 allows to separate the cache directory using a switch --cachedir to a desired location.

Examples A Windows user jdoe running NetBeans 5.0 is likely to find his userdir under C:\Documents and Settings\jdoe.netbeans\5.0\ A Windows Vista user jdoe running NetBeans 5.0 is likely to find his userdir under C:\Users\jdoe.netbeans\5.0\ A Mac OS X user jdoe running NetBeans 5.0 is likely to find his userdir under /Users/jdoe/.netbeans/5.0/ (To open this folder in the Finder, choose Go > Go to Folder from the Finder menu, type /Users/jdoe/.netbeans/5.0/ into the box, and click Go.) A Linux user jdoe running NetBeans 5.0 is likely to find his userdir under /home/jdoe/.netbeans/5.0/

For More Info

See this documentation at the NetBeans site: NetBeans 7.2 and newer

How can I scroll to a specific location on the page using jquery?

Using jquery.easing.min.js, With fixed IE console Errors


<a class="page-scroll" href="#features">Features</a>
<section id="features" class="features-section">Features Section</section>

        <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
        <script src="js/jquery.js"></script>
        <!-- Include all compiled plugins (below), or include individual files as needed -->
        <script src="js/bootstrap.min.js"></script>

        <!-- Scrolling Nav JavaScript -->
        <script src="js/jquery.easing.min.js"></script>


//jQuery to collapse the navbar on scroll, you can use this code with in external file with name scrolling-nav.js
        $(window).scroll(function () {
            if ($(".navbar").offset().top > 50) {
            } else {
        //jQuery for page scrolling feature - requires jQuery Easing plugin
        $(function () {
            $('').bind('click', function (event) {
                var anchor = $(this);
                if ($(anchor).length > 0) {
                    var href = $(anchor).attr('href');
                    if ($(href.substring(href.indexOf('#'))).length > 0) {
                        $('html, body').stop().animate({
                            scrollTop: $(href.substring(href.indexOf('#'))).offset().top
                        }, 1500, 'easeInOutExpo');
                    else {
                        window.location = href;

Find directory name with wildcard or similar to "like"

find supports wildcard matches, just add a *:

find / -type d -name "ora10*"

How to round up integer division and have int result in Java?

this might be helpfull,, Subtract the remainder to the legnth and make it a divisible number and then divide it with 153

int r=message.length()%153;       //Calculate the remainder by %153
return (message.length()-r)/153;  // find the pages by adding the remainder and 
                                  //then divide by 153 

how to find my angular version in my project?

You can also find dependencies version details in package.json file as following:

enter image description here

Reinitialize Slick js after successful ajax call

$('#slick-slider').slick('refresh'); //Working for slick 1.8.1

Adding gif image in an ImageView in android

Showing GIF In Android

Create which extends View Class

 public class CustomGifView extends View {

 private InputStream gifInputStream;
 private Movie gifMovie;
 private int movieWidth, movieHeight;
 private long movieDuration;
 private long mMovieStart;

 public CustomGifView(Context context) {

 public CustomGifView(Context context, AttributeSet attrs) {
  super(context, attrs);

 public CustomGifView(Context context, AttributeSet attrs, 
   int defStyleAttr) {
  super(context, attrs, defStyleAttr);

 private void init(Context context){
  gifInputStream = context.getResources()

  gifMovie = Movie.decodeStream(gifInputStream);
  movieWidth = gifMovie.width();
  movieHeight = gifMovie.height();
  movieDuration = gifMovie.duration();

 protected void onMeasure(int widthMeasureSpec, 
   int heightMeasureSpec) {
  setMeasuredDimension(movieWidth, movieHeight);

 public int getMovieWidth(){
  return movieWidth;

 public int getMovieHeight(){
  return movieHeight;

 public long getMovieDuration(){
  return movieDuration;

 protected void onDraw(Canvas canvas) {

  long now = android.os.SystemClock.uptimeMillis();
        if (mMovieStart == 0) {   // first time
            mMovieStart = now;

        if (gifMovie != null) {

            int dur = gifMovie.duration();
            if (dur == 0) {
                dur = 1000;

            int relTime = (int)((now - mMovieStart) % dur);


            gifMovie.draw(canvas, 0, 0);




Now call this class in your XML

        android:layout_height="wrap_content" />


Modify AndroidManifest.xml to turn OFF hardwareAccelerated.



Another Tricks

For animation functionality you may visit

How to perform mouseover function in Selenium WebDriver using Java?

Based on this blog post I was able to trigger hovering using the following code with Selenium 2 Webdriver:

String javaScript = "var evObj = document.createEvent('MouseEvents');" +
                    "evObj.initMouseEvent(\"mouseover\",true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);" +

((JavascriptExecutor)driver).executeScript(javaScript, webElement);

onclick="location.href='link.html'" does not load page in Safari

I had the same error. Make sure you don't have any <input>, <select>, etc. name="location".

Abstract methods in Python

Abstract base classes are deep magic. Periodically I implement something using them and am amazed at my own cleverness, very shortly afterwards I find myself completely confused by my own cleverness (this may well just be a personal limitation though).

Another way of doing this (should be in the python std libs if you ask me) is to make a decorator.

def abstractmethod(method):
    An @abstractmethod member fn decorator.
    (put this in some library somewhere for reuse).

    def default_abstract_method(*args, **kwargs):
        raise NotImplementedError('call to abstract method ' 
                                  + repr(method))
    default_abstract_method.__name__ = method.__name__    
    return default_abstract_method

class Shape(object):

    def __init__(self, shape_name):
       self.shape = shape_name

    def foo(self):
        print "bar"

class Rectangle(Shape):
    # note you don't need to do the constructor twice either

r = Rectangle("x")

I didn't write the decorator. It just occurred to me someone would have. You can find it here: Good one jimmy2times. Note the discussion at the bottom of that page r.e. type safety of the decorator. (That could be fixed with the inspect module if anyone was so inclined).

Automated way to convert XML files to SQL database?

There is a project on CodeProject that makes it simple to convert an XML file to SQL Script. It uses XSLT. You could probably modify it to generate the DDL too.

And See this question too : Generating SQL using XML and XSLT

How to add image in Flutter

  1. Create images folder in root level of your project.

    enter image description here

    enter image description here

  2. Drop your image in this folder, it should look like

    enter image description here

  3. Go to your pubspec.yaml file, add assets header and pay close attention to all the spaces.

      uses-material-design: true
      # add this
        - images/profile.jpg
  4. Tap on Packages get at the top right corner of the IDE.

    enter image description here

  5. Now you can use your image anywhere using


submitting a form when a checkbox is checked

                if( $(this).is(":checked") )

Though it would probably be better to add classes to each of the checkboxes and do


so that you can choose which checkboxes submit the form instead of all of them doing it.

How to implement private method in ES6 class with Traceur

As Marcelo Lazaroni has already said,

Although currently there is no way to declare a method or property as private, ES6 modules are not in the global namespace. Therefore, anything that you declare in your module and do not export will not be available to any other part of your program, but will still be available to your module during run time.

But his example didn't show how the private method could access members of the instance of the class. Max shows us some good examples of how access instance members through binding or the alternative of using a lambda method in the constructor, but I would like to add one more simple way of doing it: passing the instance as a parameter to the private method. Doing it this way would lead Max's MyClass to look like this:

function myPrivateFunction(myClass) {
  console.log("My property: " + myClass.prop);

class MyClass() {
  constructor() {
    this.prop = "myProp";
  testMethod() {
module.exports = MyClass;

Which way you do it really comes down to personal preference.

find_spec_for_exe': can't find gem bundler (>= 0.a) (Gem::GemNotFoundException)

The problem in my case is that the Gemfile.lock file had a BUNDLED_WITH version of 1.16.1 and gem install bundler installed version 2.0.1, so there was a version mismatch when looking to right the folder

gem install bundler -v 1.16.1 fixed it

Of course, you can also change your Gemfile.lock's BUNDLED_WITH with last bundler version and use recent software, as Sam3000 suggests

Using Math.round to round to one decimal place?

If you need this and similar operations more often, it may be more convenient to find the right library instead of implementing it yourself.

Here are one-liners solving your question from Apache Commons Math using Precision, Colt using Functions, and Weka using Utils:

double value = 540.512 / 1978.8 * 100;
// Apache commons math
double rounded1 = Precision.round(value, 1);
double rounded2 = Precision.round(value, 1, BigDecimal.ROUND_HALF_UP);
// Colt
double rounded3 = Functions.round(0.1).apply(value)
// Weka
double rounded4 = Utils.roundDouble(value, 1)

Maven dependencies:




Difference between size and length methods?

I bet (no language specified) size() method returns length property.

However valid for loop should looks like:

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

Find the greatest number in a list of numbers

Use max()

>>> l = [1, 2, 5]
>>> max(l)

Convert NVARCHAR to DATETIME in SQL Server 2008

SELECT CONVERT(NVARCHAR, LoginDate, 105)+' '+CONVERT(NVARCHAR, LoginDate, 108) AS LoginDate FROM YourTable

29-08-2013 13:55:48

Most efficient way to convert an HTMLCollection to an Array

not sure if this is the most efficient, but a concise ES6 syntax might be:

let arry = [...htmlCollection] 

Edit: Another one, from Chris_F comment:

let arry = Array.from(htmlCollection)

Change value of input placeholder via model?

Since AngularJS does not have directive DOM manipulations as jQuery does, a proper way to modify attributes of one element will be using directive. Through link function of a directive, you have access to both element and its attributes.

Wrapping you whole input inside one directive, you can still introduce ng-model's methods through controller property.

This method will help to decouple the logic of ngmodel with placeholder from controller. If there is no logic between them, you can definitely go as Wagner Francisco said.

Python: Find index of minimum item in list of floats

I think it's worth putting a few timings up here for some perspective.

All timings done on OS-X 10.5.8 with python2.7

John Clement's answer:

python -m timeit -s 'my_list = range(1000)[::-1]; from operator import itemgetter' 'min(enumerate(my_list),key=itemgetter(1))'
1000 loops, best of 3: 239 usec per loop    

David Wolever's answer:

python -m timeit -s 'my_list = range(1000)[::-1]' 'min((val, idx) for (idx, val) in enumerate(my_list))
1000 loops, best of 3: 345 usec per loop

OP's answer:

python -m timeit -s 'my_list = range(1000)[::-1]' 'my_list.index(min(my_list))'
10000 loops, best of 3: 96.8 usec per loop

Note that I'm purposefully putting the smallest item last in the list to make .index as slow as it could possibly be. It would be interesting to see at what N the iterate once answers would become competitive with the iterate twice answer we have here.

Of course, speed isn't everything and most of the time, it's not even worth worrying about ... choose the one that is easiest to read unless this is a performance bottleneck in your code (and then profile on your typical real-world data -- preferably on your target machines).

How can I plot data with confidence intervals?

Some addition to the previous answers. It is nice to regulate the density of the polygon to avoid obscuring the data points.

lm.fit2 = lm(medv~poly(lstat,2))
new.lstat = seq(min(lstat), max(lstat), length.out=100)
preds <- predict(lm.fit2, newdata = data.frame(lstat=new.lstat), interval = 'prediction')
lines(sort(lstat), fitted(lm.fit2)[order(lstat)], col='red', lwd=3) 
polygon(c(rev(new.lstat), new.lstat), c(rev(preds[ ,3]), preds[ ,2]), density=10, col = 'blue', border = NA)
lines(new.lstat, preds[ ,3], lty = 'dashed', col = 'red')
lines(new.lstat, preds[ ,2], lty = 'dashed', col = 'red')

drawing of the prediction interval in polynomial regression

Please note that you see the prediction interval on the picture, which is several times wider than the confidence interval. You can read here the detailed explanation of those two types of interval estimates.

Java using enum with switch statement

I am doing it like

public enum State
    // Retrieving, // the MediaRetriever is retrieving music //
    Stopped, // media player is stopped and not prepared to play
    Preparing, // media player is preparing...
    Playing, // playback active (media player ready!). (but the media player
                // may actually be
                // paused in this state if we don't have audio focus. But we
                // stay in this state
                // so that we know we have to resume playback once we get
                // focus back)
    Paused; // playback paused (media player ready!)

    //public final static State[] vals = State.values();//copy the values(), calling values() clones the array


public State getState()
        return mState;   

And use in Switch Statement

switch (mService.getState())
case Stopped:
case Paused:


case Preparing:
case Playing:


How to change onClick handler dynamically?

Nobody addressed the actual problem which was happening, to explain why the alert was issued.

This code: document.getElementById("foo").click = new function() { alert('foo'); }; assigns the click property of the #foo element to an empty object. The anonymous function in here is meant to initialize the object. I like to think of this type of function as a constructor. You put the alert in there, so it gets called because the function gets called immediately.

See this question.

git stash -> merge stashed change with current changes

The way I do this is to git add this first then git stash apply <stash code>. It's the most simple way.

jQuery function after .append

I encountered this issue while coding HTML5 for mobile devices. Some browser/device combinations caused errors because .append() method did not reflect the changes in the DOM immediatly (causing the JS to fail).

By quick-and-dirty solution for this situation was:

var appint = setInterval(function(){
    if ( $('#foobar').length > 0 ) {
        //now you can be sure append is ready
        //$('#foobar').remove(); if elem is just for checking
}, 100);
$(body).append('<div>...</div><div id="foobar"></div>');

Build Android Studio app via command line

Cheatsheet for running Gradle from the command line for Android Studio projects on Linux:

cd <project-root>
./gradlew tasks
./gradlew --help

Should get you started..

@ variables in Ruby on Rails

title is a local variable. They only exists within its scope (current block)

@title is an instance variable - and is available to all methods within the class.

You can read more here:

In Ruby on Rails - declaring your variables in your controller as instance variables (@title) makes them available to your view.

BackgroundWorker vs background Thread

What's perplexing to me is that the visual studio designer only allows you to use BackgroundWorkers and Timers that don't actually work with the service project.

It gives you neat drag and drop controls onto your service but... don't even try deploying it. Won't work.

Services: Only use System.Timers.Timer System.Windows.Forms.Timer won't work even though it's available in the toolbox

Services: BackgroundWorkers will not work when it's running as a service Use System.Threading.ThreadPools instead or Async calls

How to get the position of a character in Python?

A character might appear multiple times in a string. For example in a string sentence, position of e is 1, 4, 7 (because indexing usually starts from zero). but what I find is both of the functions find() and index() returns first position of a character. So, this can be solved doing this:

def charposition(string, char):
    pos = [] #list to store positions for each 'char' in 'string'
    for n in range(len(string)):
        if string[n] == char:
    return pos

s = "sentence"
print(charposition(s, 'e')) 

#Output: [1, 4, 7]

How to change bower's default components folder?

In addition to editing .bowerrc to setup your default install path, you can also setup custom install paths for different file types.

There is a node package called bower-installer that provides a single command for managing alternate install paths.

run npm install -g bower-installer

Set up your bower.json

  "name" : "test",
  "version": "0.1",
  "dependencies" : {
    "jquery-ui" : "latest"
  "install" : {
    "path" : {
      "css": "src/css",
      "js": "src/js"
    "sources" : {
      "jquery-ui" : [

Run the following command: bower-installer

This will install components/jquery-ui/themes/start/jquery-ui.css to ./src/css, etc

How can I run code on a background thread on Android?

Remember Running Background, Running continuously are two different tasks.

For long-term background processes, Threads aren't optimal with Android. However, here's the code and do it at your own risk...

Remember Service or Thread will run in the background but our task needs to make trigger (call again and again) to get updates, i.e. once the task is completed we need to recall the function for next update.

Timer (periodic trigger), Alarm (Timebase trigger), Broadcast (Event base Trigger), recursion will awake our functions.

public static boolean isRecursionEnable = true;

void runInBackground() {
    if (!isRecursionEnable)
        // Handle not to start multiple parallel threads

    // isRecursionEnable = false; when u want to stop
    // on exception on thread make it true again  
    new Thread(new Runnable() {
        public void run() {
            // DO your work here
            // get the data
            if (activity_is_not_in_background) {
                runOnUiThread(new Runnable() {
                    public void run() {
                        // update UI
            } else {

Using Service: If you launch a Service it will start, It will execute the task, and it will terminate itself. after the task execution. terminated might also be caused by exception, or user killed it manually from settings. START_STICKY (Sticky Service) is the option given by android that service will restart itself if service terminated.

Remember the question difference between multiprocessing and multithreading? Service is a background process (Just like activity without UI), The same way how you launch thread in the activity to avoid load on the main thread (Activity thread), the same way you need to launch threads(or async tasks) on service to avoid load on service.

In a single statement, if you want a run a background continues task, you need to launch a StickyService and run the thread in the service on event base

How to download HTTP directory with all files and sub-directories as they appear on the online files/folders list?

I was able to get this to work thanks to this post utilizing VisualWGet. It worked great for me. The important part seems to be to check the -recursive flag (see image).

Also found that the -no-parent flag is important, othewise it will try to download everything.

enter image description here enter image description here

jQuery - Dynamically Create Button and Attach Event Handler

You can either use onclick inside the button to ensure the event is preserved, or else attach the button click handler by finding the button after it is inserted. The test.html() call will not serialize the event.

Multiline TextBox multiple newline

textBox1.Text = "Line1\r\r\Line2";
Solved the problem.

How to clone a Date object?

Use the Date object's getTime() method, which returns the number of milliseconds since 1 January 1970 00:00:00 UTC (epoch time):

var date = new Date();
var copiedDate = new Date(date.getTime());

In Safari 4, you can also write:

var date = new Date();
var copiedDate = new Date(date);

...but I'm not sure whether this works in other browsers. (It seems to work in IE8).

Difference between SET autocommit=1 and START TRANSACTION in mysql (Have I missed something?)

If you want to use rollback, then use start transaction and otherwise forget all those things,

By default, MySQL automatically commits the changes to the database.

To force MySQL not to commit these changes automatically, execute following:

SET autocommit = 0;
SET autocommit = OFF

To enable the autocommit mode explicitly:

SET autocommit = 1;
SET autocommit = ON;

Clear form fields with jQuery

Use this Code Where you want to Call Normal Reset Function by jQuery


And Write this Function Out Site jQuery on Document Ready

function reset_form()
    var fm=document.getElementById('form1');

Can I set the cookies to be used by a WKWebView?

Edit for iOS 11+ only

Use WKHTTPCookieStore:

let cookie = HTTPCookie(properties: [
    .domain: "",
    .path: "/",
    .name: "MyCookieName",
    .value: "MyCookieValue",
    .secure: "TRUE",
    .expires: NSDate(timeIntervalSinceNow: 31556926)


Since you are pulling them over from HTTPCookeStorage, you can do this:

let cookies = HTTPCookieStorage.shared.cookies ?? []
for cookie in cookies {

Old answer for iOS 10 and below

If you require your cookies to be set on the initial load request, you can set them on NSMutableURLRequest. Because cookies are just a specially formatted request header this can be achieved like so:

WKWebView * webView = /*set up your webView*/
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@""]];
[request addValue:@"TeskCookieKey1=TeskCookieValue1;TeskCookieKey2=TeskCookieValue2;" forHTTPHeaderField:@"Cookie"];
// use stringWithFormat: in the above line to inject your values programmatically
[webView loadRequest:request];

If you require subsequent AJAX requests on the page to have their cookies set, this can be achieved by simply using WKUserScript to set the values programmatically via javascript at document start like so:

WKUserContentController* userContentController =;
WKUserScript * cookieScript = [[WKUserScript alloc] 
    initWithSource: @"document.cookie = 'TeskCookieKey1=TeskCookieValue1';document.cookie = 'TeskCookieKey2=TeskCookieValue2';"
    injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
// again, use stringWithFormat: in the above line to inject your values programmatically
[userContentController addUserScript:cookieScript];
WKWebViewConfiguration* webViewConfig =;
webViewConfig.userContentController = userContentController;
WKWebView * webView = [[WKWebView alloc] initWithFrame:CGRectMake(/*set your values*/) configuration:webViewConfig];

Combining these two techniques should give you enough tools to transfer cookie values from Native App Land to Web View Land. You can find more info on the cookie javascript API on Mozilla's page if you require some more advanced cookies.

Yeah, it sucks that Apple is not supporting many of the niceties of UIWebView. Not sure if they will ever support them, but hopefully they will get on this soon. Hope this helps!

Java Compare Two List's object values?

First, implement the MyData.equals(Object o) and MyData.hashCode() methods. Once you implemented the equals method, you can iterate over the lists as follows:

if(ListA == null && ListB == null)
    return false;
if(ListA == null && ListB != null)
    return true;
if(ListA != null && ListB == null)
    return true;
int max = ListA.size() > ListB.size() ? ListA.size() : ListB.size();
for(int i = 0; i < max; i++) {
    myData1 = ListA.get(i);
    myData2 = ListB.get(i);
    if(!myData1.equals(myData2)) {
        return true;
return false;

Reading string by char till end of line C/C++

A text file does not have \0 at the end of lines. It has \n. \n is a character, not a string, so it must be enclosed in single quotes

if (c == '\n')

Ruby sleep or delay less than a second?


As to your follow up question if that's the best way: No, you could get not-so-smooth framerates because the rendering of each frame might not take the same amount of time.

You could try one of these solutions:

  • Use a timer which fires 24 times a second with the drawing code.
  • Create as many frames as possible, create the motion based on the time passed, not per frame.

How to get all the values of input array element jquery

By Using map

var values = $("input[name='pname[]']")
              .map(function(){return $(this).val();}).get();

How to compile the finished C# project and then run outside Visual Studio?

I'm using Visual Studio 2017.

  1. Go to dropdown box build.
  2. Choose Pubish Guessing Game (or whatever your project is called.
  3. Wiz Box opens so tell it where to publish it and click Next.
  4. Choose how to install (I usually choose CD-ROM). click Next.
  5. Choose updates check (I usually choose no check) click Next.
  6. Click Finish

It will publish, complete with setup file to the location you specified.

Hope this helps

Convert string to JSON array

Here you get JSONObject so change this line:

JSONArray jsonArray = new JSONArray(readlocationFeed); 

with following:

JSONObject jsnobject = new JSONObject(readlocationFeed);

and after

JSONArray jsonArray = jsnobject.getJSONArray("locations");
for (int i = 0; i < jsonArray.length(); i++) {
    JSONObject explrObject = jsonArray.getJSONObject(i);

Why do I get the "Unhandled exception type IOException"?

Java has a feature called "checked exceptions". That means that there are certain kinds of exceptions, namely those that subclass Exception but not RuntimeException, such that if a method may throw them, it must list them in its throws declaration, say: void readData() throws IOException. IOException is one of those.

Thus, when you are calling a method that lists IOException in its throws declaration, you must either list it in your own throws declaration or catch it.

The rationale for the presence of checked exceptions is that for some kinds of exceptions, you must not ignore the fact that they may happen, because their happening is quite a regular situation, not a program error. So, the compiler helps you not to forget about the possibility of such an exception being raised and requires you to handle it in some way.

However, not all checked exception classes in Java standard library fit under this rationale, but that's a totally different topic.

How would I get everything before a : in a string Python

Using index:

>>> string = "Username: How are you today?"
>>> string[:string.index(":")]

The index will give you the position of : in string, then you can slice it.

If you want to use regex:

>>> import re
>>> re.match("(.*?):",string).group()

match matches from the start of the string.

you can also use itertools.takewhile

>>> import itertools
>>> "".join(itertools.takewhile(lambda x: x!=":", string))

Difference between two dates in MySQL

Or, you could use TIMEDIFF function

mysql> SELECT TIMEDIFF('2000:01:01 00:00:00', '2000:01:01 00:00:00.000001');
mysql> SELECT TIMEDIFF('2008-12-31 23:59:59.000001' , '2008-12-30 01:01:01.000002');

How can I simulate a print statement in MySQL?

to take output in MySQL you can use if statement SYNTAX:


the if_true and if_false can be used to verify and to show output as there is no print statement in the MySQL

Arrays.fill with multidimensional array in Java

Don't we all sometimes wish there was a
<T>void java.util.Arrays.deepFill(T[]…multiDimensional). Problems start with
Object threeByThree[][] = new Object[3][3];
threeByThree[1] = null; and
threeByThree[2][1] = new int[]{42}; being perfectly legal.
(If only Object twoDim[]final[] was legal and well defined…)
(Using one of the public methods from below keeps loops from the calling source code.
If you insist on using no loops at all, substitute the loops and the call to Arrays.fill()(!) using recursion.)

/** Fills matrix {@code m} with {@code value}.
 * @return {@code m}'s dimensionality.
 * @throws java.lang.ArrayStoreException if the component type
 *  of a subarray of non-zero length at the bottom level
 *  doesn't agree with {@code value}'s type. */
public static <T>int deepFill(Object[] m, T value) {
    Class<?> components; 
    if (null == m ||
        null == (components = m.getClass().getComponentType()))
        return 0;
    int dim = 0;
    while (null != (components = components.getComponentType()));
    filler((Object[][])m, value, dim);
    return dim;
/** Fills matrix {@code m} with {@code value}.
 * @throws java.lang.ArrayStoreException if the component type
 *  of a subarray of non-zero length at level {@code dimensions}
 *  doesn't agree with {@code value}'s type. */
public static <T>void fill(Object[] m, T value, int dimensions) {
    if (null != m)
        filler(m, value, dimensions);

static <T>void filler(Object[] m, T value, int toGo) {
    if (--toGo <= 0)
        java.util.Arrays.fill(m, value);
        for (Object[] subArray : (Object[][])m)
            if (null != subArray)
                filler(subArray, value, toGo);

Better way to right align text in HTML Table

Use jquery to apply class to all tr unobtrusively.

$(”table td”).addClass(”right-align-class");

Use enhanced filters on td in case you want to select a particular td.

See jquery

this in equals method

You are comparing two objects for equality. The snippet:

if (obj == this) {     return true; } 

is a quick test that can be read

"If the object I'm comparing myself to is me, return true"

. You usually see this happen in equals methods so they can exit early and avoid other costly comparisons.

MySQLi prepared statements error reporting

Not sure if this answers your question or not. Sorry if not

To get the error reported from the mysql database about your query you need to use your connection object as the focus.


echo $mysqliDatabaseConnection->error

would echo the error being sent from mysql about your query.

Hope that helps

Rounding a number to the nearest 5 or 10 or X

For a strict Visual Basic approach, you can convert the floating-point value to an integer to round to said integer. VB is one of the rare languages that rounds on type conversion (most others simply truncate.)

Multiples of 5 or x can be done simply by dividing before and multiplying after the round.

If you want to round and keep decimal places, Math.round(n, d) would work.

Running PHP script from the command line

I was looking for a resolution to this issue in Windows, and it seems to be that if you don't have the environments vars ok, you need to put the complete directory. For eg. with a file in the same directory than PHP:

F:\myfolder\php\php.exe -f F:\myfolder\php\script.php

Pods stuck in Terminating status

If --grace-period=0 is not working then you can do:

kubectl delete pods <pod> --grace-period=0 --force

POST Multipart Form Data using Retrofit 2.0 including image

Kotlin version with update for deprication of RequestBody.create :

Retrofit interface

fun uploadFile(@Part file: MultipartBody.Part): Call<FileResponse>

and to Upload

fun uploadFile(fileUrl: String){
    val file = File(fileUrl)
    val fileUploadService = RetrofitClientInstance.retrofitInstance.create(
    val requestBody = file.asRequestBody(file.extension.toMediaTypeOrNull())
    val filePart = MultipartBody.Part.createFormData(
    val call = fileUploadService.uploadFile(filePart)

    call.enqueue(object: Callback<FileResponse>{
        override fun onFailure(call: Call<FileResponse>, t: Throwable) {

        override fun onResponse(call: Call<FileResponse>, response: Response<FileResponse>) {
            Log.d(TAG,"success"+response.toString()+" "+response.body().toString()+"  "+response.body()?.status)


Thanks to @jimmy0251

How to use a BackgroundWorker?

I know this is a bit old, but in case another beginner is going through this, I'll share some code that covers a bit more of the basic operations, here is another example that also includes the option to cancel the process and also report to the user the status of the process. I'm going to add on top of the code given by Alex Aza in the solution above

public Form1()

    backgroundWorker1.DoWork += backgroundWorker1_DoWork;
    backgroundWorker1.ProgressChanged += backgroundWorker1_ProgressChanged;
    backgroundWorker1.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted;  //Tell the user how the process went
    backgroundWorker1.WorkerReportsProgress = true;
    backgroundWorker1.WorkerSupportsCancellation = true; //Allow for the process to be cancelled

//Start Process
private void button1_Click(object sender, EventArgs e)

//Cancel Process
private void button2_Click(object sender, EventArgs e)
    //Check if background worker is doing anything and send a cancellation if it is
    if (backgroundWorker1.IsBusy)


private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
    for (int i = 0; i < 100; i++)

        //Check if there is a request to cancel the process
        if (backgroundWorker1.CancellationPending)
            e.Cancel = true;
    //If the process exits the loop, ensure that progress is set to 100%
    //Remember in the loop we set i < 100 so in theory the process will complete at 99%

private void backgroundWorker1_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
    progressBar1.Value = e.ProgressPercentage;

private void backgroundWorker1_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
    if (e.Cancelled)
         lblStatus.Text = "Process was cancelled";
    else if (e.Error != null)
         lblStatus.Text = "There was an error running the process. The thread aborted";
       lblStatus.Text = "Process was completed";

How to wait in bash for several subprocesses to finish and return exit code !=0 when any subprocess ends with code !=0?

I think that the most straight forward way to run jobs in parallel and check for status is using temporary files. There are already a couple similar answers (e.g. Nietzche-jou and mug896).

rm -f fail
for i in `seq 0 9`; do
  doCalculations $i || touch fail &
! [ -f fail ]

The above code is not thread safe. If you are concerned that the code above will be running at the same time as itself, it's better to use a more unique file name, like fail.$$. The last line is to fulfill the requirement: "return exit code 1 when any of subprocesses ends with code !=0?" I threw an extra requirement in there to clean up. It may have been clearer to write it like this:

trap 'rm -f fail.$$' EXIT
for i in `seq 0 9`; do
  doCalculations $i || touch fail.$$ &
! [ -f fail.$$ ] 

Here is a similar snippet for gathering results from multiple jobs: I create a temporary directory, story the outputs of all the sub tasks in a separate file, and then dump them for review. This doesn't really match the question - I'm throwing it in as a bonus:

trap 'rm -fr $WORK' EXIT

mkdir -p $WORK
cd $WORK

for i in `seq 0 9`; do
  doCalculations $i >$i.result &
grep $ *  # display the results with filenames and contents

How can one change the timestamp of an old commit in Git?

Here is a convenient alias that changes both commit and author times of the last commit to a time accepted by date --date:

    cd = "!d=\"$(date -d \"$1\")\" && shift && GIT_COMMITTER_DATE=\"$d\" \
            git commit --amend --date \"$d\""

Usage: git cd <date_arg>


git cd now  # update the last commit time to current time
git cd '1 hour ago'  # set time to 1 hour ago

Edit: Here is a more-automated version which checks that the index is clean (no uncommitted changes) and reuses the last commit message, or fails otherwise (fool-proof):

    cd = "!d=\"$(date -d \"$1\")\" && shift && \
        git diff-index --cached --quiet HEAD --ignore-submodules -- && \
        GIT_COMMITTER_DATE=\"$d\" git commit --amend -C HEAD --date \"$d\"" \
        || echo >&2 "error: date change failed: index not clean!"

Add x and y labels to a pandas plot

For cases where you use pandas.DataFrame.hist:

plt = df.Column_A.hist(bins=10)

Note that you get an ARRAY of plots, rather than a plot. Thus to set the x label you will need to do something like this

plt[0][0].set_xlabel("column A")

How to have a a razor action link open in a new tab?

If your goal is to use the ActionLink helper and open a new tab:

@Html.ActionLink("New tab please", "Home", null , new { target = "_blank" })

@Html.ActionLink("New tab please", "Home", Nothing, New With {Key .target = "_blank"})

What's the complete range for Chinese characters in Unicode?

Unicode version 11.0.0

In Unicode the Chinese, Japanese and Korean (CJK) scripts share a common background, collectively known as CJK characters.

These ranges often contain non-assigned or reserved code points(such as U+2E9A , U+2EF4 - 2EFF),

Chinese characters

bottom  top     reference (also have a look at wiki page)   block name
4E00    9FEF CJK Unified Ideographs
3400    4DBF CJK Unified Ideographs Extension A
20000   2A6DF    CJK Unified Ideographs Extension B
2A700   2B73F    CJK Unified Ideographs Extension C
2B740   2B81F    CJK Unified Ideographs Extension D
2B820   2CEAF    CJK Unified Ideographs Extension E
2CEB0   2EBEF   CJK Unified Ideographs Extension F
3007    3007    in block CJK Symbols and Punctuation
  • In CJK Unified Ideographs block, I notice many answers use upper bound 9FCC, but U+9FCD(?) is indeed a Chinese char. And all characters in this block are Chinese characters (also used in Japanese or Korean etc.).
  • Most of characters in CJK Unified Ideographs Ext (Except Ext F, only 17% in Ext F are Chinese characters), are traditional Chinese characters, which are rarely used in China.
  • ? is the Chinese character form of zero and still in use today

Therefore the range is


CJK characters but never used in Chinese

They are Common Han used only for compatibility.

It is almost impossible to see them appear in any Chinese books, articles, writings etc.

All characters here have one corresponding glyph-identical Chinese character, such as ?(U+F90A) and ?(U+91D1), they are identical glyphs.

 F900    FAFF  CJK Compatibility Ideographs
2F800   2FA1F CJK Compatibility Ideographs Supplement

CJK related symbols

2E80    2EFF CJK Radicals Supplement
2F00    2FDF Kangxi Radicals 
2FF0    2FFF    Ideographic Description Character
3000    303F    CJK Symbols and Punctuation
3100    312f    Bopomofo
31A0    31BF    Bopomofo Extended
31C0    31EF CJK Strokes
3200    32FF    Enclosed CJK Letters and Months
3300    33FF    CJK Compatibility
FE30    FE4F    CJK Compatibility Forms
FF00    FFEF    Halfwidth and Fullwidth Forms
1F200   1F2FF   Enclosed Ideographic Supplement
  • some blocks such as Hangul Compatibility Jamo are excluded because of no relation to Chinese.
  • Kangxi Radicals is not Chinese characters, they are graphical components of Chinese characters, used specially to express radicals, .e.g. ?(U+2F3B) and ?(U+5F73), ?(U+2EDC) and ? (U+98DE)

Other common punctuation appearing in Chinese

This is a wide range, some punctuation may be never used, some punctuations such as ……”“ are used so much in Chinese.

0000    007F    C0 Controls and Basic Latin 
2000    206F    General Punctuation

There are also many Chinese-related symbols, such as Yijing Hexagram Symbols or Kanbun, but it's off-topic anyway. I write non-chinese-characters in CJK to have a better explanation of what Chinese characters are. And the ranges above already cover almost all the characters which appear in Chinese writing except math and other specialty notation.


CJK Symbols and Punctuation

 ???????<>«»??????????????[]?????????????????????????????????? ? ?

Halfwidth and Fullwidth Forms



  1. (in chinese language, notice the right side bar)
  2. (notice the bottom table)

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

extending de Almeida's answer I am editing code little bit here. since previous code was hiding gps location icon I did following way which worked better.

 <LinearLayout xmlns:android=""


    android:padding="4dp" >

        android:textColor="@drawable/textcolor_radiobutton" />
        android:background="#aaa" />

        android:textColor="@drawable/textcolor_radiobutton" />

        android:background="#aaa" />

        android:textColor="@drawable/textcolor_radiobutton" />
        android:background="#aaa" />

        android:textColor="@drawable/textcolor_radiobutton" />

    android:scrollbars="vertical" />

Copy existing project with a new name in Android Studio

When refactoring the package name in Android Studio, you may need to click the little cogwheel up to the right by the package/android/project/etc - navigator and uncheck 'compact empty middle packages' in order to see each part of the package name as an own directory. Then for individual directories do refactor.

This is important if you need to change all parts of the package name. For example, from com.example.originalproject to org.mydomain.newproject. Otherwise, the refactor/rename operation will only let you change "originalproject" to "newproject", and it will leave "com.example" unchanged. There is a good video that shows this:

How to schedule a task to run when shutting down windows

For those who prefer using the Task Scheduler, it's possible to schedule a task to run after a restart / shutdown has been initiated by setting the task to run after event 1074 in the System log in the Event Viewer has been logged. However, it's only good for very short task, which will run as long as the system is restarting / shutting down, which is usually only a few seconds.

  • From the Task Scheduler:

    Begin the task: On an event
    Log: System
    Source: USER32
    EventID: 1074

  • From the command prompt:

    schtasks /create /tn "taskname" /tr "task file" /sc onevent /ec system /mo *[system/eventid=1074]

Comment: the /ec option is available from Windows Vista and above. (thank you @t2d)

Please note that the task status can be:

The operation being requested was not performed because the user has not logged on to the network. The specified service does not exist. (0x800704DD)

However, it doesn't mean that it didn't run.

How to represent multiple conditions in a shell if statement?

Classic technique (escape metacharacters):

if [ \( "$g" -eq 1 -a "$c" = "123" \) -o \( "$g" -eq 2 -a "$c" = "456" \) ]
then echo abc
else echo efg

I've enclosed the references to $g in double quotes; that's good practice, in general. Strictly, the parentheses aren't needed because the precedence of -a and -o makes it correct even without them.

Note that the -a and -o operators are part of the POSIX specification for test, aka [, mainly for backwards compatibility (since they were a part of test in 7th Edition UNIX, for example), but they are explicitly marked as 'obsolescent' by POSIX. Bash (see conditional expressions) seems to preempt the classic and POSIX meanings for -a and -o with its own alternative operators that take arguments.

With some care, you can use the more modern [[ operator, but be aware that the versions in Bash and Korn Shell (for example) need not be identical.

for g in 1 2 3
    for c in 123 456 789
        if [[ ( "$g" -eq 1 && "$c" = "123" ) || ( "$g" -eq 2 && "$c" = "456" ) ]]
        then echo "g = $g; c = $c; true"
        else echo "g = $g; c = $c; false"

Example run, using Bash 3.2.57 on Mac OS X:

g = 1; c = 123; true
g = 1; c = 456; false
g = 1; c = 789; false
g = 2; c = 123; false
g = 2; c = 456; true
g = 2; c = 789; false
g = 3; c = 123; false
g = 3; c = 456; false
g = 3; c = 789; false

You don't need to quote the variables in [[ as you do with [ because it is not a separate command in the same way that [ is.

Isn't it a classic question?

I would have thought so. However, there is another alternative, namely:

if [ "$g" -eq 1 -a "$c" = "123" ] || [ "$g" -eq 2 -a "$c" = "456" ]
then echo abc
else echo efg

Indeed, if you read the 'portable shell' guidelines for the autoconf tool or related packages, this notation — using '||' and '&&' — is what they recommend. I suppose you could even go so far as:

if [ "$g" -eq 1 ] && [ "$c" = "123" ]
then echo abc
elif [ "$g" -eq 2 ] && [ "$c" = "456" ]
then echo abc
else echo efg

Where the actions are as trivial as echoing, this isn't bad. When the action block to be repeated is multiple lines, the repetition is too painful and one of the earlier versions is preferable — or you need to wrap the actions into a function that is invoked in the different then blocks.

window.location (JS) vs header() (PHP) for redirection

A better way to set the location in JS is via:

window.location.href = '';

Whether to use PHP or JS to manage the redirection depends on what your code is doing and how. But if you're in a position to use PHP; that is, if you're going to be using PHP to send some JS code back to the browser that simply tells the browser to go somewhere else, then logic suggests that you should cut out the middle man and tell the browser directly via PHP.

How To limit the number of characters in JTextField?

Just put this code in KeyTyped event:

    if ((jtextField.getText() + evt.getKeyChar()).length() > 20) {

Where "20" is the maximum number of characters that you want.

What is a lambda expression in C++11?

Well, one practical use I've found out is reducing boiler plate code. For example:

void process_z_vec(vector<int>& vec)
  auto print_2d = [](const vector<int>& board, int bsize)
    for(int i = 0; i<bsize; i++)
      for(int j=0; j<bsize; j++)
        cout << board[bsize*i+j] << " ";
      cout << "\n";
  // Do sth with the vec.
  // Do sth else with the vec.

Without lambda, you may need to do something for different bsize cases. Of course you could create a function but what if you want to limit the usage within the scope of the soul user function? the nature of lambda fulfills this requirement and I use it for that case.

Stop and Start a service via batch or cmd file?

or you can start remote service with this cmd : sc \\<computer> start <service>

Can I escape html special chars in javascript?

The most concise and performant way to display unencoded text is to use textContent property.

Faster than using innerHTML. And that's without taking into account escaping overhead.

document.body.textContent = 'a <b> c </b>';

How to determine the version of the C++ standard used by the compiler?

Depending on what you want to achieve, Boost.Config might help you. It does not provide detection of the standard-version, but it provides macros that let you check for support of specific language/compiler-features.

npm command to uninstall or prune unused packages in Node.js

If you're not worried about a couple minutes time to do so, a solution would be to rm -rf node_modules and npm install again to rebuild the local modules.

How would I check a string for a certain letter in Python?

If you want a version that raises an error:

"string to search".index("needle") 

If you want a version that returns -1:

"string to search".find("needle") 

This is more efficient than the 'in' syntax

Loop through childNodes

Couldn't resist to add another method, using childElementCount. It returns the number of child element nodes from a given parent, so you can loop over it.

for(var i=0, len = parent.childElementCount ; i < len; ++i){
    ... do something with parent.children[i]

How to extract Month from date in R

?month states:

Date-time must be a POSIXct, POSIXlt, Date, Period, chron, yearmon, yearqtr, zoo, zooreg, timeDate, xts, its, ti, jul, timeSeries, and fts objects.

Your object is a factor, not even a character vector (presumably because of stringsAsFactors = TRUE). You have to convert your vector to some datetime class, for instance to POSIXlt:

some_date <- c("01/02/1979", "03/04/1980")
month(as.POSIXlt(some_date, format="%d/%m/%Y"))
[1] 2 4

There's also a convenience function dmy, that can do the same (tip proposed by @Henrik):

[1] 2 4

Going even further, @IShouldBuyABoat gives another hint that dd/mm/yyyy character formats are accepted without any explicit casting:

[1] 2 4

For a list of formats, see ?strptime. You'll find that "standard unambiguous format" stands for

The default formats follow the rules of the ISO 8601 international standard which expresses a day as "2001-02-28" and a time as "14:01:02" using leading zeroes as here.

What's the difference between & and && in MATLAB?

As already mentioned by others, & is a logical AND operator and && is a short-circuit AND operator. They differ in how the operands are evaluated as well as whether or not they operate on arrays or scalars:

  • & (AND operator) and | (OR operator) can operate on arrays in an element-wise fashion.
  • && and || are short-circuit versions for which the second operand is evaluated only when the result is not fully determined by the first operand. These can only operate on scalars, not arrays.

How to get annotations of a member variable?

You can get annotations on the getter method:


Getting the annotations of a private field seems like a bad idea... what if the property isn't even backed by a field, or is backed by a field with a different name? Even ignoring those cases, you're breaking abstraction by looking at private stuff.

C programming in Visual Studio

You can use Visual Studio for C, but if you are serious about learning the newest C available, I recommend using something like Code::Blocks with MinGW-TDM version, which you can get a 32 bit version of. I use version 5.1 which supports the newest C and C++. Another benefit is that it is a better platform for creating software that can be easily ported to other platforms. If you were, for example, to code in C, using the SDL library, you could create software that could be recompiled with little to no changes to the code, on Linux, Apple and many mobile devices. The way Microsoft has been going these days, I think this is definitely the better route to take.

Can one class extend two classes?

Java does not support multiple inheritance, that's why you can't extend a class from two different classes at the same time.

Rather, use a single class to extend from, and use interfaces to include additional functionality.

Multiple connections to a server or shared resource by the same user, using more than one user name, are not allowed

Even if you remove the shared folder via net use * /del, on the server side there is still a connection up there.

In order to get around this problem which Microsoft created by design you should map the drive in a way to let windows think it's another share on another server. The simplest way to do that is to use DNS aliases or ip addresses. In your case, if your first mapping uses the ip address like \\IP\Share with your current credential, you should use something like \\ServerName\Share password /user:Domain\Username this should create a new share with the new credentials.

Microsoft call this behavior by design .. i call it just stupid design.

Converting any string into camel case

In Scott’s specific case I’d go with something like:

String.prototype.toCamelCase = function() {
    return this.replace(/^([A-Z])|\s(\w)/g, function(match, p1, p2, offset) {
        if (p2) return p2.toUpperCase();
        return p1.toLowerCase();        

'EquipmentClass name'.toCamelCase()  // -> equipmentClassName
'Equipment className'.toCamelCase()  // -> equipmentClassName
'equipment class name'.toCamelCase() // -> equipmentClassName
'Equipment Class Name'.toCamelCase() // -> equipmentClassName

The regex will match the first character if it starts with a capital letter, and any alphabetic character following a space, i.e. 2 or 3 times in the specified strings.

By spicing up the regex to /^([A-Z])|[\s-_](\w)/g it will also camelize hyphen and underscore type names.

'hyphen-name-format'.toCamelCase()     // -> hyphenNameFormat
'underscore_name_format'.toCamelCase() // -> underscoreNameFormat

Getting value of HTML text input

If your page is refreshed on submitting - yes, but only through the querystring: (You must use method "GET" then). Else, you can return its value from the php script.

Styling every 3rd item of a list using CSS?

:nth-child is the answer you are looking for.

How to run an .ipynb Jupyter Notebook from terminal?

nbconvert allows you to run notebooks with the --execute flag:

jupyter nbconvert --execute <notebook>

If you want to run a notebook and produce a new notebook, you can add --to notebook:

jupyter nbconvert --execute --to notebook <notebook>

Or if you want to replace the existing notebook with the new output:

jupyter nbconvert --execute --to notebook --inplace <notebook>

Since that's a really long command, you can use an alias:

alias nbx="jupyter nbconvert --execute --to notebook"
nbx [--inplace] <notebook>

"call to undefined function" error when calling class method


I stumbled upon this error today while testing a simple script. I am not using "class" function though so it take it with grain of salt. I was calling function before its definition & declaration ...something like this

       catch (exception $e)
            echo "$e->getMessage()";

       function foo(){
                       echo "blah blah blah";

so php was throwing me error "call to undefined function ".

This kinda seem classic programming error but may help someone in need of clue.

MySQL: Insert record if not exists in table

I had a similar problem and I needed to insert multiple if not existing. So from the examples above I came to this combination... it's here just in case somebody would need it.

Notice: I had to define name everywhere as MSSQL required it... MySQL works with * too.

INSERT INTO names (name)
  SELECT name
     SELECT 'Test 4' as name
  ) AS tmp_single
     SELECT name FROM names WHERE name = 'Test 4'
  SELECT name
     SELECT 'Test 5' as name
  ) AS tmp_single
     SELECT name FROM names WHERE name = 'Test 5'
) tmp_all;




Is there a way to use max-width and height for a background image?

It looks like you're trying to scale the background image? There's a great article in the reference bellow where you can use css3 to achieve this.

And if I miss-read the question then I humbly accept the votes down. (Still good to know though)

Please consider the following code:

#some_div_or_body { 
   background: url(images/bg.jpg) no-repeat center center fixed; 
   -webkit-background-size: cover;
   -moz-background-size: cover;
   -o-background-size: cover;
   background-size: cover;

This will work on all major browsers, of course it doesn't come easy on IE. There are some workarounds however such as using Microsoft's filters:

filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='.myBackground.jpg', sizingMethod='scale');
-ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='myBackground.jpg', sizingMethod='scale')";

There are some alternatives that can be used with a little bit peace of mind by using jQuery:


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


#bg { position: fixed; top: 0; left: 0; }
.bgwidth { width: 100%; }
.bgheight { height: 100%; }


 $(window).load(function() {    

var theWindow        = $(window),
    $bg              = $("#bg"),
    aspectRatio      = $bg.width() / $bg.height();

function resizeBg() {

    if ( (theWindow.width() / theWindow.height()) < aspectRatio ) {
    } else {




I hope this helps!

Src: Perfect Full Page Background Image

How to split a string in shell and get the last field

If your last field is a single character, you could do this:


echo ${a: -1}
echo ${a:(-1)}

Check string manipulation in bash.

Which is the correct C# infinite loop, for (;;) or while (true)?

I prefer slightly more "literate" code. I'm much more likely to do something like this in practice:

bool shouldContinue = true;
while (shouldContinue)
    // ...

    shouldContinue = CheckSomething();

What is the newline character in the C language: \r or \n?

It's \n. When you're reading or writing text mode files, or to stdin/stdout etc, you must use \n, and C will handle the translation for you. When you're dealing with binary files, by definition you are on your own.

What is the difference between Bootstrap .container and .container-fluid classes?

Both .container and .container-fluid are responsive (i.e. they change the layout based on the screen width), but in different ways (I know, the naming doesn't make it sound that way).

Short Answer:

.container is jumpy / choppy resizing, and

.container-fluid is continuous / fine resizing at width: 100%.

From a functionality perspective:

.container-fluid continuously resizes as you change the width of your window/browser by any amount, leaving no extra empty space on the sides ever, unlike how .container does. (Hence the naming: "fluid" as opposed to "digital", "discrete", "chunked", or "quantized").

.container resizes in chunks at several certain widths. In other words, it will be different specific aka "fixed" widths different ranges of screen widths.

Semantics: "fixed width"

You can see how naming confusion can arise. Technically, we can say .container is "fixed width", but it is fixed only in the sense that it doesn't resize at every granular width. It's actually not "fixed" in the sense that it's always stays at a specific pixel width, since it actually can change size.

From a fundamental perspective:

.container-fluid has the CSS property width: 100%;, so it continually readjusts at every screen width granularity.

.container-fluid {
  width: 100%;

.container has something like "width = 800px" (or em, rem etc.), a specific pixel width value at different screen widths. This of course is what causes the element width to abruptly jump to a different width when the screen width crosses a screen width threshold. And that threshold is governed by CSS3 media queries, which allow you to apply different styles for different conditions, such as screen width ranges.

@media screen and (max-width: 400px){
  .container {
    width: 123px;
@media screen and (min-width: 401px) and (max-width: 800px){

  .container {
    width: 456px;
@media screen and (min-width: 801px){
  .container {
    width: 789px;


You can make any fixed widths element responsive via media queries, not just .container elements, since media queries is exactly how .container is implemented by bootstrap in the background (see JKillian's answer for the code).

Deserialize JSON to Array or List with HTTPClient .ReadAsAsync using .NET 4.0 Task pattern

The return type depends on the server, sometimes the response is indeed a JSON array but sent as text/plain

Setting the accept headers in the request should get the correct type:

client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 

which can then be serialized to a JSON list or array. Thanks for the comment from @svick which made me curious that it should work.

The Exception I got without configuring the accept headers was System.Net.Http.UnsupportedMediaTypeException.

Following code is cleaner and should work (untested, but works in my case):

    var client = new HttpClient();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    var response = await client.GetAsync("");
    var model = await response.Content.ReadAsAsync<List<Job>>();

How to refresh materialized view in oracle

a bit late to the game, but I found a way to make the original syntax in this question work (I'm on Oracle 11g)

** first switch to schema of your MV **


alternatively you can add some options:


this actually works for me, and adding parallelism option sped my execution about 2.5 times.

More info here: How to Refresh a Materialized View in Parallel

How to replace DOM element in place using Javascript?

You can replace an HTML Element or Node using Node.replaceWith(newNode).

This example should keep all attributes and childs from origin node:

const links = document.querySelectorAll('a')

links.forEach(link => {
  const replacement = document.createElement('span')
  // copy attributes
  for (let i = 0; i < link.attributes.length; i++) {
     const attr = link.attributes[i]
     replacement.setAttribute(, attr.value)
  // copy content
  replacement.innerHTML = link.innerHTML
  // or you can use appendChild instead
  // link.childNodes.forEach(node => replacement.appendChild(node))


If you have these elements:

<a href="#link-1">Link 1</a>
<a href="#link-2">Link 2</a>
<a href="#link-3">Link 3</a>
<a href="#link-4">Link 4</a>

After running above codes, you will end up with these elements:

<span href="#link-1">Link 1</span>
<span href="#link-2">Link 2</span>
<span href="#link-3">Link 3</span>
<span href="#link-4">Link 4</span>

How can I convert bigint (UNIX timestamp) to datetime in SQL Server?

For GMT, here is the easiest way:

Select dateadd(s, @UnixTime+DATEDIFF (S, GETUTCDATE(), GETDATE()), '1970-01-01')

iPhone viewWillAppear not firing

As no answer is accepted and people (like I did) land here I give my variation. Though I am not sure that was the original problem. When the navigation controller is added as a subview to a another view you must call the viewWillAppear/Dissappear etc. methods yourself like this:

- (void) viewWillAppear:(BOOL)animated
    [super viewWillAppear:animated];

    [subNavCntlr viewWillAppear:animated];

- (void) viewWillDisappear:(BOOL)animated
    [super viewWillDisappear:animated];

    [subNavCntlr viewWillDisappear:animated];

Just to make the example complete. This code appears in my ViewController where I created and added the the navigation controller into a view that I placed on the view.

- (void)viewDidLoad {

    // This is the root View Controller
    rootTable *rootTableController = [[rootTable alloc]

    subNavCntlr = [[UINavigationController alloc]   

    [rootTableController release];

    subNavCntlr.view.frame = subNavContainer.bounds;

    [subNavContainer addSubview:subNavCntlr.view];

    [super viewDidLoad];

the .h looks like this

@interface navTestViewController : UIViewController <UINavigationControllerDelegate> {
    IBOutlet UIView *subNavContainer;
    UINavigationController *subNavCntlr;


In the nib file I have the view and below this view I have a label a image and the container (another view) where i put the controller in. Here is how it looks. I had to scramble some things as this was work for a client.

alt text

Javascript How to define multiple variables on a single line?

note you can only do this with Numbers and Strings

you could do...

var a, b, c; a = b = c = 0; //but why?

// c = 1, b = 0, a = 0;

Best way to pretty print a hash

Of all the gems I tried, show_data gem worked the best for me, I now use it extensively to log params hash in Rails pretty much all the time

C char array initialization

Interestingly enough, it is possible to initialize arrays in any way at any time in the program, provided they are members of a struct or union.

Example program:

#include <stdio.h>

struct ccont
  char array[32];

struct icont
  int array[32];

int main()
  int  cnt;
  char carray[32] = { 'A', 66, 6*11+1 };    // 'A', 'B', 'C', '\0', '\0', ...
  int  iarray[32] = { 67, 42, 25 };

  struct ccont cc = { 0 };
  struct icont ic = { 0 };

  /*  these don't work
  carray = { [0]=1 };           // expected expression before '{' token
  carray = { [0 ... 31]=1 };    // (likewise)
  carray = (char[32]){ [0]=3 }; // incompatible types when assigning to type 'char[32]' from type 'char *'
  iarray = (int[32]){ 1 };      // (likewise, but s/char/int/g)

  // but these perfectly work...
  cc = (struct ccont){ .array='a' };        // 'a', '\0', '\0', '\0', ...
  // the following is a gcc extension, 
  cc = (struct ccont){ .array={ [0 ... 2]='a' } };  // 'a', 'a', 'a', '\0', '\0', ...
  ic = (struct icont){ .array={ 42,67 } };      // 42, 67, 0, 0, 0, ...
  // index ranges can overlap, the latter override the former
  // (no compiler warning with -Wall -Wextra)
  ic = (struct icont){ .array={ [0 ... 1]=42, [1 ... 2]=67 } }; // 42, 67, 67, 0, 0, ...

  for (cnt=0; cnt<5; cnt++)
    printf("%2d %c %2d %c\n",iarray[cnt], carray[cnt],ic.array[cnt],cc.array[cnt]);

  return 0;

HTML/CSS font color vs span style

<span style="color:#ffffff; font-size:18px; line-height:35px; font-family: Calibri;">Our Activities </span>

This works for me well:) As it has been already mentioned above "The font tag has been deprecated, at least in XHTML. It always safe to use span tag. font may not give you desire results, at least in my case it didn't.

Notice: Trying to get property of non-object error

@Balamanigandan your Original Post :- PHP Notice: Trying to get property of non-object error

Your are trying to access the Null Object. From AngularJS your are not passing any Objects instead you are passing the $_GET element. Try by using $_GET['uid'] instead of $objData->token

How to get the current date and time of your timezone in Java?

I couldn't get it to work using Calendar. You have to use DateFormat

//Wednesday, July 20, 2011 3:54:44 PM PDT
DateFormat df = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL);
final String dateTimeString = df.format(new Date());

//Wednesday, July 20, 2011
df = DateFormat.getDateInstance(DateFormat.FULL);
final String dateString = df.format(new Date());

//3:54:44 PM PDT
df = DateFormat.getTimeInstance(DateFormat.FULL);
final String timeString = df.format(new Date());

How to check whether a variable is a class or not?

simplest way is to use inspect.isclass as posted in the most-voted answer.
the implementation details could be found at python2 inspect and python3 inspect.
for new-style class: isinstance(object, type)
for old-style class: isinstance(object, types.ClassType)
em, for old-style class, it is using types.ClassType, here is the code from

class _C:
    def _m(self): pass
ClassType = type(_C)

MongoDB - admin user not authorized

You can try: Using the --authenticationDatabase flag helps.

mongo --port 27017 -u "admin" -p "password" --authenticationDatabase "admin"

Docker "ERROR: could not find an available, non-overlapping IPv4 address pool among the defaults to assign to the network"

Killing the vpn is not needed.

This other comment about using a new network comes pretty close to the solution for me, and was working for a while, but I found a better way thanks to some talk over in another question

Create a network with:

docker network create your-network --subnet

Then, at the bottom of docker-compose.yaml, put this:

      name: your-network

Done. No need to add networks to all container definitions etc. and you can re-use the network with other docker-compose files as well if you'd like.

Find row where values for column is maximal in a pandas DataFrame

The idmax of the DataFrame returns the label index of the row with the maximum value and the behavior of argmax depends on version of pandas (right now it returns a warning). If you want to use the positional index, you can do the following:

max_row = df['A'].values.argmax()


import numpy as np
max_row = np.argmax(df['A'].values)

Note that if you use np.argmax(df['A']) behaves the same as df['A'].argmax().

How to set connection timeout with OkHttp

You can set a call timeout to cover the entire cycle from resolving DNS, connecting, writing the request body, server processing, and reading the response body.

val client = OkHttpClient().newBuilder().callTimeout(CALL_TIMEOUT_IN_MINUTES, TimeUnit.MINUTES).build()

Sqlite or MySql? How to decide?

Their feature sets are not at all the same. Sqlite is an embedded database which has no network capabilities (unless you add them). So you can't use it on a network.

If you need

  • Network access - for example accessing from another machine;
  • Any real degree of concurrency - for example, if you think you are likely to want to run several queries at once, or run a workload that has lots of selects and a few updates, and want them to go smoothly etc.
  • a lot of memory usage, for example, to buffer parts of your 1Tb database in your 32G of memory.

You need to use mysql or some other server-based RDBMS.

Note that MySQL is not the only choice and there are plenty of others which might be better for new applications (for example pgSQL).

Sqlite is a very, very nice piece of software, but it has never made claims to do any of these things that RDBMS servers do. It's a small library which runs SQL on local files (using locking to ensure that multiple processes don't screw the file up). It's really well tested and I like it a lot.

Also, if you aren't able to choose this correctly by yourself, you probably need to hire someone on your team who can.

An efficient way to Base64 encode a byte array?

Based on your edit and comments.. would this be what you're after?

byte[] newByteArray = UTF8Encoding.UTF8.GetBytes(Convert.ToBase64String(currentByteArray));

How to check all checkboxes using jQuery?

Trigger Click





    $('input:checkbox').prop('checked', this.checked);

If else embedding inside html

<?php if ($foo) { ?>
    <div class="mydiv">Condition is true</div>
<?php } else { ?>
    <div class="myotherdiv">Condition is false</div>
<?php } ?>

How to set app icon for Electron / Atom Shell App




You can do it for macOS, too. Ok, not through code, but with some simple steps:

  1. Find the .icns file you want to use, open it and copy it via Edit menu
  2. Find the, usually in node_modules/electron/dist
  3. Open the information window
  4. Select the icon on the top left corner (gray border around it)
  5. Paste the icon via cmd+v
  6. Enjoy your icon during development :-)

enter image description here

Actually it is a general thing not specific to electron. You can change the icon of many macOS apps like this.