Programs & Examples On #Atlcom

How to reset a timer in C#?

For clarity since some other comments are incorrect, when using System.Timers setting Enabled to true will reset the elapsed time. I just tested the behavior with the below:

Timer countDown= new Timer(3000);

    TextBox.TextDidChange += TextBox_TextDidChange;
    countdown.Elapsed += CountDown_Elapsed;

void TextBox_TextDidChange(Object sender, EventArgs e)
    countdown.Enabled = true;

void CountDown_Elapsed(object sender, EventArgs e)

I would input text to the text box repeatedly and the timer would only run 3 seconds after the last keystroke. It's hinted at in the docs as well, as you'll see: calling Timers.Start() simply sets Enabled to true.

And to be sure, which I should've just went straight to from the beginning, you'll see in the .NET reference source that if enabling an already Enabled timer it calls the private UpdateTimer() method, which internally calls Change().

How do you Hover in ReactJS? - onMouseLeave not registered during fast hover over

I know It's been a while since this question was asked but I just run into the same issue of inconsistency with onMouseLeave() What I did is to use onMouseOut() for the drop-list and on mouse leave for the whole menu, it is reliable and works every time I've tested it. I saw the events here in the docs: here is an example using

  //do what ever, for example I use it to collapse the dropdown
  let collapsing = true;
  this.setState({dropDownCollapsed : collapsing });

    <div class="dropdown" onMouseLeave={this.handleHoverOff.bind(this)}>
      <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Dropdown Example
      <span class="caret"></span></button>
      <ul class="dropdown-menu" onMouseOut={this.handleHoverOff.bind(this)}>
        <li><a href="#">bla bla 1</a></li>
        <li><a href="#">bla bla 2</a></li>
        <li><a href="#">bla bla 3</a></li>

Append text using StreamWriter

using(StreamWriter writer = new StreamWriter("debug.txt", true))
  writer.WriteLine("whatever you text is");

The second "true" parameter tells it to append.

Error Handler - Exit Sub vs. End Sub

Your ProcExit label is your place where you release all the resources whether an error happened or not. For instance:

Public Sub SubA()
  On Error Goto ProcError

  Open File for Writing

  Connection = Nothing
  Close File

  Exit Sub

  MsgBox Err.Description  
  Resume ProcExit
End Sub

How to debug PDO database queries?

Here is a function I made to return a SQL query with "resolved" parameters.

function paramToString($query, $parameters) {
    if(!empty($parameters)) {
        foreach($parameters as $key => $value) {
            preg_match('/(\?(?!=))/i', $query, $match, PREG_OFFSET_CAPTURE);
            $query = substr_replace($query, $value, $match[0][1], 1);
    return $query;
    $query = "SELECT email FROM table WHERE id = ? AND username = ?";
    $values = [1, 'Super'];

    echo paramToString($query, $values);

Assuming you execute like this

$values = array(1, 'SomeUsername');

This function DOES NOT add quotes to queries but does the job for me.

Android Gradle plugin 0.7.0: "duplicate files during packaging of APK"

I noticed this commit comment in AOSP, the solution will be to exclude some files using DSL. Probably when 0.7.1 is released.

commit e7669b24c1f23ba457fdee614ef7161b33feee69
Author: Xavier Ducrohet <--->
Date:   Thu Dec 19 10:21:04 2013 -0800

    Add DSL to exclude some files from packaging.

    This only applies to files coming from jar dependencies.
    The DSL is:

    android {
      packagingOptions {
        exclude 'META-INF/LICENSE.txt'

Transpose a range in VBA

Strictly in reference to prefacing "transpose", by the book, either one will work; i.e., application.transpose() OR worksheetfunction.transpose(), and by experience, if you really like typing, application.WorksheetFunction.Transpose() will work also-

How to get the previous page URL using JavaScript?

You can use the following to get the previous URL.

var oldURL = document.referrer;

How to change a dataframe column from String type to Double type in PySpark?

Preserve the name of the column and avoid extra column addition by using the same name as input column:

changedTypedf = joindf.withColumn("show", joindf["show"].cast(DoubleType()))

Why am I getting a " Traceback (most recent call last):" error?

At the beginning of your file you set raw_input to 0. Do not do this, at it modifies the built-in raw_input() function. Therefore, whenever you call raw_input(), it is essentially calling 0(), which raises the error. To remove the error, remove the first line of your code:

M = 1.6
# Miles to Kilometers 
# Celsius Celsius = (var1 - 32) * 5/9
# Gallons to liters Gallons = 3.6
# Pounds to kilograms Pounds = 0.45
# Inches to centimete Inches = 2.54

def intro():
    print("Welcome! This program will convert measures for you.")

def main():
    print("Select operation.")
    print("1.Miles to Kilometers")
    print("2.Fahrenheit to Celsius")
    print("3.Gallons to liters")
    print("4.Pounds to kilograms")
    print("5.Inches to centimeters")

    choice = input("Enter your choice by number: ")

    if choice == '1':

    elif choice == '2':

    elif choice == '3':

    elif choice == '4':

    elif choice == '5':


def convertMK():
    input_M = float(raw_input(("Miles: ")))
    M_conv = (M) * input_M
    print("Kilometers: %f\n" % M_conv)
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
    elif restart == 'n':
        print("I didn't quite understand that answer. Terminating.")

def converCF():
    input_F = float(raw_input(("Fahrenheit: ")))
    F_conv = (input_F - 32) * 5/9
    print("Celcius: %f\n") % F_conv
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
    elif restart == 'n':
        print("I didn't quite understand that answer. Terminating.")

def convertGL():
    input_G = float(raw_input(("Gallons: ")))
    G_conv = input_G * 3.6
    print("Centimeters: %f\n" % G_conv)
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
    elif restart == 'n':
        print ("I didn't quite understand that answer. Terminating.")

def convertPK():
    input_P = float(raw_input(("Pounds: ")))
    P_conv = input_P * 0.45
    print("Centimeters: %f\n" % P_conv)
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
    elif restart == 'n':
        print ("I didn't quite understand that answer. Terminating.")

def convertIC():
    input_cm = float(raw_input(("Inches: ")))
    inches_conv = input_cm * 2.54
    print("Centimeters: %f\n" % inches_conv)
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
    elif restart == 'n':
        print ("I didn't quite understand that answer. Terminating.")

def end():
    print("This program will close.")


Using in my project (Eclipse)

You need to add this in your build.gradle:

dependencies {
    compile ''

And then Sync Project with Gradle Files. Finally, you can use CardView as it's described here.

How to set time to 24 hour format in Calendar

You can set the calendar to use only AM or PM using

calendar.set(Calendar.AM_PM, int);

0 = AM

1 = PM

Hope this helps

PDF Editing in PHP?

If you need really simple PDFs, then Zend or FPDF is fine. However I find them difficult and frustrating to work with. Also, because of the way the API works, there's no good way to separate content from presentation from business logic.

For that reason, I use dompdf, which automatically converts HTML and CSS to PDF documents. You can lay out a template just as you would for an HTML page and use standard HTML syntax. You can even include an external CSS file. The library isn't perfect and very complex markup or css sometimes gets mangled, but I haven't found anything else that works as well.

Java generics - get class?

I'm not 100% sure if this works in all cases (needs at least Java 1.5):

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

public class Main 
    public class A

    public class B extends A

    public Map<A, B> map = new HashMap<Main.A, Main.B>();

    public static void main(String[] args) 

            Field field = Main.class.getField("map");           
            System.out.println("Field " + field.getName() + " is of type " + field.getType().getSimpleName());

            Type genericType = field.getGenericType();

            if(genericType instanceof ParameterizedType)
                ParameterizedType type = (ParameterizedType) genericType;               
                Type[] typeArguments = type.getActualTypeArguments();

                for(Type typeArgument : typeArguments) 
                    Class<?> classType = ((Class<?>)typeArgument);                  
                    System.out.println("Field " + field.getName() + " has a parameterized type of " + classType.getSimpleName());
        catch(Exception e)

This will output:

Field map is of type Map
Field map has a parameterized type of A
Field map has a parameterized type of B

How to reset (clear) form through JavaScript?

Use JavaScript function reset():


What's the fastest way to convert String to Number in JavaScript?

The fastest way is using -0:

const num = "12.34" - 0;

Show a child form in the centre of Parent form in C#

Assuming your code is running inside your parent form, then something like this is probably what you're looking for:

loginForm = new SubLogin();
loginForm.StartPosition = FormStartPosition.CenterParent

For the record, there's also a Form.CenterToParent() function, if you need to center it after creation for whatever reason too.

How to convert datetime format to date format in crystal report using C#?

if it is just a format issue use ToShortDateString()

How can I write data attributes using Angular?

Use attribute binding syntax instead

<ol class="viewer-nav"><li *ngFor="let section of sections" 
    []="section.value">{{ section.text }}</li>  


<ol class="viewer-nav"><li *ngFor="let section of sections""{{section.value}}">{{ section.text }}</li>  

See also :

Deep copy in ES6 using the spread syntax

const cloneData = (dataArray) => {
    newData= []
    dataArray.forEach((value) => {
    return newData
  • a = [{name:"siva"}, {name:"siva1"}] ;
  • b = myCopy(a)
  • b === a // false`

Converting char[] to byte[]

Convert without creating String object:

import java.nio.CharBuffer;
import java.nio.ByteBuffer;
import java.util.Arrays;

byte[] toBytes(char[] chars) {
  CharBuffer charBuffer = CharBuffer.wrap(chars);
  ByteBuffer byteBuffer = Charset.forName("UTF-8").encode(charBuffer);
  byte[] bytes = Arrays.copyOfRange(byteBuffer.array(),
            byteBuffer.position(), byteBuffer.limit());
  Arrays.fill(byteBuffer.array(), (byte) 0); // clear sensitive data
  return bytes;


char[] chars = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
byte[] bytes = toBytes(chars);
/* do something with chars/bytes */
Arrays.fill(chars, '\u0000'); // clear sensitive data
Arrays.fill(bytes, (byte) 0); // clear sensitive data

Solution is inspired from Swing recommendation to store passwords in char[]. (See Why is char[] preferred over String for passwords?)

Remember not to write sensitive data to logs and ensure that JVM won't hold any references to it.

The code above is correct but not effective. If you don't need performance but want security you can use it. If security also not a goal then do simply String.getBytes. Code above is not effective if you look down of implementation of encode in JDK. Besides you need to copy arrays and create buffers. Another way to convert is inline all code behind encode (example for UTF-8):

val xs: Array[Char] = "A ß € ?  ".toArray
val len = xs.length
val ys: Array[Byte] = new Array(3 * len) // worst case
var i = 0; var j = 0 // i for chars; j for bytes
while (i < len) { // fill ys with bytes
  val c = xs(i)
  if (c < 0x80) {
    ys(j) = c.toByte
    i = i + 1
    j = j + 1
  } else if (c < 0x800) {
    ys(j) = (0xc0 | (c >> 6)).toByte
    ys(j + 1) = (0x80 | (c & 0x3f)).toByte
    i = i + 1
    j = j + 2
  } else if (Character.isHighSurrogate(c)) {
    if (len - i < 2) throw new Exception("overflow")
    val d = xs(i + 1)
    val uc: Int = 
      if (Character.isLowSurrogate(d)) {
        Character.toCodePoint(c, d)
      } else {
        throw new Exception("malformed")
    ys(j) = (0xf0 | ((uc >> 18))).toByte
    ys(j + 1) = (0x80 | ((uc >> 12) & 0x3f)).toByte
    ys(j + 2) = (0x80 | ((uc >>  6) & 0x3f)).toByte
    ys(j + 3) = (0x80 | (uc & 0x3f)).toByte
    i = i + 2 // 2 chars
    j = j + 4
  } else if (Character.isLowSurrogate(c)) {
    throw new Exception("malformed")
  } else {
    ys(j) = (0xe0 | (c >> 12)).toByte
    ys(j + 1) = (0x80 | ((c >> 6) & 0x3f)).toByte
    ys(j + 2) = (0x80 | (c & 0x3f)).toByte
    i = i + 1
    j = j + 3
// check
println(new String(ys, 0, j, "UTF-8"))

Excuse me for using Scala language. If you have problems with converting this code to Java I can rewrite it. What about performance always check on real data (with JMH for example). This code looks very similar to what you can see in JDK[2] and Protobuf[3].

How can I link a photo in a Facebook album to a URL

Unfortunately, no. This feature is not available for facebook albums.

No log4j2 configuration file found. Using default configuration: logging only errors to the console

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Console name="Console" target="SYSTEM_OUT">
  <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
<Root level="DEBUG">
  <AppenderRef ref="Console"/>
  1. Create a new Text document and copy-paste the above code and save it as log4j2.xml.

  2. Now copy this log4j2.xml file and paste it under your src folder of your Java project.

  3. Run your java program again, you will see error is gone.

How to move a marker in Google Maps API

Here is the full code with no errors

        <!DOCTYPE html>
        <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
        <style type="text/css">
          html { height: 100% }
          body { height: 100%; margin: 0; padding: 0 }
          #map_canvas { height: 100% }

        height: 400px; 
        width: 500px;

        <script type="text/javascript">
        function initialize() {

            var myLatLng = new google.maps.LatLng( 17.3850, 78.4867 ),
                myOptions = {
                    zoom: 5,
                    center: myLatLng,
                    mapTypeId: google.maps.MapTypeId.ROADMAP
                map = new google.maps.Map( document.getElementById( 'map-canvas' ), myOptions ),
                marker = new google.maps.Marker( {icon: {
                    url: '',
                    // This marker is 20 pixels wide by 32 pixels high.
                    size: new google.maps.Size(20, 32),
                    // The origin for this image is (0, 0).
                    origin: new google.maps.Point(0, 0),
                    // The anchor for this image is the base of the flagpole at (0, 32).
                    anchor: new google.maps.Point(0, 32)
                }, position: myLatLng, map: map} );

            marker.setMap( map );
            moveBus( map, marker );


        function moveBus( map, marker ) {
            setTimeout(() => {
                marker.setPosition( new google.maps.LatLng( 12.3850, 77.4867 ) );
                map.panTo( new google.maps.LatLng( 17.3850, 78.4867 ) );
            }, 1000)



        <body onload="initialize()">
        <script type="text/javascript">

        <script src=""></script>
        <div id="map-canvas" style="height: 500px; width: 500px;"></div>


How do I import a CSV file in R?

You would use the read.csv function; for example:

dat = read.csv("spam.csv", header = TRUE)

You can also reference this tutorial for more details.

Note: make sure the .csv file to read is in your working directory (using getwd()) or specify the right path to file. If you want, you can set the current directory using setwd.

what is <meta charset="utf-8">?

That meta tag basically specifies which character set a website is written with.

Here is a definition of UTF-8:

UTF-8 (U from Universal Character Set + Transformation Format—8-bit) is a character encoding capable of encoding all possible characters (called code points) in Unicode. The encoding is variable-length and uses 8-bit code units.

Rails Object to hash


as_json has very flexible way to configure complex object according to model relations


Model campaign belongs to shop and has one list

Model list has many list_tasks and each of list_tasks has many comments

We can get one json which combines all those data easily.

        except: [:created_at, :updated_at],
        include: {
            shop: {
                except: [:created_at, :updated_at, :customer_id],
                include: {customer: {except: [:created_at, :updated_at]}}},
            list: {
                except: [:created_at, :updated_at, :observation_id],
                include: {
                    list_tasks: {
                        except: [:created_at, :updated_at],
                        include: {comments: {except: [:created_at, :updated_at]}}
        methods: :tags

Notice methods: :tags can help you attach any additional object which doesn't have relations with others. You just need to define a method with name tags in model campaign. This method should return whatever you need (e.g. Tags.all)

Official documentation for as_json

How to list containers in Docker

To display only running containers

docker ps

To show all containers (includes all states)

docker ps -a

To show the latest created container (includes all states)

docker ps -l

To show n last created containers (includes all states)

docker ps -n=-1

To display total file sizes

docker ps -s

In the new version of Docker, commands are updated, and some management commands are added:

docker container ls

List all the running containers.

docker container ls -a

Include .so library in apk in android studio

I've tried the solution presented in the accepted answer and it did not work for me. I wanted to share what DID work for me as it might help someone else. I've found this solution here.

Basically what you need to do is put your .so files inside a a folder named lib (Note: it is not libs and this is not a mistake). It should be in the same structure it should be in the APK file.

In my case it was:
|--|--| files.

So I've made a lib folder and inside it an armeabi folder where I've inserted all the needed .so files. I then zipped the folder into a .zip (the structure inside the zip file is now lib/armeabi/*.so) I renamed the .zip file into armeabi.jar and added the line compile fileTree(dir: 'libs', include: '*.jar') into dependencies {} in the gradle's build file.

This solved my problem in a rather clean way.

Batch file for PuTTY/PSFTP file transfer automation

You need to store the psftp script (lines from open to bye) into a separate file and pass that to psftp using -b switch:

cd "C:\Program Files (x86)\PuTTY"
psftp -b "C:\path\to\script\script.txt"


EDIT: For username+password: As you cannot use psftp commands in a batch file, for the same reason, you cannot specify the username and the password as psftp commands. These are inputs to the open command. While you can specify the username with the open command (open <user>@<IP>), you cannot specify the password this way. This can be done on a psftp command line only. Then it's probably cleaner to do all on the command-line:

cd "C:\Program Files (x86)\PuTTY"
psftp -b script.txt <user>@<IP> -pw <PW>

And remove the open, <user> and <PW> lines from your script.txt.


What you are doing atm is that you run psftp without any parameter or commands. Once you exit it (like by typing bye), your batch file continues trying to run open command (and others), what Windows shell obviously does not understand.

If you really want to keep everything in one file (the batch file), you can write commands to psftp standard input, like:

    echo cd ...
    echo lcd ...
    echo put
) | psftp -b script.txt <user>@<IP> -pw <PW>

How to pass data using NotificationCenter in swift 3.0 and NSNotificationCenter in swift 2.0?

In swift 4.2 I used following code to show and hide code using NSNotification

 @objc func keyboardWillShow(notification: NSNotification) {
    if let keyboardSize = (notification.userInfo? [UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
        let keyboardheight = keyboardSize.height

Using varchar(MAX) vs TEXT on SQL Server

For large text, the full text index is much faster. But you can full text index varchar(max)as well.

CSS: image link, change on hover

If you give generally give a span the property display:block, it'll then behave like a div, i.e you can set width and height.

You can also skip the div or span and just set the a the to display: block and apply the backgound style to it.

<a href="" class="myImage"><!----></a>

      .myImage {display: block; width: 160px; height: 20px; margin:0 0 10px 0; background: url(image.png) center top no-repeat;}

ImportError: DLL load failed: %1 is not a valid Win32 application

All you have to do is copy the cv2.pyd file from the x86 folder (C:\opencv\build\python\2.7\x86\ for example) to C:\Python27\Lib\site-packages\ , not from the x64 folder.

Hope that help you.

Which Eclipse version should I use for an Android app?

I would recommend at least Eclipse Indigo (v 3.7) for Android Development because even though a minimum of Helios (v 3.6) is required for ADT 22.0.1 as explained here...

... Indigo is required for Android NDK development using CDT, as explained here:

Converting HTML files to PDF

If you have the funding, nothing beats Prince XML as this video shows

Android : How to set onClick event for Button in List item of ListView

This has been discussed in many posts but still I could not figure out a solution with:


Below solution will work with any of the ui components : Button, ImageButtons, ImageView, Textview. LinearLayout, RelativeLayout clicks inside a listview cell and also will respond to onItemClick:

Adapter class - getview():

        public View getView(int position, View convertView, ViewGroup parent) {
            View view = convertView;
            if (view == null) {
                view = lInflater.inflate(R.layout.my_ref_row, parent, false);
            final Organization currentOrg = organizationlist.get(position).getOrganization();

            TextView name = (TextView) view.findViewById(;
            Button btn = (Button) view.findViewById(;
            btn.setOnClickListener(new OnClickListener() {

                public void onClick(View v) {




In this was you can get the button clicked object to the activity. (Specially when you want the button to act as a check box with selected and non-selected states):

    public void doSelection(Organization currentOrg) {
        Log.e("Btn clicked ", currentOrg.getOrgName());
        if (currentOrg.isSelected() == false) {
        } else {


split string only on first instance - java

Yes you can, just pass the integer param to the split method

String stSplit = "apple=fruit table price=5"

stSplit.split("=", 2);

Here is a java doc reference : String#split(java.lang.String, int)

Excel formula to get week number in month (having Monday)

Jonathan from the ExcelCentral forums suggests:


This formula extracts the week of the year [...] and then subtracts it from the week of the first day in the month to get the week of the month. You can change the day that weeks begin by changing the second argument of both WEEKNUM functions (set to 2 [for Monday] in the above example). For weeks beginning on Sunday, use:


For weeks beginning on Tuesday, use:



I like it better because it's using the built in week calculation functionality of Excel (WEEKNUM).

How to decrypt Hash Password in Laravel

Short answer is that you don't 'decrypt' the password (because it's not encrypted - it's hashed).

The long answer is that you shouldn't send the user their password by email, or any other way. If the user has forgotten their password, you should send them a password reset email, and allow them to change their password on your website.

Laravel has most of this functionality built in (see the Laravel documentation - I'm not going to replicate it all here. Also available for versions 4.2 and 5.0 of Laravel).

For further reading, check out this 'blogoverflow' post: Why passwords should be hashed.

How to initailize byte array of 100 bytes in java with all 0's

A new byte array will automatically be initialized with all zeroes. You don't have to do anything.

The more general approach to initializing with other values, is to use the Arrays class.

import java.util.Arrays;

byte[] bytes = new byte[100];
Arrays.fill( bytes, (byte) 1 );

Xcode/Simulator: How to run older iOS version?

Choosing older simulator versions is not obvious in Xcode 3.2.5. Older Xcodes had separate lists of "iOS Device SDKs" and "iOS Simulator SDKs" in the "Base SDK" build setting popup menu, but in Xcode 3.2.5 these have been replaced with a single "iOS SDKs" list that only offers 4.2 and "latest".

If you create a new default iOS project, it defaults to 4.2 for both Base SDK and Deployment Target, and in the "Overview" popup in the project's top-left corner, only the 4.2 Simulator is available.

To run an older iOS simulator, you must choose an older iOS version in the "iOS Deployment Target" build setting popup. Only then will the "Overview" popup offer older Simulators: back to 4.0 for iPhone and to 3.2 for iPad.

Vue 2 - Mutating props vue-warn

The answer is simple, you should break the direct prop mutation by assigning the value to some local component variables(could be data property, computed with getters, setters, or watchers).

Here's a simple solution using the watcher.



  export default {
  props: {
    value: {
      type: String,
      default: '',
  data() {
    return {
      input: '',
  watch: {
    value: {
      handler(after) {
        this.input = after;
      immediate: true,
  methods: {
    updateInput() {
      this.$emit('input', this.input);

It's what I use to create any data input components and it works just fine. Any new data sent(v-model(ed)) from parent will be watched by the value watcher and is assigned to the input variable and once the input is received, we can catch that action and emit input to parent suggesting that data is input from the form element.

'MOD' is not a recognized built-in function name

It can be done using % operator. i.e. SELECT 50 % 5

Oracle date format picture ends before converting entire input string

What you're trying to insert is not a date, I think, but a string. You need to use to_date() function, like this:

insert into table t1 (id, date_field) values (1, to_date('20.06.2013', ''));

Cannot find firefox binary in PATH. Make sure firefox is installed

File pathToBinary = new File("C:\\user\\Programme\\FirefoxPortable\\App\\Firefox\\firefox.exe");
FirefoxBinary ffBinary = new FirefoxBinary(pathToBinary);
FirefoxProfile firefoxProfile = new FirefoxProfile();       
WebDriver driver = new FirefoxDriver(ffBinary,firefoxProfile);

Unit testing void methods?

Test its side-effects. This includes:

  • Does it throw any exceptions? (If it should, check that it does. If it shouldn't, try some corner cases which might if you're not careful - null arguments being the most obvious thing.)
  • Does it play nicely with its parameters? (If they're mutable, does it mutate them when it shouldn't and vice versa?)
  • Does it have the right effect on the state of the object/type you're calling it on?

Of course, there's a limit to how much you can test. You generally can't test with every possible input, for example. Test pragmatically - enough to give you confidence that your code is designed appropriately and implemented correctly, and enough to act as supplemental documentation for what a caller might expect.

Find and Replace text in the entire table using a MySQL query

I believe "swapnesh" answer to be the best ! Unfortunately I couldn't execute it in phpMyAdmin ( who although illogical (and tried several things) it kept saying that a new statement was found and that no delimiter was found…

Thus I came with the following solution that might be usefull if you exeprience the same issue and have no other access to the database than PMA…

UPDATE `wp_posts` AS `toUpdate`,
(SELECT `ID`,REPLACE(`guid`,'http://old.tld','http://new.tld') AS `guid` 
 FROM `wp_posts` WHERE `guid` LIKE 'http://old.tld%') AS `updated`
SET `toUpdate`.`guid`=`updated`.`guid`
WHERE `toUpdate`.`ID`=`updated`.`ID`;

To test the expected result you may want to use :

SELECT `toUpdate`.`guid` AS `old guid`,`updated`.`guid` AS `new guid`
FROM `wp_posts` AS `toUpdate`,
(SELECT `ID`,REPLACE(`guid`,'http://old.tld','http://new.tld') AS `guid`
 FROM `wp_posts` WHERE `guid` LIKE 'http://old.tld%') AS `updated`
WHERE `toUpdate`.`ID`=`updated`.`ID`;

jQuery event for images loaded

  function CheckImageLoadingState()
     var counter = 0;
     var length = 0;

     jQuery('#siteContent img').each(function() 

     jQuery('#siteContent img').each(function() 
           }).each(function() {
              if(this.complete) jQuery(this).load();
           if(counter === length) 
              //function to call when all the images have been loaded

Android: I lost my android key store, what should I do?

No, there is no chance to do that. You just learned how important a backup can be.

Android Studio - No JVM Installation found

Just make sure that the installed version of both, Android Studio and JDK, are of either 32-bit or 64-bit. If JDK is of 32-bit and Android Studio of 64-bit or vice-verse, then it won't work though you set up JAVA_HOME.

How to make parent wait for all child processes to finish?

Use waitpid() like this:

pid_t childPid;  // the child process that the execution will soon run inside of. 
childPid = fork();

if(childPid == 0)  // fork succeeded 
   // Do something   

else if(childPid < 0)  // fork failed 
   // log the error

else  // Main (parent) process after fork succeeds 
    int returnStatus;    
    waitpid(childPid, &returnStatus, 0);  // Parent process waits here for child to terminate.

    if (returnStatus == 0)  // Verify child process terminated without error.  
       printf("The child process terminated normally.");    

    if (returnStatus == 1)      
       printf("The child process terminated with an error!.");    

Float to String format specifier

Use ToString() with this format:

12345.678901.ToString("0.0000"); // outputs 12345.6789
12345.0.ToString("0.0000"); // outputs 12345.0000

Put as much zero as necessary at the end of the format.

jquery append div inside div with id and manipulate

Why not go even simpler with either one of these options:

$("#box").html('<div id="myid" style="display:block; float:left;width:'+width+'px; height:'+height+'px; margin-top:'+positionY+'px;margin-left:'+positionX+'px;border:1px dashed #CCCCCC;"></div>');

Or, if you want to append it to existing content:

$("#box").append('<div id="myid" style="display:block; float:left;width:'+width+'px; height:'+height+'px; margin-top:'+positionY+'px;margin-left:'+positionX+'px;border:1px dashed #CCCCCC;"></div>');

Note: I put the id="myid" right into the HTML string rather than using separate code to set it.

Both the .html() and .append() jQuery methods can take a string of HTML so there's no need to use a separate step for creating the objects.

onKeyDown event not working on divs in React

Using the div trick with tab_index="0" or tabIndex="-1" works, but any time the user is focusing a view that's not an element, you get an ugly focus-outline on the entire website. This can be fixed by setting the CSS for the div to use outline: none in the focus.

Here's the implementation with styled components:

import styled from "styled-components"

const KeyReceiver = styled.div`
  &:focus {
    outline: none;

and in the App class:

  render() {
    return (      
      <KeyReceiver onKeyDown={this.handleKeyPress} tabIndex={-1}>
          Display stuff...

how to transfer a file through SFTP in java?

Try this code.

public void send (String fileName) {
    String SFTPHOST = "host:IP";
    int SFTPPORT = 22;
    String SFTPUSER = "username";
    String SFTPPASS = "password";
    String SFTPWORKINGDIR = "file/to/transfer";

    Session session = null;
    Channel channel = null;
    ChannelSftp channelSftp = null;
    System.out.println("preparing the host information for sftp.");

    try {
        JSch jsch = new JSch();
        session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT);
        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        System.out.println("Host connected.");
        channel = session.openChannel("sftp");
        System.out.println("sftp channel opened and connected.");
        channelSftp = (ChannelSftp) channel;;
        File f = new File(fileName);
        channelSftp.put(new FileInputStream(f), f.getName());"File transfered successfully to host.");
    } catch (Exception ex) {
        System.out.println("Exception found while tranfer the response.");
    } finally {
        System.out.println("sftp Channel exited.");
        System.out.println("Channel disconnected.");
        System.out.println("Host Session disconnected.");

Out-File -append in Powershell does not produce a new line and breaks string into characters

Out-File defaults to unicode encoding which is why you are seeing the behavior you are. Use -Encoding Ascii to change this behavior. In your case

Out-File -Encoding Ascii -append textfile.txt. 

Add-Content uses Ascii and also appends by default.

"This is a test" | Add-Content textfile.txt.

As for the lack of newline: You did not send a newline so it will not write one to file.

How can I get table names from an MS Access Database?

Here is an updated answer which works in Access 2010 VBA using Data Access Objects (DAO). The table's name is held in TableDef.Name. The collection of all table definitions is held in TableDefs. Here is a quick example of looping through the table names:

Dim db as Database
Dim td as TableDef
Set db = CurrentDb()
For Each td In db.TableDefs
Next td

Difference between View and ViewGroup in Android

View is a basic building block of UI (User Interface) in android. A view is a small rectangular box which responds to user inputs. Eg: EditText, Button, CheckBox, etc..

ViewGroup is a invisible container of other views (child views) and other viewgroups. Eg: LinearLayout is a viewgroup which can contain other views in it.

ViewGroup is a special kind of view which is extended from View as its base class. ViewGroup is the base class for layouts.

as name states View is singular and the group of Views is the ViewGroup.

more info:

MVC4 HTTP Error 403.14 - Forbidden

I had set the new app's application pool to the DefaultAppPool in IIS which obviously is using the Classic pipeline with .NET v.2.0.

To solve the problem I created a new App Pool using the Integrated pipeline and .NET v4.0. just for this new application and then everything started working as expected.

Don't forget to assign this new app pool to the application. Select the application in IIS, click Basic Settings and then pick the new app pool for the app.

Excel formula to display ONLY month and year?

Try the formula


Get all table names of a particular database by SQL query?

Stolen from here:

FROM sys.Tables

How to check if the key pressed was an arrow key in Java KeyListener?

You should be using things like: KeyEvent.VK_UP instead of the actual code.

How are you wanting to refactor it? What is the goal of the refactoring?

How to create an array for JSON using PHP?

Easy peasy lemon squeezy:

$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);

echo json_encode($arr);

There's a post by andyrusterholz at g-m-a-i-l dot c-o-m on the aforementioned page that can also handle complex nested arrays (if that's your thing).

installing python packages without internet and using source code as .tar.gz and .whl

This isn't an answer. I was struggling but then realized that my install was trying to connect to internet to download dependencies.

So, I downloaded and installed dependencies first and then installed with below command. It worked

python -m pip install filename.tar.gz

open() in Python does not create a file if it doesn't exist

If you want to open it to read and write, I'm assuming you don't want to truncate it as you open it and you want to be able to read the file right after opening it. So this is the solution I'm using:

file = open('myfile.dat', 'a+'), 0)

How to run Maven from another directory (without cd to project dir)?

For me, works this way: mvn -f /path/to/pom.xml [goals]

Java Wait and Notify: IllegalMonitorStateException

You can't wait() on an object unless the current thread owns that object's monitor. To do that, you must synchronize on it:

class Runner implements Runnable
  public void run()
      synchronized(Main.main) {
    } catch (InterruptedException e) {}
    System.out.println("Runner away!");

The same rule applies to notify()/notifyAll() as well.

The Javadocs for wait() mention this:

This method should only be called by a thread that is the owner of this object's monitor. See the notify method for a description of the ways in which a thread can become the owner of a monitor.


IllegalMonitorStateException – if the current thread is not the owner of this object's monitor.

And from notify():

A thread becomes the owner of the object's monitor in one of three ways:

  • By executing a synchronized instance method of that object.
  • By executing the body of a synchronized statement that synchronizes on the object.
  • For objects of type Class, by executing a synchronized static method of that class.

Java - escape string to prevent SQL injection

The only way to prevent SQL injection is with parameterized SQL. It simply isn't possible to build a filter that's smarter than the people who hack SQL for a living.

So use parameters for all input, updates, and where clauses. Dynamic SQL is simply an open door for hackers, and that includes dynamic SQL in stored procedures. Parameterize, parameterize, parameterize.

How to exit a function in bash

If you want to return from an outer function with an error without exiting you can use this trick:

do-something-complex() {
  # Using `return` here would only return from `fail`, not from `do-something-complex`.
  # Using `exit` would close the entire shell.
  # So we (ab)use a different feature. :)
  fail() { : "${__fail_fast:?$1}"; }

  nested-func() {
      try-this || fail "This didn't work"
      try-that || fail "That didn't work"

Trying it out:

$ do-something-complex
try-this: command not found
bash: __fail_fast: This didn't work

This has the added benefit/drawback that you can optionally turn off this feature: __fail_fast=x do-something-complex.

Note that this causes the outermost function to return 1.

What is the best way to check for Internet connectivity using .NET?

private bool ping()
    System.Net.NetworkInformation.Ping pingSender = new System.Net.NetworkInformation.Ping();
    System.Net.NetworkInformation.PingReply reply = pingSender.Send(address);
    if (reply.Status == System.Net.NetworkInformation.IPStatus.Success)
        return true;
        return false;

Java double.MAX_VALUE?

Double.MAX_VALUE is the maximum value a double can represent (somewhere around 1.7*10^308).

This should end in some calculation problems, if you try to subtract the maximum possible value of a data type.

Even though when you are dealing with money you should never use floating point values especially while rounding this can cause problems (you will either have to much or less money in your system then).

XAMPP Apache Webserver localhost not working on MAC OS


sudo /Applications/XAMPP/xamppfiles/bin/apachectl start

in terminal

Change a web.config programmatically with C# (.NET)

Since web.config file is xml file you can open web.config using xmldocument class. Get the node from that xml file that you want to update and then save xml file.

here is URL that explains in more detail how you can update web.config file programmatically.

Note: if you make any changes to web.config, ASP.NET detects that changes and it will reload your application(recycle application pool) and effect of that is data kept in Session, Application, and Cache will be lost (assuming session state is InProc and not using a state server or database).

Checking for multiple conditions using "when" on single task in ansible

Adding to answer, which will probably fix your error.

Strictly answering your question, I just want to point out that the when: statement is probably correct, but would look easier to read in multiline and still fulfill your logic:

  - sshkey_result.rc == 1
  - github_username is undefined or 
    github_username |lower == 'none'

How can I setup & run PhantomJS on Ubuntu?

If you want to use phantomjs easily, you can use it at You can get the result just by http request.

How can I see the specific value of the sql_mode?

It's only blank for you because you have not set the sql_mode. If you set it, then that query will show you the details:

mysql> SELECT @@sql_mode;
| @@sql_mode |
|            |
1 row in set (0.00 sec)

mysql> set sql_mode=ORACLE;
Query OK, 0 rows affected (0.00 sec)

mysql> SELECT @@sql_mode;
| @@sql_mode                                                                                                           |
1 row in set (0.00 sec)

How to name Dockerfiles

I think you should have a directory per container with a Dockerfile (no extension) in it. For example:


When you build just use the directory name, Docker will find the Dockerfile. e.g:

docker build -f ./db .

How to output git log with the first line only?

if you want to always use git log in such way you could add git alias by

git config --global alias.log log --oneline

after that git log will print what normally would be printed by git log --oneline

SQL: How to perform string does not equal

NULL-safe condition would looks like:

select * from table
where NOT (tester <=> 'username')

Getting all names in an enum as a String[]

Here's one-liner for any enum class:

public static String[] getNames(Class<? extends Enum<?>> e) {

Pre Java 8 is still a one-liner, albeit less elegant:

public static String[] getNames(Class<? extends Enum<?>> e) {
    return Arrays.toString(e.getEnumConstants()).replaceAll("^.|.$", "").split(", ");

That you would call like this:

String[] names = getNames(State.class); // any other enum class will work

If you just want something simple for a hard-coded enum class:

public static String[] names() {
    return Arrays.toString(State.values()).replaceAll("^.|.$", "").split(", ");

CSS3 Transparency + Gradient

New syntax has been supported for a while by all modern browsers (starting from Chrome 26, Opera 12.1, IE 10 and Firefox 16):

background: linear-gradient(to bottom, rgba(0, 0, 0, 1), rgba(0, 0, 0, 0));

This renders a gradient, starting from solid black at the top, to fully transparent at the bottom.

Documentation on MDN.

Can an Android NFC phone act as an NFC tag?

You can definitely make an Android phone write to a tag reader using the NDEFPush functionality in the peer-to-peer support - but you will need to write the code on the tag reader side to use peer-to-peer as well (llcp).

Ordering by specific field value first

do this:

SELECT * FROM table ORDER BY column `name`+0 ASC

Appending the +0 will mean that:

0, 10, 11, 2, 3, 4

becomes :

0, 2, 3, 4, 10, 11

Search input with an icon Bootstrap 4

you can also do in this way using input-group

<div class="input-group">
  <input class="form-control"
         placeholder="I can help you to find anything you want!">
  <div class="input-group-addon" ><i class="fa fa-search"></i></div>


php/mySQL on XAMPP: password for phpMyAdmin and mysql_connect different?

if you open localhost/phpmyadmin you will find a tab called "User accounts". There you can define all your users that can access the mysql database, set their rights and even limit from where they can connect.

How to skip the OPTIONS preflight request?

The preflight is being triggered by your Content-Type of application/json. The simplest way to prevent this is to set the Content-Type to be text/plain in your case. application/x-www-form-urlencoded & multipart/form-data Content-Types are also acceptable, but you'll of course need to format your request payload appropriately.

If you are still seeing a preflight after making this change, then Angular may be adding an X-header to the request as well.

Or you might have headers (Authorization, Cache-Control...) that will trigger it, see:

How to configure socket connect timeout

I just wrote an extension class in order to allow timeouts in connections. Use it exactly as you would use the standard Connect() methods, with an extra parameter named timeout.

using System;
using System.Net;
using System.Net.Sockets;

/// <summary>
/// Extensions to Socket class
/// </summary>
public static class SocketExtensions
    /// <summary>
    /// Connects the specified socket.
    /// </summary>
    /// <param name="socket">The socket.</param>
    /// <param name="host">The host.</param>
    /// <param name="port">The port.</param>
    /// <param name="timeout">The timeout.</param>
    public static void Connect(this Socket socket, string host, int port, TimeSpan timeout)
        AsyncConnect(socket, (s, a, o) => s.BeginConnect(host, port, a, o), timeout);

    /// <summary>
    /// Connects the specified socket.
    /// </summary>
    /// <param name="socket">The socket.</param>
    /// <param name="addresses">The addresses.</param>
    /// <param name="port">The port.</param>
    /// <param name="timeout">The timeout.</param>
    public static void Connect(this Socket socket, IPAddress[] addresses, int port, TimeSpan timeout)
        AsyncConnect(socket, (s, a, o) => s.BeginConnect(addresses, port, a, o), timeout);

    /// <summary>
    /// Asyncs the connect.
    /// </summary>
    /// <param name="socket">The socket.</param>
    /// <param name="connect">The connect.</param>
    /// <param name="timeout">The timeout.</param>
    private static void AsyncConnect(Socket socket, Func<Socket, AsyncCallback, object, IAsyncResult> connect, TimeSpan timeout)
        var asyncResult = connect(socket, null, null);
        if (!asyncResult.AsyncWaitHandle.WaitOne(timeout))
            catch (SocketException)
            { }
            catch (ObjectDisposedException)
            { }

ggplot2 plot without axes, legends, etc

Re: changing opts to theme etc (for lazy folks):


Credentials for the SQL Server Agent service are invalid

the button 'Use same account' below thee main window will fill in all the textboxes automatically. this worked fpr me.

Print page numbers on pages when printing html

This javascript will add absolute positioned div's with pagenumbers on the right bottom corner and works in all browsers.

A4 height = 297mm = 1123px(96dpi)

        <style type="text/css">
            @page {
              size: A4;
              margin: 0; 

            body {
              margin: 0;
        <script type="text/javascript">
          window.onload = addPageNumbers;

          function addPageNumbers() {
            var totalPages = Math.ceil(document.body.scrollHeight / 1123);  //842px A4 pageheight for 72dpi, 1123px A4 pageheight for 96dpi, 
            for (var i = 1; i <= totalPages; i++) {
              var pageNumberDiv = document.createElement("div");
              var pageNumber = document.createTextNode("Page " + i + " of " + totalPages);
     = "absolute";
     = "calc((" + i + " * (297mm - 0.5px)) - 40px)"; //297mm A4 pageheight; 0,5px unknown needed necessary correction value; additional wanted 40px margin from bottom(own element height included)
     = "16px";
              document.body.insertBefore(pageNumberDiv, document.getElementById("content"));
     = "calc(100% - (" + pageNumberDiv.offsetWidth + "px + 20px))";
        <div id="content">
            Lorem ipsum....

CSS ''background-color" attribute not working on checkbox inside <div>

We can provide background color from the css file. Try this one,

<!DOCTYPE html>
            input[type="checkbox"] {
                width: 25px;
                height: 25px;
                background: gray;
                -webkit-appearance: none;
                -moz-appearance: none;
                appearance: none;
                border: none;
                outline: none;
                position: relative;
                left: -5px;
                top: -5px;
                cursor: pointer;
            input[type="checkbox"]:checked {
                background: blue;
            .checkbox-container {
                position: absolute;
                display: inline-block;
                margin: 20px;
                width: 25px;
                height: 25px;
                overflow: hidden;
        <div class="checkbox-container">
            <input type="checkbox" />

Convert string to ASCII value python

It is not at all obvious why one would want to concatenate the (decimal) "ascii values". What is certain is that concatenating them without leading zeroes (or some other padding or a delimiter) is useless -- nothing can be reliably recovered from such an output.

>>> tests = ["hi", "Hi", "HI", '\x0A\x29\x00\x05']
>>> ["".join("%d" % ord(c) for c in s) for s in tests]
['104105', '72105', '7273', '104105']

Note that the first 3 outputs are of different length. Note that the fourth result is the same as the first.

>>> ["".join("%03d" % ord(c) for c in s) for s in tests]
['104105', '072105', '072073', '010041000005']
>>> [" ".join("%d" % ord(c) for c in s) for s in tests]
['104 105', '72 105', '72 73', '10 41 0 5']
>>> ["".join("%02x" % ord(c) for c in s) for s in tests]
['6869', '4869', '4849', '0a290005']

Note no such problems.

How to extract duration time from ffmpeg output?

From my experience many tools offer the desired data in some kind of a table/ordered structure and also offer parameters to gather specific parts of that data. This applies to e.g. smartctl, nvidia-smi and ffmpeg/ffprobe, too. Simply speaking - often there's no need to pipe data around or to open subshells for such a task.

As a consequence I'd use the right tool for the job - in that case ffprobe would return the raw duration value in seconds, afterwards one could create the desired time format on his own:

$ ffmpeg --version
ffmpeg version 2.2.3 ...

The command may vary dependent on the version you are using.

#!/usr/bin/env bash

# Get raw duration value
ffprobe -v quiet -print_format compact=print_section=0:nokey=1:escape=csv -show_entries format=duration "$input_file"

An explanation:

"-v quiet": Don't output anything else but the desired raw data value

"-print_format": Use a certain format to print out the data

"compact=": Use a compact output format

"print_section=0": Do not print the section name

":nokey=1": do not print the key of the key:value pair

":escape=csv": escape the value

"-show_entries format=duration": Get entries of a field named duration inside a section named format

Reference: ffprobe man pages

Spring: Returning empty HTTP Responses with ResponseEntity<Void> doesn't work

You can also not specify the type parameter which seems a bit cleaner and what Spring intended when looking at the docs:

@RequestMapping(method = RequestMethod.HEAD, value = Constants.KEY )
public ResponseEntity taxonomyPackageExists( @PathVariable final String key ){
    // ...
    return new ResponseEntity(HttpStatus.NO_CONTENT);

How to check if a file is empty in Bash?

Misspellings are irritating, aren't they? Check your spelling of empty, but then also try this:

#!/bin/bash -e

if [ -s diff.txt ]
        rm -f empty.txt
        touch full.txt
        rm -f full.txt
        touch empty.txt

I like shell scripting a lot, but one disadvantage of it is that the shell cannot help you when you misspell, whereas a compiler like your C++ compiler can help you.

Notice incidentally that I have swapped the roles of empty.txt and full.txt, as @Matthias suggests.

How to Use slideDown (or show) function on a table row?

Animations are not supported on table rows.

From "Learning jQuery" by Chaffer and Swedberg

Table rows present particular obstacles to animation, since browsers use different values (table-row and block) for their visible display property. The .hide() and .show() methods, without animation, are always safe to use with table rows. As of jQuery version 1.1.3, .fadeIn() and .fadeOut() can be used as well.

You can wrap your td contents in a div and use the slideDown on that. You need to decide if the animation is worth the extra markup.

String.Format like functionality in T-SQL?

take a look at xp_sprintf. example below.

DECLARE @ret_string varchar (255)
EXEC xp_sprintf @ret_string OUTPUT, 
    'INSERT INTO %s VALUES (%s, %s)', 'table1', '1', '2'
PRINT @ret_string

Result looks like this:

INSERT INTO table1 VALUES (1, 2)

Just found an issue with the max size (255 char limit) of the string with this so there is an alternative function you can use:

create function dbo.fnSprintf (@s varchar(MAX), 
                @params varchar(MAX), @separator char(1) = ',')
returns varchar(MAX)
declare @p varchar(MAX)
declare @paramlen int

set @params = @params + @separator
set @paramlen = len(@params)
while not @params = ''
    set @p = left(@params+@separator, charindex(@separator, @params)-1)
    set @s = STUFF(@s, charindex('%s', @s), 2, @p)
    set @params = substring(@params, len(@p)+2, @paramlen)
return @s

To get the same result as above you call the function as follows:

print dbo.fnSprintf('INSERT INTO %s VALUES (%s, %s)', 'table1,1,2', default)

Is there an eval() function in Java?

The following resolved the issue:

ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
String str = "4*5";

intl extension: installing php_intl.dll

  1. Under php extensions in your wampserver, ensure intl is checked
  2. check your extension_dir in your php/v7.0/php file ensure the directory is not commented and it is accurate
  3. (Dont know if this contributed but i did all three)In your extension list in the same file as 2 above, include the intl file in the same format as the rest(if it is not included). All the best

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

Dir.foreach("#{Rails.root.to_s}/app/models") do |model_path|
  next unless model_path.match(/.rb$/)
  model_class = model_path.gsub(/.rb$/, '').classify.constantize
  puts model_class

This will give to you all the model classes you have on your project.

How to create empty constructor for data class in Kotlin Android

the modern answer for this should be using Kotlin's no-arg compiler plugin which creates a non argument construct code for classic apies more about here

simply you have to add the plugin class path in build.gradle project level

    dependencies {

    classpath "org.jetbrains.kotlin:kotlin-noarg:1.4.10"


then configure your annotation to generate the no-arg constructor

apply plugin: "kotlin-noarg"

noArg {
      invokeInitializers = true

then define your annotation file NoArg.kt

 annotation class NoArg

finally in any data class you can simply use your own annotation

data class SomeClass( val datafield:Type , ...   )

I used to create my own no-arg constructor as the accepted answer , which i got by search but then this plugin released or something and I found it way cleaner .

Check if argparse optional argument is set or not

If your argument is positional (ie it doesn't have a "-" or a "--" prefix, just the argument, typically a file name) then you can use the nargs parameter to do this:

parser = argparse.ArgumentParser(description='Foo is a program that does things')
parser.add_argument('filename', nargs='?')
args = parser.parse_args()

if args.filename is not None:
    print('The file name is {}'.format(args.filename))
    print('Oh well ; No args, no problems')

How to negate 'isblank' function

If you're trying to just count how many of your cells in a range are not blank try this:


Example: (assume that it starts from A1 downwards):




=COUNTA(A1:A6) returns 4 since there are two blank cells in there.

Conditional replacement of values in a data.frame

Try data.table's := operator :

DT =
DT[b==0, est := (a-5)/2.533]

It's fast and short. See these linked questions for more information on := :

Why has data.table defined :=

When should I use the := operator in data.table

How do you remove columns from a data.frame

R self reference

What is the difference between an int and an Integer in Java and C#?

int is predefined in library function c# but in java we can create object of Integer

Printing an array in C++?

C++ can print whatever you want if you program it to do so. You'll have to go through the array yourself printing each element.

How to use sed/grep to extract text between two words?

This might work for you (GNU sed):

sed '/Here/!d;s//&\n/;s/.*\n//;:a;/String/bb;$!{n;ba};:b;s//\n&/;P;D' file 

This presents each representation of text between two markers (in this instance Here and String) on a newline and preserves newlines within the text.

how to convert a string to an array in php

explode() might be the function you are looking for

$array = explode(' ',$str);

Is it better to use C void arguments "void foo(void)" or not "void foo()"?

void foo(void) is better because it explicitly says: no parameters allowed.

void foo() means you could (under some compilers) send parameters, at least if this is the declaration of your function rather than its definition.

Run react-native application on iOS device directly from command line?

Actually, For the first build, please do it with Xcode and then do the following way:

  1. brew install ios-deploy
  2. npx react-native run-ios --device

The second command will run the app on the first connected device.

How to get featured image of a product in woocommerce

I got the solution . I tried this .

<?php $image = wp_get_attachment_image_src( get_post_thumbnail_id( $loop->post->ID ), 'single-post-thumbnail' );?>

    <img src="<?php  echo $image[0]; ?>" data-id="<?php echo $loop->post->ID; ?>">

How to disable text selection highlighting

With SASS (SCSS syntax)

You can do this with a mixin:

// Disable selection
@mixin disable-selection {
    -webkit-touch-callout: none; /* iOS Safari */
    -webkit-user-select: none;   /* Safari */
    -khtml-user-select: none;    /* Konqueror HTML */
    -moz-user-select: none;      /* Firefox */
    -ms-user-select: none;       /* Internet Explorer/Edge */
    user-select: none;           /* Non-prefixed version, currently supported by Chrome and Opera */

// No selectable element
.no-selectable {
    @include disable-selection;

In an HTML tag:

<div class="no-selectable">TRY TO HIGHLIGHT</div>

Try it in this CodePen.

If you are using an autoprefixer you can remove other prefixes.

Browser compatibility here.

Text inset for UITextField?

If you want to change TOP and LEFT indent only then

// placeholder position

- (CGRect)textRectForBounds:(CGRect)bounds {

CGRect frame = bounds;
frame.origin.y = 3;
 frame.origin.x = 5;
bounds = frame;
return CGRectInset( bounds , 0 , 0 );

// text position

- (CGRect)editingRectForBounds:(CGRect)bounds {

CGRect frame = bounds;
frame.origin.y = 3;
 frame.origin.x = 5;
bounds = frame;
return CGRectInset( bounds , 0 , 0 );

Maven and adding JARs to system scope

System scope was only designed to deal with 'system' files; files sitting in some fixed location. Files in /usr/lib, or ${java.home} (e.g. tools.jar). It wasn't designed to support miscellaneous .jar files in your project.

The authors intentionally refused to make the pathname expansions work right for that to discourage you. As a result, in the short term you can use install:install-file to install into the local repo, and then some day use a repo manager to share.

Best way to remove items from a collection

A lot of good responses here; I especially like the lambda expressions...very clean. I was remiss, however, in not specifying the type of Collection. This is a SPRoleAssignmentCollection (from MOSS) that only has Remove(int) and Remove(SPPrincipal), not the handy RemoveAll(). So, I have settled on this, unless there is a better suggestion.

foreach (SPRoleAssignment spAssignment in workspace.RoleAssignments)
    if (spAssignment.Member.Name != shortName) continue;

What is the best way to delete a component with CLI

Answer for Angular 2+

Remove component from imports and declaration array of app.modules.ts.

Second check its reference is added in other module, if yes then remove it and

finally delete that component Manually from app and you are done.

Or you can do it in reverse order also.

Where does Jenkins store configuration files for the jobs it runs?

The best approach would be to keep your job configurations in a Jenkinsfile that live in source control.

Call a stored procedure with another in Oracle

@Michael Lockwood - you don't need to use the keyword "CALL" anywhere. You just need to mention the procedure call directly.

That is

   proc1(input1, input2);

instead of

   call proc1(input1, input2);

How do I use Linq to obtain a unique list of properties from a list of objects?

Using straight Linq, with the Distinct() extension:

var idList = (from x in yourList select x.ID).Distinct();

Android WebView Cookie Problem

My working code

public View onCreateView(...){
    mWebView = (WebView) view.findViewById(;

    WebSettings webSettings = mWebView.getSettings();


    CookieManager cookieManager = CookieManager.getInstance();
    //cookieManager.removeSessionCookie(); // remove
    cookieManager.removeAllCookie(); //remove
    // Recommended "hack" with a delay between the removal and the installation of "Cookies"

    cookieManager.setCookie("", "cookiename=" + value + "; path=/registration" + "; secure"); // ;

    mWebView.loadUrl(sp.getString("url", "") + end_url);

    return view;

To debug the query, "cookieManager.setCookie (....);" I recommend you to look through the contents of the database webviewCookiesChromium.db (stored in "/data/data/") There You can see the correct settings.

Disabling "cookieManager.removeSessionCookie();" and/or "cookieManager.removeAllCookie();"

// and/or

Compare the set value with those that are set by the browser. Adjust the request for the installation of the cookies before until "flags" browser is not installed will fit with what You decide. I found that a query can be "flags":

// You may want to add the secure flag for https:
+ "; secure"
// In case you wish to convert session cookies to have an expiration:
+ "; expires=Thu, 01-Jan-2037 00:00:10 GMT"
// These flags I found in the database:
+ "; path=/registration"
+ ";"

How to Store Historical Data

Another option is to archive the operational data on a [daily|hourly|whatever] basis. Most database engines support the extraction of the data into an archive.

Basically, the idea is to create a scheduled Windows or CRON job that

  1. determines the current tables in the operational database
  2. selects all data from every table into a CSV or XML file
  3. compresses the exported data to a ZIP file, preferably with the timestamp of the generation in the file name for easier archiving.

Many SQL database engines come with a tool that can be used for this purpose. For example, when using MySQL on Linux, the following command can be used in a CRON job to schedule the extraction:

mysqldump --all-databases --xml --lock-tables=false -ppassword | gzip -c | cat > /media/bak/servername-$(date +%Y-%m-%d)-mysql.xml.gz

CSS to make HTML page footer stay at bottom of the page with a minimum height, but not overlap the page

Dynamic one liner using jQuery

All CSS methods I have come across are too rigid. Also, setting the footer to fixed is not an option if that's not part of the design.

Tested on:

  • Chrome: 60
  • FF: 54
  • IE: 11

Assuming this layout:


  <div id="content"></div>
  <div id="footer"></div>


Use the following jQuery function:

$('#content').css("min-height", $(window).height() - $("#footer").height() + "px");

What that does is set the min-height for #content to the window height - the height of the footer what ever that might be at the time.

Since we used min-height, if #content height exceeds the window height, the function degrades gracefully and does not any effect anything since it's not needed.

See it in action:

$("#fix").click(function() {
  $('#content').css("min-height", $(window).height() - $("#footer").height() + "px");
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;

html {
  background: #111;

body {
  text-align: center;
  background: #444

#content {
  background: #999;

#footer {
  background: #777;
  width: 100%;
<script src=""></script>


  <div id="content">
    <p>Very short content</p>
    <button id="fix">Fix it!</button>
  <div id="footer">Mr. Footer</div>


Same snippet on JsFiddle


We can take this further and make this function adapt to dynamic viewer height resizing like so:

$(window).resize(function() {
    $('#content').css("min-height", $(window).height() - $("#footer").height() + "px");
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;

html {
  background: #111;

body {
  text-align: center;
  background: #444

#content {
  background: #999;

#footer {
  background: #777;
  width: 100%;
<script src=""></script>


  <div id="content">
    <p>Very short content</p>
  <div id="footer">Mr. Footer</div>


How to set layout_gravity programmatically?

I switched from LinearLayout.LayoutParams to RelativeLayout.LayoutParams to finally get the result I was desiring on a custom circleview I created.

But instead of gravity you use addRule

RelativeLayout.LayoutParams mCircleParams = new RelativeLayout.LayoutParams(circleheight,circleheight);


Best way to parse command line arguments in C#?

I wrote a C# command line argument parser a while back. Its at:

Android Lint contentDescription warning

Since I need the ImageView to add an icon just for aesthetics I've added tools:ignore="ContentDescription" within each ImageView I had in my xml file.

I'm no longer getting any error messages

How to delete an array element based on key?

this looks like PHP to me. I'll delete if it's some other language.

Simply unset($arr[1]);

How to set Meld as git mergetool

After installing it I had to tell git where it was:

git config --global merge.tool meld
git config --global diff.tool meld
git config --global mergetool.meld.path “C:\Program Files (x86)\Meld\meld.exe”

And that seems to work. Both merging and diffing with “git difftool” or “git mergetool”

If someone facing issue such as Meld crash after starting (problem indication with python) then you need to set up Meld/lib to your system environment variable as bellow C:\Program Files (x86)\Meld\lib

Query an XDocument for elements by name at any depth

This my variant of the solution based on LINQ and the Descendants method of the XDocument class

using System;
using System.Linq;
using System.Xml.Linq;

class Test
    static void Main()
        XDocument xml = XDocument.Parse(@"
          <child id='1'/>
          <child id='2'>
            <subChild id='3'>
                <extChild id='5' />
                <extChild id='6' />
            <subChild id='4'>
                <extChild id='7' />

        xml.Descendants().Where(p => p.Name.LocalName == "extChild")
                         .ForEach(e => Console.WriteLine(e));



For more details on the Desendants method take a look here.

How to set the min and max height or width of a Frame?

A workaround - at least for the minimum size: You can use grid to manage the frames contained in root and make them follow the grid size by setting sticky='nsew'. Then you can use root.grid_rowconfigure and root.grid_columnconfigure to set values for minsize like so:

from tkinter import Frame, Tk

class MyApp():
    def __init__(self):
        self.root = Tk()

        self.my_frame_red = Frame(self.root, bg='red')
        self.my_frame_red.grid(row=0, column=0, sticky='nsew')

        self.my_frame_blue = Frame(self.root, bg='blue')
        self.my_frame_blue.grid(row=0, column=1, sticky='nsew')

        self.root.grid_rowconfigure(0, minsize=200, weight=1)
        self.root.grid_columnconfigure(0, minsize=200, weight=1)
        self.root.grid_columnconfigure(1, weight=1)


if __name__ == '__main__':
    app = MyApp()

But as Brian wrote (in 2010 :D) you can still resize the window to be smaller than the frame if you don't limit its minsize.

How to set minDate to current date in jQuery UI Datepicker?

minDate property for current date works on for both -> minDate:"yy-mm-dd" or minDate:0

How do I make a self extract and running installer

I have created step by step instructions on how to do this as I also was very confused about how to get this working.

How to make a self extracting archive that runs your setup.exe with 7zip -sfx switch

Here are the steps.

Step 1 - Setup your installation folder

To make this easy create a folder c:\Install. This is where we will copy all the required files.

Step 2 - 7Zip your installers

  1. Go to the folder that has your .msi and your setup.exe
  2. Select both the .msi and the setup.exe
  3. Right-Click and choose 7Zip --> "Add to Archive"
  4. Name your archive "Installer.7z" (or a name of your choice)
  5. Click Ok
  6. You should now have "Installer.7z".
  7. Copy this .7z file to your c:\Install directory

Step 3 - Get the 7z-Extra sfx extension module

You need to download 7zSD.sfx

  1. Download one of the LZMA packages from here
  2. Extract the package and find 7zSD.sfx in the bin folder.
  3. Copy the file "7zSD.sfx" to c:\Install

Step 4 - Setup your config.txt

I would recommend using NotePad++ to edit this text file as you will need to encode in UTF-8, the following instructions are using notepad++.

  1. Using windows explorer go to c:\Install
  2. right-click and choose "New Text File" and name it config.txt
  3. right-click and choose "Edit with NotePad++
  4. Click the "Encoding Menu" and choose "Encode in UTF-8"
  5. Enter something like this:

    Title="SOFTWARE v1.0.0.0"
    BeginPrompt="Do you want to install SOFTWARE v1.0.0.0?"

Edit this replacing [SOFTWARE v1.0.0.0] with your product name. Notes on the parameters and options for the setup file are here.


You should now have a folder "c:\Install" with the following 3 files:

  1. Installer.7z
  2. 7zSD.sfx
  3. config.txt

Step 5 - Create the archive

These instructions I found on the web but nowhere did it explain any of the 4 steps above.

  1. Open a cmd window, Window + R --> cmd --> press enter
  2. In the command window type the following

    cd \
    cd Install
    copy /b 7zSD.sfx + config.txt + Installer.7z MyInstaller.exe
  3. Look in c:\Install and you will now see you have a MyInstaller.exe

  4. You are finished

Run the installer

Double click on MyInstaller.exe and it will prompt with your message. Click OK and the setup.exe will run.

P.S. Note on Automation

Now that you have this working in your c:\Install directory I would create an "Install.bat" file and put the copy script in it.

copy /b 7zSD.sfx + config.txt + Installer.7z MyInstaller.exe

Now you can just edit and run the Install.bat every time you need to rebuild a new version of you deployment package.

Find object by id in an array of JavaScript objects

While there are many correct answers here, many of them do not address the fact that this is an unnecessarily expensive operation if done more than once. In an extreme case this could be the cause of real performance problems.

In the real world, if you are processing a lot of items and performance is a concern it's much faster to initially build a lookup:

var items = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}];

var lookup = items.reduce((o,i)=>o[]=o,{});

you can then get at items in fixed time like this :

var bar = o[id];

You might also consider using a Map instead of an object as the lookup:

UTF-8: General? Bin? Unicode?

In general, utf8_general_ci is faster than utf8_unicode_ci, but less correct.

Here is the difference:

For any Unicode character set, operations performed using the _general_ci collation are faster than those for the _unicode_ci collation. For example, comparisons for the utf8_general_ci collation are faster, but slightly less correct, than comparisons for utf8_unicode_ci. The reason for this is that utf8_unicode_ci supports mappings such as expansions; that is, when one character compares as equal to combinations of other characters. For example, in German and some other languages “ß” is equal to “ss”. utf8_unicode_ci also supports contractions and ignorable characters. utf8_general_ci is a legacy collation that does not support expansions, contractions, or ignorable characters. It can make only one-to-one comparisons between characters.

Quoted from:

For more detailed explanation, please read the following post from MySQL forums:,187048,188748

As for utf8_bin: Both utf8_general_ci and utf8_unicode_ci perform case-insensitive comparison. In constrast, utf8_bin is case-sensitive (among other differences), because it compares the binary values of the characters.

Accidentally committed .idea directory files into git

You can remove it from the repo and commit the change.

git rm .idea/ -r --cached
git add -u .idea/
git commit -m "Removed the .idea folder"

After that, you can push it to the remote and every checkout/clone after that will be ok.

move_uploaded_file gives "failed to open stream: Permission denied" error

I ran into this related issue even after having already successfully run composer. I updated composer, and when running composer install or php composer.phar install I got:

...failed to open stream: Permission denied...

It turns out after much research that the previous answers regarding changing permissions for the folder worked. They are just slightly different directories now.

In my install, on OS X, the cache file is in /Users/[USER]/.composer/cache, and I was having trouble because the cache file was owned by root. Changing ownership of '.composer' recursively to my user solved the issue.

This is what I did:

sudo chown -R [USER] cache

Then I ran the composer install again and voila!

Cookie blocked/not saved in IFRAME in Internet Explorer

If anybody is looking for Apache line; we used this one.

Header set P3P "CP=\"Thanks IE8\""

It really didn't matter what we set CP value to, as long as there is the P3P header.

How to change environment's font size?

According to the changelog of version 1.2, new commands were added to zoom in and out only the font but the entire UI.


Use the following keybindings to replace the default global zoom actions:

on macOS:

{ "key": "cmd+numpad_add",      "command": "editor.action.fontZoomIn" },
{ "key": "shift+cmd+=",         "command": "editor.action.fontZoomIn" },
{ "key": "cmd+=",               "command": "editor.action.fontZoomIn" },
{ "key": "cmd+numpad_subtract", "command": "editor.action.fontZoomOut" },
{ "key": "shift+cmd+-",         "command": "editor.action.fontZoomOut" },
{ "key": "cmd+-",               "command": "editor.action.fontZoomOut" },
{ "key": "cmd+numpad0",         "command": "editor.action.fontZoomReset" },
{ "key": "cmd+0",               "command": "editor.action.fontZoomReset" },

on Windows and Linux:

{ "key": "ctrl+numpad_add",      "command": "editor.action.fontZoomIn" },
{ "key": "shift+ctrl+=",         "command": "editor.action.fontZoomIn" },
{ "key": "ctrl+=",               "command": "editor.action.fontZoomIn" },
{ "key": "ctrl+numpad_subtract", "command": "editor.action.fontZoomOut" },
{ "key": "shift+ctrl+-",         "command": "editor.action.fontZoomOut" },
{ "key": "ctrl+-",               "command": "editor.action.fontZoomOut" },
{ "key": "ctrl+numpad0",         "command": "editor.action.fontZoomReset" },
{ "key": "ctrl+0",               "command": "editor.action.fontZoomReset" },

Convert all strings in a list to int

Use a list comprehension:

results = [int(i) for i in results]


>>> results = ["1", "2", "3"]
>>> results = [int(i) for i in results]
>>> results
[1, 2, 3]

How to unpublish an app in Google Play Developer Console

In the current version of Google Play store Console as of(August 2017) here is the procedure of unpublishing your app.

  • Choose the app you wish to unpublish.
  • Go to Store presence > Pricing & distribution.
  • You will see "unpublish" button in the app availability section as shown below. enter image description here

After clicking unpublish a dialog will popup confirm and save the changes.

An item with the same key has already been added

I have had the same error. And after I have already thought my mind is broken, because I had rename almost all my models properties the solution was delete one reference on All Syncfusion Controls and add references to the individual controls of this controls. (From Nuget)

ASP.NET MVC 3 - redirect to another action

Your method needs to return a ActionResult type:

public ActionResult Index()
    //All we want to do is redirect to the class selection page
    return RedirectToAction("SelectClasses", "Registration");

variable is not declared it may be inaccessible due to its protection level

I had a similar issue to this. I solved it by making all the projects within my solution target the same .NET Framework 4 Client Profile and then rebuilding the entire solution.

Update a local branch with the changes from a tracked remote branch

You have set the upstream of that branch


git branch -f --track my_local_branch origin/my_remote_branch
# OR (if my_local_branch is currently checked out):
$ git branch --set-upstream-to my_local_branch origin/my_remote_branch

(git branch -f --track won't work if the branch is checked out: use the second command git branch --set-upstream-to instead, or you would get "fatal: Cannot force update the current branch.")

That means your branch is already configured with:

branch.my_local_branch.remote origin
branch.my_local_branch.merge my_remote_branch

Git already has all the necessary information.
In that case:

# if you weren't already on my_local_branch branch:
git checkout my_local_branch 
# then:
git pull

is enough.

If you hadn't establish that upstream branch relationship when it came to push your 'my_local_branch', then a simple git push -u origin my_local_branch:my_remote_branch would have been enough to push and set the upstream branch.
After that, for the subsequent pulls/pushes, git pull or git push would, again, have been enough.

Making a button invisible by clicking another button in HTML

  1. getElementById returns a single object for which you can specify the style.So, the above explanation is correct.

  2. getElementsByTagName returns multiple objects(array of objects and properties) for which we cannot apply the style directly.

Last non-empty cell in a column

An alternative solution without array formulas, possibly more robust than that of a previous answer with a (hint to a) solution without array formulas, is


See this answer as an example. Kudos to Brad and barry houdini, who helped solving this question.

Possible reasons for preferring a non-array formula are given in:

  1. An official Microsoft page (look for "Disadvantages of using array formulas").
    Array formulas can seem magical, but they also have some disadvantages:

    • You may occasionally forget to press CTRL+SHIFT+ENTER. Remember to press this key combination whenever you enter or edit an array formula.
    • Other users may not understand your formulas. Array formulas are relatively undocumented, so if other people need to modify your workbooks, you should either avoid array formulas or make sure those users understand how to change them.
    • Depending on the processing speed and memory of your computer, large array formulas can slow down calculations.
  2. Array Formula Heresy.

RichTextBox (WPF) does not have string property "Text"

Using two extension methods, this becomes very easy:

public static class Ext
    public static void SetText(this RichTextBox richTextBox, string text)
        richTextBox.Document.Blocks.Add(new Paragraph(new Run(text)));

    public static string GetText(this RichTextBox richTextBox)
        return new TextRange(richTextBox.Document.ContentStart,

What does "Content-type: application/json; charset=utf-8" really mean?

I exactly agree with @deceze but I want to develop this "I get an error from the service" part of the question,

We getting this kind of errors as http 415

Http 415 Unsupported Media type error

The HTTP 415 Unsupported Media Type client error response code indicates that the server refuses to accept the request because the payload format is in an unsupported format.

The format problem might be due to the request's indicated Content-Type or Content-Encoding, or as a result of inspecting the data directly.

In other words, such is seen in this example.

  • We have to set the correct content type and we have to accept the right content type as seen Add Content-Type: application/json and Accept: application/json. Otherwise, it will assume the default

Can Selenium WebDriver open browser windows silently in the background?

Here is a .NET solution that worked for me:

Download PhantomJS at

Copy the .exe file from the bin folder in the download folder and paste it to the bin debug/release folder of your Visual Studio project.

Add this using

using OpenQA.Selenium.PhantomJS;

In your code, open the driver like this:

PhantomJSDriver driver = new PhantomJSDriver();
using (driver)
   // Your code here

What are the differences between if, else, and else if?

The else if can be used in conjunction with 'if', and 'else' to further break down the logic

//if less than zero
if( myInt < 0){
      //do something
}else if( myInt > 0 && myInt < 10){
//else if between 0 and 10      
      //do something
//else all others  
      //do something

Add text to Existing PDF using Python

Leveraging David Dehghan's answer above, the following works in Python 2.7.13:

from PyPDF2 import PdfFileWriter, PdfFileReader, PdfFileMerger

import StringIO

from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter

packet = StringIO.StringIO()
# create a new PDF with Reportlab
can = canvas.Canvas(packet, pagesize=letter)
can.drawString(290, 720, "Hello world")

#move to the beginning of the StringIO buffer
new_pdf = PdfFileReader(packet)
# read your existing PDF
existing_pdf = PdfFileReader("original.pdf")
output = PdfFileWriter()
# add the "watermark" (which is the new pdf) on the existing page
page = existing_pdf.getPage(0)
# finally, write "output" to a real file
outputStream = open("destination.pdf", "wb")

How do I solve the "server DNS address could not be found" error on Windows 10?

There might be a problem with your DNS servers of the ISP. A computer by default uses the ISP's DNS servers. You can manually configure your DNS servers. It is free and usually better than your ISP.

  1. Go to Control Panel ? Network and Internet ? Network and Sharing Centre
  2. Click on Change Adapter settings.
  3. Right click on your connection icon (Wireless Network Connection or Local Area Connection) and select properties.
  4. Select Internet protocol version 4.
  5. Click on "Use the following DNS server address" and type either of the two DNS given below.

Google Public DNS

Preferred DNS server :
Alternate DNS server :


Preferred DNS server :
Alternate DNS server :

MYSQL: How to copy an entire row from one table to another in mysql with the second table having one extra column?

Hope this will help someone... Here's a little PHP script I wrote in case you need to copy some columns but not others, and/or the columns are not in the same order on both tables. As long as the columns are named the same, this will work. So if table A has [userid, handle, something] and tableB has [userID, handle, timestamp], then you'd "SELECT userID, handle, NOW() as timestamp FROM tableA", then get the result of that, and pass the result as the first parameter to this function ($z). $toTable is a string name for the table you're copying to, and $link_identifier is the db you're copying to. This is relatively fast for small sets of data. Not suggested that you try to move more than a few thousand rows at a time this way in a production setting. I use this primarily to back up data collected during a session when a user logs out, and then immediately clear the data from the live db to keep it slim.

 function mysql_multirow_copy($z,$toTable,$link_identifier) {
            $fields = "";
            for ($i=0;$i<mysql_num_fields($z);$i++) {
                if ($i>0) {
                    $fields .= ",";
                $fields .= mysql_field_name($z,$i);
            $q = "INSERT INTO $toTable ($fields) VALUES";
            $c = 0;
            mysql_data_seek($z,0); //critical reset in case $z has been parsed beforehand. !
            while ($a = mysql_fetch_assoc($z)) {
                foreach ($a as $key=>$as) {
                    $a[$key] = addslashes($as);
                    next ($a);
                if ($c>0) {
                    $q .= ",";
                $q .= "('".implode(array_values($a),"','")."')";
            $q .= ";";
            $z = mysql_query($q,$link_identifier);
            return ($q);

Automatically resize jQuery UI dialog to the width of the content loaded by ajax

edit this bellow:

 resizable: false,_x000D_

How to set default values in Go structs

One possible idea is to write separate constructor function

//Something is the structure we work with
type Something struct {
     Text string 
     DefaultText string 
// NewSomething create new instance of Something
func NewSomething(text string) Something {
   something := Something{}
   something.Text = text
   something.DefaultText = "default text"
   return something

Cannot access wamp server on local network

go Setting -> General and change url in WordPress Address (URL) and Site Address (URL)

enter your pc name or your ip address in place of localhost

before : http://localhost/wordpress-test

after : http://your-pc-name/wordpress-test

...and that's can access wordpress from any pc in your LAN...!!!

How to get multiple counts with one SQL query?

Building on other posted answers.

Both of these will produce the right values:

select distributor_id,
    count(*) total,
    sum(case when level = 'exec' then 1 else 0 end) ExecCount,
    sum(case when level = 'personal' then 1 else 0 end) PersonalCount
from yourtable
group by distributor_id

SELECT a.distributor_id,
          (SELECT COUNT(*) FROM myTable WHERE level='personal' and distributor_id = a.distributor_id) as PersonalCount,
          (SELECT COUNT(*) FROM myTable WHERE level='exec' and distributor_id = a.distributor_id) as ExecCount,
          (SELECT COUNT(*) FROM myTable WHERE distributor_id = a.distributor_id) as TotalCount
       FROM myTable a ; 

However, the performance is quite different, which will obviously be more relevant as the quantity of data grows.

I found that, assuming no indexes were defined on the table, the query using the SUMs would do a single table scan, while the query with the COUNTs would do multiple table scans.

As an example, run the following script:

drop table t1

create table t1 (f1 int)

    insert into t1 values (1) 
    insert into t1 values (1) 
    insert into t1 values (2)
    insert into t1 values (2)
    insert into t1 values (2)
    insert into t1 values (3)
    insert into t1 values (3)
    insert into t1 values (3)
    insert into t1 values (3)
    insert into t1 values (4)
    insert into t1 values (4)
    insert into t1 values (4)
    insert into t1 values (4)
    insert into t1 values (4)

SELECT SUM(CASE WHEN f1 = 1 THEN 1 else 0 end),
SUM(CASE WHEN f1 = 2 THEN 1 else 0 end),
SUM(CASE WHEN f1 = 3 THEN 1 else 0 end),
SUM(CASE WHEN f1 = 4 THEN 1 else 0 end)
from t1

(select COUNT(*) from t1 where f1 = 1),
(select COUNT(*) from t1 where f1 = 2),
(select COUNT(*) from t1 where f1 = 3),
(select COUNT(*) from t1 where f1 = 4)

Highlight the 2 SELECT statements and click on the Display Estimated Execution Plan icon. You will see that the first statement will do one table scan and the second will do 4. Obviously one table scan is better than 4.

Adding a clustered index is also interesting. E.g.

Create clustered index t1f1 on t1(f1);
Update Statistics t1;

The first SELECT above will do a single Clustered Index Scan. The second SELECT will do 4 Clustered Index Seeks, but they are still more expensive than a single Clustered Index Scan. I tried the same thing on a table with 8 million rows and the second SELECT was still a lot more expensive.

Create XML file using java

You can use a DOM XML parser to create an XML file using Java. A good example can be found on this site:

try {
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

    //root elements
    Document doc = docBuilder.newDocument();

    Element rootElement = doc.createElement("company");

    //staff elements
    Element staff = doc.createElement("Staff");

    //set attribute to staff element
    Attr attr = doc.createAttribute("id");

    //shorten way
    //staff.setAttribute("id", "1");

    //firstname elements
    Element firstname = doc.createElement("firstname");

    //lastname elements
    Element lastname = doc.createElement("lastname");
    lastname.appendChild(doc.createTextNode("mook kim"));

    //nickname elements
    Element nickname = doc.createElement("nickname");

    //salary elements
    Element salary = doc.createElement("salary");

    //write the content into xml file
    TransformerFactory transformerFactory =  TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    DOMSource source = new DOMSource(doc);

    StreamResult result =  new StreamResult(new File("C:\\testing.xml"));
    transformer.transform(source, result);


}catch(ParserConfigurationException pce){
}catch(TransformerException tfe){

How to downgrade tensorflow, multiple versions possible?

If you have anaconda, you can just install desired version and conda will automatically downgrade the current package for you.

For example:

conda install tensorflow=1.1

Where does Java's String constant pool live, the heap or the stack?

String pooling

String pooling (sometimes also called as string canonicalisation) is a process of replacing several String objects with equal value but different identity with a single shared String object. You can achieve this goal by keeping your own Map (with possibly soft or weak references depending on your requirements) and using map values as canonicalised values. Or you can use String.intern() method which is provided to you by JDK.

At times of Java 6 using String.intern() was forbidden by many standards due to a high possibility to get an OutOfMemoryException if pooling went out of control. Oracle Java 7 implementation of string pooling was changed considerably. You can look for details in and

String.intern() in Java 6

In those good old days all interned strings were stored in the PermGen – the fixed size part of heap mainly used for storing loaded classes and string pool. Besides explicitly interned strings, PermGen string pool also contained all literal strings earlier used in your program (the important word here is used – if a class or method was never loaded/called, any constants defined in it will not be loaded).

The biggest issue with such string pool in Java 6 was its location – the PermGen. PermGen has a fixed size and can not be expanded at runtime. You can set it using -XX:MaxPermSize=96m option. As far as I know, the default PermGen size varies between 32M and 96M depending on the platform. You can increase its size, but its size will still be fixed. Such limitation required very careful usage of String.intern – you’d better not intern any uncontrolled user input using this method. That’s why string pooling at times of Java 6 was mostly implemented in the manually managed maps.

String.intern() in Java 7

Oracle engineers made an extremely important change to the string pooling logic in Java 7 – the string pool was relocated to the heap. It means that you are no longer limited by a separate fixed size memory area. All strings are now located in the heap, as most of other ordinary objects, which allows you to manage only the heap size while tuning your application. Technically, this alone could be a sufficient reason to reconsider using String.intern() in your Java 7 programs. But there are other reasons.

String pool values are garbage collected

Yes, all strings in the JVM string pool are eligible for garbage collection if there are no references to them from your program roots. It applies to all discussed versions of Java. It means that if your interned string went out of scope and there are no other references to it – it will be garbage collected from the JVM string pool.

Being eligible for garbage collection and residing in the heap, a JVM string pool seems to be a right place for all your strings, isn’t it? In theory it is true – non-used strings will be garbage collected from the pool, used strings will allow you to save memory in case then you get an equal string from the input. Seems to be a perfect memory saving strategy? Nearly so. You must know how the string pool is implemented before making any decisions.


Running a command as Administrator using PowerShell?

You can create a batch file (*.bat) that runs your powershell script with administrative privileges when double-clicked. In this way, you do not need to change anything in your powershell script.To do this, create a batch file with the same name and location of your powershell script and then put the following content in it:

@echo off

set scriptFileName=%~n0
set scriptFolderPath=%~dp0
set powershellScriptFileName=%scriptFileName%.ps1

powershell -Command "Start-Process powershell \"-ExecutionPolicy Bypass -NoProfile -NoExit -Command `\"cd \`\"%scriptFolderPath%\`\"; & \`\".\%powershellScriptFileName%\`\"`\"\" -Verb RunAs"

That's it!

Here is the explanation:

Assuming your powershell script is in the path C:\Temp\ScriptTest.ps1, your batch file must have the path C:\Temp\ScriptTest.bat. When someone execute this batch file, the following steps will occur:

  1. The cmd will execute the command

    powershell -Command "Start-Process powershell \"-ExecutionPolicy Bypass -NoProfile -NoExit -Command `\"cd \`\"C:\Temp\`\"; & \`\".\ScriptTest.ps1\`\"`\"\" -Verb RunAs"
  2. A new powershell session will open and the following command will be executed:

    Start-Process powershell "-ExecutionPolicy Bypass -NoProfile -NoExit -Command `"cd \`"C:\Temp\`"; & \`".\ScriptTest.ps1\`"`"" -Verb RunAs
  3. Another new powershell session with administrative privileges will open in the system32 folder and the following arguments will be passed to it:

    -ExecutionPolicy Bypass -NoProfile -NoExit -Command "cd \"C:\Temp\"; & \".\ScriptTest.ps1\""
  4. The following command will be executed with administrative privileges:

    cd "C:\Temp"; & ".\ScriptTest.ps1"

    Once the script path and name arguments are double quoted, they can contain space or single quotation mark characters (').

  5. The current folder will change from system32 to C:\Temp and the script ScriptTest.ps1 will be executed. Once the parameter -NoExit was passed, the window wont be closed, even if your powershell script throws some exception.

Powershell: A positional parameter cannot be found that accepts argument "xxx"

I had this problem when trying to change directory, using the character _. The solution was to use a string to change directories.

C:\> cd "my_new_dir"

Unable to begin a distributed transaction

OK, so services are started, there is an ethernet path between them, name resolution works, linked servers work, and you disabled transaction authentication.

My gut says firewall issue, but a few things come to mind...

  1. Are the machines in the same domain? (yeah, shouldn't matter with disabled authentication)
  2. Are firewalls running on the the machines? DTC can be a bit of pain for firewalls as it uses a range of ports, see For the time being, I would disable firewalls for the sake of identifying the problem
  3. What does DTC ping say?
  4. What account is the SQL Service running as ?

Easiest way to activate PHP and MySQL on Mac OS 10.6 (Snow Leopard), 10.7 (Lion), 10.8 (Mountain Lion)?

Considering it hasn't been released yet, I'm assuming this is a question for ahead-of-time or you have a developer's build. As Benjamin mentioned, MAMP is the easiest way. However, if you want a native install, the process should be like 10.5. PHP comes installed on OS X by default (not always activated for some), just download the 32-bit version of MySQL, start Apache, and you should be good to go. You may have to tweak Apache for PHP or MySQL, depending on what builds are present. I didn't have to tweak anything to have it working.

Converting a string to JSON object

convert the string to HashMap using Object Mapper ...

new ObjectMapper().readValue(string, Map.class);

Internally Map will behave as JSON Object

How do I check if a string contains a specific word?

A simpler option:

return ( ! empty($a) && strpos($a, 'are'))? true : false;

Create a data.frame with m columns and 2 rows

Does m really need to be a data.frame() or will a matrix() suffice?

m <- matrix(0, ncol = 30, nrow = 2)

You can wrap a data.frame() around that if you need to:

m <- data.frame(m)

or all in one line: m <- data.frame(matrix(0, ncol = 30, nrow = 2))

Smooth scrolling when clicking an anchor link

Never forget that offset() function is giving your element's position to document. So when you need scroll your element relative to its parent you should use this;

     scrollTop: $( $.attr(this, 'href') ).position().top + $('.scroll-div').scrollTop()
     }, 500);       

The key point is getting scrollTop of scroll-div and add it to scrollTop. If you won't do that position() function always gives you different position values.

How to run batch file from network share without "UNC path are not supported" message?

My situation is just a little different. I'm running a batch file on startup to distribute the latest version of internal business applications.

In this situation I'm using the Windows Registry Run Key with the following string

cmd /c copy \\serverName\SharedFolder\startup7.bat %USERPROFILE% & %USERPROFILE%\startup7.bat

This runs two commands on startup in the correct sequence. First copying the batch file locally to a directory the user has permission to. Then executing the same batch file. I can create a local directory c:\InternalApps and copy all of the files from the network.

This is probably too late to solve the original poster's question but it may help someone else.

converting drawable resource image into bitmap

Here is another way to convert Drawable resource into Bitmap in android:

Drawable drawable = getResources().getDrawable(R.drawable.input);
Bitmap bitmap = ((BitmapDrawable)drawable).getBitmap();

NSRange from Swift Range?

func formatAttributedStringWithHighlights(text: String, highlightedSubString: String?, formattingAttributes: [String: AnyObject]) -> NSAttributedString {
    let mutableString = NSMutableAttributedString(string: text)

    let text = text as NSString         // convert to NSString be we need NSRange
    if let highlightedSubString = highlightedSubString {
        let highlightedSubStringRange = text.rangeOfString(highlightedSubString) // find first occurence
        if highlightedSubStringRange.length > 0 {       // check for not found
            mutableString.setAttributes(formattingAttributes, range: highlightedSubStringRange)

    return mutableString

How to install plugin for Eclipse from .zip

Seen here. You can unzip and

enter image description here enter image description here

Clicking Local will prefix your location fith file:/C:/etc/folder

You can Click archive instead and select your zip, as suggested in the second popular question. It will prefix with jar:// but it is not accepted by Eclipse itself. So, I used the plain folder solution.

Setting up a git remote origin

You can include the branch to track when setting up remotes, to keep things working as you might expect:

git remote add --track master origin [email protected]:group/project.git   # git
git remote add --track master origin [email protected]:group/project.git   # git w/IP
git remote add --track master origin   # http
git remote add --track master origin # http w/IP
git remote add --track master origin /Volumes/Git/group/project/           # local
git remote add --track master origin G:/group/project/                     # local, Win

This keeps you from having to manually edit your git config or specify branch tracking manually.

connect to host localhost port 22: Connection refused

Check if this port is open. Maybe your SSH demon is not running. See if sshd is running. If not, then start it.

How to run a PowerShell script

If your script is named with the .ps1 extension and you're in a PowerShell window, you just run ./myscript.ps1 (assuming the file is in your working directory).

This is true for me anyway on Windows 10 with PowerShell version 5.1 anyway, and I don't think I've done anything to make it possible.

MySQL user DB does not have password columns - Installing MySQL on OSX

It only worked with me when I "flushed" after the commands mentioned here. Here's the full list of commands I used:

Previous answers might not work for later mysql versions. Try these steps if previous answers did not work for you:

1- Click on the wamp icon > mysql > mysql console

2- write following commands, one by one

use mysql;
update user set authentication_string=password('your_password') where user='root';

Using PUT method in HTML form

I wrote an npm package called 'html-form-enhancer'. By dropping it into your HTML source, it takes over submission of forms with methods aside from GET and POST, and also adds application/json serialization.

<script type=module" src="html-form-enhancer.js"></script>

<form method="PUT">

jQuery - how can I find the element with a certain id?

I don't know if this solves your problem but instead of:

$("#tbIntervalos").find("td").attr("id", horaInicial);

you can just do:

$("#tbIntervalos td#" + horaInicial);

How to resolve Unneccessary Stubbing exception

 when(dao.doSearch(dto)).thenReturn(inspectionsSummaryList);//got error in this line

The when here configures your mock to do something. However, you donot use this mock in any way anymore after this line (apart from doing a verify). Mockito warns you that the when line therefore is pointless. Perhaps you made a logic error?

SQL DATEPART(dw,date) need monday = 1 and sunday = 7

Try this:

          @addDate AS DATE, 
          @numDays AS INT

    WHILE @numDays > 0 BEGIN
        SET @addDate = DATEADD(day, 1, @addDate)    
        IF DATENAME(DW, @addDate) <> 'sunday' BEGIN
            SET @numDays = @numDays - 1 


Handle ModelState Validation in ASP.NET Web API

Maybe not what you were looking for, but perhaps nice for someone to know:

If you are using .net Web Api 2 you could just do the following:

if (!ModelState.IsValid)
     return BadRequest(ModelState);

Depending on the model errors, you get this result:

   Message: "The request is invalid."
   ModelState: {
       model.PropertyA: [
            "The PropertyA field is required."
       model.PropertyB: [
             "The PropertyB field is required."

PHPUnit assert that an exception was thrown?

For PHPUnit 5.7.27 and PHP 5.6 and to test multiple exceptions in one test, it was important to force the exception testing. Using exception handling alone to assert the instance of Exception will skip testing the situation if no exception occurs.

public function testSomeFunction() {

    $targetClassObj= new TargetClass();
    try {
    } catch ( \Exception $e ) {
    $this->assertEquals('Some message',$e->getMessage());

    try {
    } catch ( Exception $e ) {
    $this->assertEquals('Another message',$e->getMessage());


node.js require() cache - possible to invalidate?

The documentation says:

Modules are cached in this object when they are required. By deleting a key value from this object, the next require will reload the module. This does not apply to native addons, for which reloading will result in an error.

Easy way to dismiss keyboard?

@Nicholas Riley & @Kendall Helmstetter Geln & @cannyboy:

Absolutely brilliant!

Thank you.

Considering your advice and the advice of others in this thread, this is what I've done:

What it looks like when used:

[[self appDelegate] dismissKeyboard]; (note: I added appDelegate as an addition to NSObject so I can use anywhere on anything)

What it looks like under the hood:

- (void)dismissKeyboard 
    UITextField *tempTextField = [[[UITextField alloc] initWithFrame:CGRectZero] autorelease];
    tempTextField.enabled = NO;
    [myRootViewController.view addSubview:tempTextField];
    [tempTextField becomeFirstResponder];
    [tempTextField resignFirstResponder];
    [tempTextField removeFromSuperview];


Amendment to my answer to included tempTextField.enabled = NO;. Disabling the text field will prevent UIKeyboardWillShowNotification and UIKeyboardWillHideNotification keyboard notifications from being sent should you rely on these notifications throughout your app.

Bootstrap 3: How do you align column content to bottom of row

You can use display: table-cell and vertical-align: bottom, on the 2 columns that you want to be aligned bottom, like so:

    float: none;
    display: table-cell;
    vertical-align: bottom;

Working example here.

Also, this might be a possible duplicate question.

Place a button right aligned

Another possibility is to use an absolute positioning oriented to the right. You can do it this way:

style="position: absolute; right: 0;"

Get url parameters from a string in .NET

if you want in get your QueryString on Default page .Default page means your current page url . you can try this code :

string paramIl = HttpUtility.ParseQueryString(this.ClientQueryString).Get("city");

Download a file from NodeJS Server using Express


Express has a helper for this to make life easier.

app.get('/download', function(req, res){
  const file = `${__dirname}/upload-folder/dramaticpenguin.MOV`;; // Set disposition and send it.

Old Answer

As far as your browser is concerned, the file's name is just 'download', so you need to give it more info by using another HTTP header.

res.setHeader('Content-disposition', 'attachment; filename=dramaticpenguin.MOV');

You may also want to send a mime-type such as this:

res.setHeader('Content-type', 'video/quicktime');

If you want something more in-depth, here ya go.

var path = require('path');
var mime = require('mime');
var fs = require('fs');

app.get('/download', function(req, res){

  var file = __dirname + '/upload-folder/dramaticpenguin.MOV';

  var filename = path.basename(file);
  var mimetype = mime.lookup(file);

  res.setHeader('Content-disposition', 'attachment; filename=' + filename);
  res.setHeader('Content-type', mimetype);

  var filestream = fs.createReadStream(file);

You can set the header value to whatever you like. In this case, I am using a mime-type library - node-mime, to check what the mime-type of the file is.

Another important thing to note here is that I have changed your code to use a readStream. This is a much better way to do things because using any method with 'Sync' in the name is frowned upon because node is meant to be asynchronous.

Set the text in a span

This is because you have wrong selector. According to your markup, .ui-icon and .ui-icon-circle-triangle-w" should point to the same <span> element. So you should use:



$(".ui-datepicker-prev .ui-icon").html("<<");


$(".ui-datepicker-prev span").html("<<");

Auto line-wrapping in SVG text

Text wrapping is not part of SVG1.1, the currently implemented spec. You should rather use HTML via the <foreignObject/> element.

<svg ...>

<foreignObject x="20" y="90" width="150" height="200">
<p xmlns="">Text goes here</p>

<text x="20" y="20">Your SVG viewer cannot display html.</text>


Use getElementById on HTMLElement instead of HTMLDocument

Sub Scrape()
    Dim Browser As InternetExplorer
    Dim Document As htmlDocument
    Dim Elements As IHTMLElementCollection
    Dim Element As IHTMLElement

    Set Browser = New InternetExplorer
    Browser.Visible = True
    Browser.navigate ""

    Do While Browser.Busy And Not Browser.readyState = READYSTATE_COMPLETE

    Set Document = Browser.Document

    Set Elements = Document.getElementById("hmenus").getElementsByTagName("li")
    For Each Element In Elements
        Debug.Print Element.innerText
        'Ask Question
    Next Element

    Set Document = Nothing
    Set Browser = Nothing
End Sub

Could not load file or assembly System.Net.Http, Version= with ASP.NET (MVC 4) Web API OData Prerelease

Or you could do this from NuGet Package Manager Console

 Install-Package Microsoft.AspNet.WebApi -Version 5.0.0

And then you will be able to add the reference to System.Web.Http.WebHost 5.0

Performing Inserts and Updates with Dapper

Instead of using any 3rd party library for query operations, I would rather suggest writing queries on your own. Because using any other 3rd party packages would take away the main advantage of using dapper i.e. flexibility to write queries.

Now, there is a problem with writing Insert or Update query for the entire object. For this, one can simply create helpers like below:


 public static string InsertQueryBuilder(IEnumerable < string > fields) {

  StringBuilder columns = new StringBuilder();
  StringBuilder values = new StringBuilder();

  foreach(string columnName in fields) {
   columns.Append($ "{columnName}, ");
   values.Append($ "@{columnName}, ");

  string insertQuery = $ "({ columns.ToString().TrimEnd(',', ' ')}) VALUES ({ values.ToString().TrimEnd(',', ' ')}) ";

  return insertQuery;

Now, by simply passing the name of the columns to insert, the whole query will be created automatically, like below:

List < string > columns = new List < string > {
//QueryBuilder is the class having the InsertQueryBuilder()
string insertQueryValues = QueryBuilderUtil.InsertQueryBuilder(columns);

string insertQuery = $ "INSERT INTO UserDetails {insertQueryValues} RETURNING UserId";

Guid insertedId = await _connection.ExecuteScalarAsync < Guid > (insertQuery, userObj);

You can also modify the function to return the entire INSERT statement by passing the TableName parameter.

Make sure that the Class property names match with the field names in the database. Then only you can pass the entire obj (like userObj in our case) and values will be mapped automatically.

In the same way, you can have the helper function for UPDATE query as well:

  public static string UpdateQueryBuilder(List < string > fields) {
   StringBuilder updateQueryBuilder = new StringBuilder();

   foreach(string columnName in fields) {
    updateQueryBuilder.AppendFormat("{0}=@{0}, ", columnName);
   return updateQueryBuilder.ToString().TrimEnd(',', ' ');

And use it like:

List < string > columns = new List < string > {
//QueryBuilder is the class having the UpdateQueryBuilder()
string updateQueryValues = QueryBuilderUtil.UpdateQueryBuilder(columns);

string updateQuery =  $"UPDATE UserDetails SET {updateQueryValues} WHERE UserId=@UserId";

await _connection.ExecuteAsync(updateQuery, userObj);

Though in these helper functions also, you need to pass the name of the fields you want to insert or update but at least you have full control over the query and can also include different WHERE clauses as and when required.

Through this helper functions, you will save the following lines of code:

For Insert Query:

 $ "INSERT INTO UserDetails (UserName,City) VALUES (@UserName,@City) RETURNING UserId";

For Update Query:

$"UPDATE UserDetails SET UserName=@UserName, City=@City WHERE UserId=@UserId";

There seems to be a difference of few lines of code, but when it comes to performing insert or update operation with a table having more than 10 fields, one can feel the difference.

You can use the nameof operator to pass the field name in the function to avoid typos

Instead of:

List < string > columns = new List < string > {

You can write:

List < string > columns = new List < string > {

How to clear form after submit in Angular 2?

To reset your form after submitting, you can just simply invoke this.form.reset(). By calling reset() it will:

  1. Mark the control and child controls as pristine.
  2. Mark the control and child controls as untouched.
  3. Set the value of control and child controls to custom value or null.
  4. Update value/validity/errors of affected parties.

Please find this pull request for a detailed answer. FYI, this PR has already been merged to 2.0.0.

Hopefully this can be helpful and let me know if you have any other questions in regards to Angular2 Forms.

NoSql vs Relational database

RDBMS focus more on relationship and NoSQL focus more on storage.

You can consider using NoSQL when your RDBMS reaches bottlenecks. NoSQL makes RDBMS more flexible.

One line if in VB .NET

Just add Then:

If A = 1 Then A = 2


If A = 1 Then _
    A = 2

Using onBlur with JSX and React

There are a few problems here.

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

2: you need a place to render the error.

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

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