Programs & Examples On #Qtextdocument

The QTextDocument class, part of the Qt framework, holds formatted text that can be viewed and edited using a QTextEdit.

How do I find out where login scripts live?

The default location for logon scripts is the netlogon share of a domain controller. On the server this is located:

%SystemRoot%'SYSVOL'sysvol''scripts

It can presumably be changes from this default but I've never met anyone that had a reason to.

To get list of domain controllers programatically see this article: http://www.microsoft.com/technet/scriptcenter/resources/qanda/dec04/hey1216.mspx

JSON character encoding - is UTF-8 well-supported by browsers or should I use numeric escape sequences?

I had a problem there. When I JSON encode a string with a character like "é", every browsers will return the same "é", except IE which will return "\u00e9".

Then with PHP json_decode(), it will fail if it find "é", so for Firefox, Opera, Safari and Chrome, I've to call utf8_encode() before json_decode().

Note : with my tests, IE and Firefox are using their native JSON object, others browsers are using json2.js.

Android offline documentation and sample codes

First of All you should download the Android SDK. Download here:
http://developer.android.com/sdk/index.html

Then, as stated in the SDK README:

The Android SDK archive now only contains the tools. It no longer comes populated with a specific Android platform or Google add-on. Instead you use the SDK Manager to install or update SDK components such as platforms, tools, add-ons, and documentation.

fast way to copy formatting in excel

Just use the NumberFormat property after the Value property: In this example the Ranges are defined using variables called ColLetter and SheetRow and this comes from a for-next loop using the integer i, but they might be ordinary defined ranges of course.

TransferSheet.Range(ColLetter & SheetRow).Value = Range(ColLetter & i).Value TransferSheet.Range(ColLetter & SheetRow).NumberFormat = Range(ColLetter & i).NumberFormat

In Node.js, how do I "include" functions from my other files?

Another method when using node.js and express.js framework

var f1 = function(){
   console.log("f1");
}
var f2 = function(){
   console.log("f2");
}

module.exports = {
   f1 : f1,
   f2 : f2
}

store this in a js file named s and in the folder statics

Now to use the function

var s = require('../statics/s');
s.f1();
s.f2();

java- reset list iterator to first element of the list

You can call listIterator method again to get an instance of iterator pointing at beginning of list:

iter = list.listIterator();

Testing whether a value is odd or even

Otherway using strings because why not

function isEven(__num){
    return String(__num/2).indexOf('.') === -1;
}

jQuery get textarea text

the best way: $('#myTextBox').val('new value').trim();

rejected master -> master (non-fast-forward)

Try this command: "git pull origin master"

It worked for me.

Check this link: https://help.github.com/articles/dealing-with-non-fast-forward-errors

Using onBlur with JSX and React

There are a few problems here.

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

2: you need a place to render the error.

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

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

add allow_url_fopen to my php.ini using .htaccess

allow_url_fopen is generally set to On. If it is not On, then you can try two things.

  1. Create an .htaccess file and keep it in root folder ( sometimes it may need to place it one step back folder of the root) and paste this code there.

    php_value allow_url_fopen On
    
  2. Create a php.ini file (for update server php5.ini) and keep it in root folder (sometimes it may need to place it one step back folder of the root) and paste the following code there:

    allow_url_fopen = On;
    

I have personally tested the above solutions; they worked for me.

Angular 5 Reactive Forms - Radio Button Group

IF you want to derive usg Boolean true False need to add "[]" around value

<form [formGroup]="form">
  <input type="radio" [value]=true formControlName="gender" >Male
  <input type="radio" [value]=false formControlName="gender">Female
</form>

Capitalize the first letter of both words in a two word string

You could also use the snakecase package:

install.packages("snakecase")
library(snakecase)

name <- c("zip code", "state", "final count")
to_title_case(name)
#> [1] "Zip Code"    "State"       "Final Count"

# or 
to_upper_camel_case(name, sep_out = " ")
#> [1] "Zip Code"    "State"       "Final Count"

https://github.com/Tazinho/snakecase

Can two Java methods have same name with different return types?

Only if their parameter declarations are different from memory.

How do I get the list of keys in a Dictionary?

To get list of all keys

using System.Linq;
List<String> myKeys = myDict.Keys.ToList();

System.Linq is supported in .Net framework 3.5 or above. See the below links if you face any issue in using System.Linq

Visual Studio Does not recognize System.Linq

System.Linq Namespace

jQueryUI modal dialog does not show close button (x)

I think the problem is that the browser could not load the jQueryUI image sprite that contains the X icon. Please use Fiddler, Firebug, or some other that can give you access to the HTTP requests the browser makes to the server and verify the image sprite is loaded successfully.

Get the filename of a fileupload in a document through JavaScript

Try the value property, like this:

var fu1 = document.getElementById("FileUpload1");
alert("You selected " + fu1.value);

NOTE: It looks like FileUpload1 is an ASP.Net server-side FileUpload control.
If so, you should get its ID using the ClientID property, like this:

var fu1 = document.getElementById("<%= FileUpload1.ClientID %>");

iOS application: how to clear notifications?

Update for iOS 10 (Swift 3)

In order to clear all local notifications in iOS 10 apps, you should use the following code:

import UserNotifications

...

if #available(iOS 10.0, *) {
    let center = UNUserNotificationCenter.current()
    center.removeAllPendingNotificationRequests() // To remove all pending notifications which are not delivered yet but scheduled.
    center.removeAllDeliveredNotifications() // To remove all delivered notifications
} else {
    UIApplication.shared.cancelAllLocalNotifications()
}

This code handles the clearing of local notifications for iOS 10.x and all preceding versions of iOS. You will need to import UserNotifications for the iOS 10.x code.

Get Memory Usage in Android

Based on the previous answers and personnal experience, here is the code I use to monitor CPU use. The code of this class is written in pure Java.

import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * Utilities available only on Linux Operating System.
 * 
 * <p>
 * A typical use is to assign a thread to CPU monitoring:
 * </p>
 * 
 * <pre>
 * &#064;Override
 * public void run() {
 *  while (CpuUtil.monitorCpu) {
 * 
 *      LinuxUtils linuxUtils = new LinuxUtils();
 * 
 *      int pid = android.os.Process.myPid();
 *      String cpuStat1 = linuxUtils.readSystemStat();
 *      String pidStat1 = linuxUtils.readProcessStat(pid);
 * 
 *      try {
 *          Thread.sleep(CPU_WINDOW);
 *      } catch (Exception e) {
 *      }
 * 
 *      String cpuStat2 = linuxUtils.readSystemStat();
 *      String pidStat2 = linuxUtils.readProcessStat(pid);
 * 
 *      float cpu = linuxUtils.getSystemCpuUsage(cpuStat1, cpuStat2);
 *      if (cpu &gt;= 0.0f) {
 *          _printLine(mOutput, &quot;total&quot;, Float.toString(cpu));
 *      }
 * 
 *      String[] toks = cpuStat1.split(&quot; &quot;);
 *      long cpu1 = linuxUtils.getSystemUptime(toks);
 * 
 *      toks = cpuStat2.split(&quot; &quot;);
 *      long cpu2 = linuxUtils.getSystemUptime(toks);
 * 
 *      cpu = linuxUtils.getProcessCpuUsage(pidStat1, pidStat2, cpu2 - cpu1);
 *      if (cpu &gt;= 0.0f) {
 *          _printLine(mOutput, &quot;&quot; + pid, Float.toString(cpu));
 *      }
 * 
 *      try {
 *          synchronized (this) {
 *              wait(CPU_REFRESH_RATE);
 *          }
 *      } catch (InterruptedException e) {
 *          e.printStackTrace();
 *          return;
 *      }
 *  }
 * 
 *  Log.i(&quot;THREAD CPU&quot;, &quot;Finishing&quot;);
 * }
 * </pre>
 */
public final class LinuxUtils {

    // Warning: there appears to be an issue with the column index with android linux:
    // it was observed that on most present devices there are actually
    // two spaces between the 'cpu' of the first column and the value of 
    // the next column with data. The thing is the index of the idle 
    // column should have been 4 and the first column with data should have index 1. 
    // The indexes defined below are coping with the double space situation.
    // If your file contains only one space then use index 1 and 4 instead of 2 and 5.
    // A better way to deal with this problem may be to use a split method 
    // not preserving blanks or compute an offset and add it to the indexes 1 and 4.

    private static final int FIRST_SYS_CPU_COLUMN_INDEX = 2;

    private static final int IDLE_SYS_CPU_COLUMN_INDEX = 5;

    /** Return the first line of /proc/stat or null if failed. */
    public String readSystemStat() {

        RandomAccessFile reader = null;
        String load = null;

        try {
            reader = new RandomAccessFile("/proc/stat", "r");
            load = reader.readLine();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            Streams.close(reader);
        }

        return load;
    }

    /**
     * Compute and return the total CPU usage, in percent.
     * 
     * @param start
     *            first content of /proc/stat. Not null.
     * @param end
     *            second content of /proc/stat. Not null.
     * @return 12.7 for a CPU usage of 12.7% or -1 if the value is not
     *         available.
     * @see {@link #readSystemStat()}
     */
    public float getSystemCpuUsage(String start, String end) {
        String[] stat = start.split("\\s");
        long idle1 = getSystemIdleTime(stat);
        long up1 = getSystemUptime(stat);

        stat = end.split("\\s");
        long idle2 = getSystemIdleTime(stat);
        long up2 = getSystemUptime(stat);

        // don't know how it is possible but we should care about zero and
        // negative values.
        float cpu = -1f;
        if (idle1 >= 0 && up1 >= 0 && idle2 >= 0 && up2 >= 0) {
            if ((up2 + idle2) > (up1 + idle1) && up2 >= up1) {
                cpu = (up2 - up1) / (float) ((up2 + idle2) - (up1 + idle1));
                cpu *= 100.0f;
            }
        }

        return cpu;
    }

    /**
     * Return the sum of uptimes read from /proc/stat.
     * 
     * @param stat
     *            see {@link #readSystemStat()}
     */
    public long getSystemUptime(String[] stat) {
        /*
         * (from man/5/proc) /proc/stat kernel/system statistics. Varies with
         * architecture. Common entries include: cpu 3357 0 4313 1362393
         * 
         * The amount of time, measured in units of USER_HZ (1/100ths of a
         * second on most architectures, use sysconf(_SC_CLK_TCK) to obtain the
         * right value), that the system spent in user mode, user mode with low
         * priority (nice), system mode, and the idle task, respectively. The
         * last value should be USER_HZ times the second entry in the uptime
         * pseudo-file.
         * 
         * In Linux 2.6 this line includes three additional columns: iowait -
         * time waiting for I/O to complete (since 2.5.41); irq - time servicing
         * interrupts (since 2.6.0-test4); softirq - time servicing softirqs
         * (since 2.6.0-test4).
         * 
         * Since Linux 2.6.11, there is an eighth column, steal - stolen time,
         * which is the time spent in other operating systems when running in a
         * virtualized environment
         * 
         * Since Linux 2.6.24, there is a ninth column, guest, which is the time
         * spent running a virtual CPU for guest operating systems under the
         * control of the Linux kernel.
         */

        // with the following algorithm, we should cope with all versions and
        // probably new ones.
        long l = 0L;

        for (int i = FIRST_SYS_CPU_COLUMN_INDEX; i < stat.length; i++) {
            if (i != IDLE_SYS_CPU_COLUMN_INDEX ) { // bypass any idle mode. There is currently only one.
                try {
                    l += Long.parseLong(stat[i]);
                } catch (NumberFormatException ex) {
                    ex.printStackTrace();
                    return -1L;
                }
            }
        }

        return l;
    }

    /**
     * Return the sum of idle times read from /proc/stat.
     * 
     * @param stat
     *            see {@link #readSystemStat()}
     */
    public long getSystemIdleTime(String[] stat) {
        try {
            return Long.parseLong(stat[IDLE_SYS_CPU_COLUMN_INDEX]);
        } catch (NumberFormatException ex) {
            ex.printStackTrace();
        }

        return -1L;
    }

    /** Return the first line of /proc/pid/stat or null if failed. */
    public String readProcessStat(int pid) {

        RandomAccessFile reader = null;
        String line = null;

        try {
            reader = new RandomAccessFile("/proc/" + pid + "/stat", "r");
            line = reader.readLine();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            Streams.close(reader);
        }

        return line;
    }

    /**
     * Compute and return the CPU usage for a process, in percent.
     * 
     * <p>
     * The parameters {@code totalCpuTime} is to be the one for the same period
     * of time delimited by {@code statStart} and {@code statEnd}.
     * </p>
     * 
     * @param start
     *            first content of /proc/pid/stat. Not null.
     * @param end
     *            second content of /proc/pid/stat. Not null.
     * @return the CPU use in percent or -1f if the stats are inverted or on
     *         error
     * @param uptime
     *            sum of user and kernel times for the entire system for the
     *            same period of time.
     * @return 12.7 for a cpu usage of 12.7% or -1 if the value is not available
     *         or an error occurred.
     * @see {@link #readProcessStat(int)}
     */
    public float getProcessCpuUsage(String start, String end, long uptime) {

        String[] stat = start.split("\\s");
        long up1 = getProcessUptime(stat);

        stat = end.split("\\s");
        long up2 = getProcessUptime(stat);

        float ret = -1f;
        if (up1 >= 0 && up2 >= up1 && uptime > 0.) {
            ret = 100.f * (up2 - up1) / (float) uptime;
        }

        return ret;
    }

    /**
     * Decode the fields of the file {@code /proc/pid/stat} and return (utime +
     * stime)
     * 
     * @param stat
     *            obtained with {@link #readProcessStat(int)}
     */
    public long getProcessUptime(String[] stat) {
        return Long.parseLong(stat[14]) + Long.parseLong(stat[15]);
    }

    /**
     * Decode the fields of the file {@code /proc/pid/stat} and return (cutime +
     * cstime)
     * 
     * @param stat
     *            obtained with {@link #readProcessStat(int)}
     */
    public long getProcessIdleTime(String[] stat) {
        return Long.parseLong(stat[16]) + Long.parseLong(stat[17]);
    }

    /**
     * Return the total CPU usage, in percent.
     * <p>
     * The call is blocking for the time specified by elapse.
     * </p>
     * 
     * @param elapse
     *            the time in milliseconds between reads.
     * @return 12.7 for a CPU usage of 12.7% or -1 if the value is not
     *         available.
     */
    public float syncGetSystemCpuUsage(long elapse) {

        String stat1 = readSystemStat();
        if (stat1 == null) {
            return -1.f;
        }

        try {
            Thread.sleep(elapse);
        } catch (Exception e) {
        }

        String stat2 = readSystemStat();
        if (stat2 == null) {
            return -1.f;
        }

        return getSystemCpuUsage(stat1, stat2);
    }

    /**
     * Return the CPU usage of a process, in percent.
     * <p>
     * The call is blocking for the time specified by elapse.
     * </p>
     * 
     * @param pid
     * @param elapse
     *            the time in milliseconds between reads.
     * @return 6.32 for a CPU usage of 6.32% or -1 if the value is not
     *         available.
     */
    public float syncGetProcessCpuUsage(int pid, long elapse) {

        String pidStat1 = readProcessStat(pid);
        String totalStat1 = readSystemStat();
        if (pidStat1 == null || totalStat1 == null) {
            return -1.f;
        }

        try {
            Thread.sleep(elapse);
        } catch (Exception e) {
            e.printStackTrace();
            return -1.f;
        }

        String pidStat2 = readProcessStat(pid);
        String totalStat2 = readSystemStat();
        if (pidStat2 == null || totalStat2 == null) {
            return -1.f;
        }

        String[] toks = totalStat1.split("\\s");
        long cpu1 = getSystemUptime(toks);

        toks = totalStat2.split("\\s");
        long cpu2 = getSystemUptime(toks);

        return getProcessCpuUsage(pidStat1, pidStat2, cpu2 - cpu1);
    }

}

There are several ways of exploiting this class. You can call either syncGetSystemCpuUsage or syncGetProcessCpuUsage but each is blocking the calling thread. Since a common issue is to monitor the total CPU usage and the CPU use of the current process at the same time, I have designed a class computing both of them. That class contains a dedicated thread. The output management is implementation specific and you need to code your own.

The class can be customized by a few means. The constant CPU_WINDOW defines the depth of a read, i.e. the number of milliseconds between readings and computing of the corresponding CPU load. CPU_REFRESH_RATE is the time between each CPU load measurement. Do not set CPU_REFRESH_RATE to 0 because it will suspend the thread after the first read.

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;

import android.app.Application;
import android.os.Handler;
import android.os.HandlerThread;
import android.util.Log;

import my.app.LinuxUtils;
import my.app.Streams;
import my.app.TestReport;
import my.app.Utils;

public final class CpuUtil {

    private static final int CPU_WINDOW = 1000;

    private static final int CPU_REFRESH_RATE = 100; // Warning: anything but > 0

    private static HandlerThread handlerThread;

    private static TestReport output;

    static {
        output = new TestReport();
        output.setDateFormat(Utils.getDateFormat(Utils.DATE_FORMAT_ENGLISH));
    }

    private static boolean monitorCpu;

    /**
     * Construct the class singleton. This method should be called in
     * {@link Application#onCreate()}
     * 
     * @param dir
     *            the parent directory
     * @param append
     *            mode
     */
    public static void setOutput(File dir, boolean append) {
        try {
            File file = new File(dir, "cpu.txt");
            output.setOutputStream(new FileOutputStream(file, append));
            if (!append) {
                output.println(file.getAbsolutePath());
                output.newLine(1);

                // print header
                _printLine(output, "Process", "CPU%");

                output.flush();
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    /** Start CPU monitoring */
    public static boolean startCpuMonitoring() {
        CpuUtil.monitorCpu = true;

        handlerThread = new HandlerThread("CPU monitoring"); //$NON-NLS-1$
        handlerThread.start();

        Handler handler = new Handler(handlerThread.getLooper());
        handler.post(new Runnable() {

            @Override
            public void run() {
                while (CpuUtil.monitorCpu) {

                    LinuxUtils linuxUtils = new LinuxUtils();

                    int pid = android.os.Process.myPid();
                    String cpuStat1 = linuxUtils.readSystemStat();
                    String pidStat1 = linuxUtils.readProcessStat(pid);

                    try {
                        Thread.sleep(CPU_WINDOW);
                    } catch (Exception e) {
                    }

                    String cpuStat2 = linuxUtils.readSystemStat();
                    String pidStat2 = linuxUtils.readProcessStat(pid);

                    float cpu = linuxUtils
                            .getSystemCpuUsage(cpuStat1, cpuStat2);
                    if (cpu >= 0.0f) {
                        _printLine(output, "total", Float.toString(cpu));
                    }

                    String[] toks = cpuStat1.split(" ");
                    long cpu1 = linuxUtils.getSystemUptime(toks);

                    toks = cpuStat2.split(" ");
                    long cpu2 = linuxUtils.getSystemUptime(toks);

                    cpu = linuxUtils.getProcessCpuUsage(pidStat1, pidStat2,
                            cpu2 - cpu1);
                    if (cpu >= 0.0f) {
                        _printLine(output, "" + pid, Float.toString(cpu));
                    }

                    try {
                        synchronized (this) {
                            wait(CPU_REFRESH_RATE);
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        return;
                    }
                }

                Log.i("THREAD CPU", "Finishing");
            }

        });

        return CpuUtil.monitorCpu;
    }

    /** Stop CPU monitoring */
    public static void stopCpuMonitoring() {
        if (handlerThread != null) {
            monitorCpu = false;
            handlerThread.quit();
            handlerThread = null;
        }
    }

    /** Dispose of the object and release the resources allocated for it */
    public void dispose() {

        monitorCpu = false;

        if (output != null) {
            OutputStream os = output.getOutputStream();
            if (os != null) {
                Streams.close(os);
                output.setOutputStream(null);
            }

            output = null;
        }
    }

    private static void _printLine(TestReport output, String process, String cpu) {
        output.stampln(process + ";" + cpu);
    }

}

How to empty a Heroku database

Now it's diffrent with heroku. Try: heroku pg:reset DATABASE --confirm

Conversion failed when converting the varchar value 'simple, ' to data type int

If you are converting a varchar to int make sure you do not have decimal places.

For example, if you are converting a varchar field with value (12345.0) to an integer then you get this conversion error. In my case I had all my fields with .0 as ending so I used the following statement to globally fix the problem.

CONVERT(int, replace(FIELD_NAME,'.0',''))

When to use malloc for char pointers

malloc is for allocating memory on the free-store. If you have a string literal that you do not want to modify the following is ok:

char *literal = "foo";

However, if you want to be able to modify it, use it as a buffer to hold a line of input and so on, use malloc:

char *buf = (char*) malloc(BUFSIZE); /* define BUFSIZE before */
// ...
free(buf);

Javascript find json value

Just use the ES6 find() function in a functional way:

_x000D_
_x000D_
var data=[{name:"Afghanistan",code:"AF"},{name:"Åland Islands",code:"AX"},{name:"Albania",code:"AL"},{name:"Algeria",code:"DZ"}];

let country = data.find(el => el.code === "AL");
// => {name: "Albania", code: "AL"}
console.log(country["name"]);
_x000D_
_x000D_
_x000D_

or Lodash _.find:

_x000D_
_x000D_
var data=[{name:"Afghanistan",code:"AF"},{name:"Åland Islands",code:"AX"},{name:"Albania",code:"AL"},{name:"Algeria",code:"DZ"}];

let country = _.find(data, ["code", "AL"]);
// => {name: "Albania", code: "AL"}
console.log(country["name"]);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

jQuery Mobile: document ready vs. page events

While you use .on(), it's basically a live query that you are using.

On the other hand, .ready (as in your case) is a static query. While using it, you can dynamically update data and do not have to wait for the page to load. You can simply pass on the values into your database (if required) when a particular value is entered.

The use of live queries is common in forms where we enter data (account or posts or even comments).

Return value from nested function in Javascript

Right. The function you pass to getLocations() won't get called until the data is available, so returning "country" before it's been set isn't going to help you.

The way you need to do this is to have the function that you pass to geocoder.getLocations() actually do whatever it is you wanted done with the returned values.

Something like this:

function reverseGeocode(latitude,longitude){
  var geocoder = new GClientGeocoder();
  var latlng = new GLatLng(latitude, longitude);

  geocoder.getLocations(latlng, function(addresses) {
    var address = addresses.Placemark[0].address;
    var country = addresses.Placemark[0].AddressDetails.Country.CountryName;
    var countrycode = addresses.Placemark[0].AddressDetails.Country.CountryNameCode;
    var locality = addresses.Placemark[0].AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName;
    do_something_with_address(address, country, countrycode, locality);
  });   
}

function do_something_with_address(address, country, countrycode, locality) {
  if (country==="USA") {
     alert("USA A-OK!"); // or whatever
  }
}

If you might want to do something different every time you get the location, then pass the function as an additional parameter to reverseGeocode:

function reverseGeocode(latitude,longitude, callback){
  // Function contents the same as above, then
  callback(address, country, countrycode, locality);
}
reverseGeocode(latitude, longitude, do_something_with_address);

If this looks a little messy, then you could take a look at something like the Deferred feature in Dojo, which makes the chaining between functions a little clearer.

How to reset db in Django? I get a command 'reset' not found error

reset has been replaced by flush with Django 1.5, see:

python manage.py help flush

Failed to find target with hash string 'android-25'

Well, I was suffering with this Issue but finally I found the solution.

Problem Starts Here: ["Install missing platform(s) and sync project" (link) doesn't work & gradle sync failed]

Problem Source: Just check out the app -> src-build.gradle and you will find the parameters

  1. compileSdkVersion 25

  2. buildToolsVersion "25.0.1"

  3. targetSdkVersion 25

Note: You might find these parameters with different values e.g compileSdkVersion 23 etc.

These above parameters in build.gradle creates error because their values are not compatible with your current SDK version.

The solution to This error is simple, just open a new project in your Android Studio, In that new project goto app -> src-build.gradle.

In build.gradle file of new project find these parameters:

enter image description here

In my case these are:

compileSdkVersion "26"    
buildToolsVersion "26.0.1"
targetSdkVersion 26

Now copy these parameters from your new project build.gradle file and post them in the same file of the other project(having Error).

Find control by name from Windows Forms controls

You can use:

f.Controls[name];

Where f is your form variable. That gives you the control with name name.

Replace one character with another in Bash

Use inline shell string replacement. Example:

foo="  "

# replace first blank only
bar=${foo/ /.}

# replace all blanks
bar=${foo// /.}

See http://tldp.org/LDP/abs/html/string-manipulation.html for more details.

How to backup a local Git repository?

came to this question via google.

Here is what i did in the simplest way.

git checkout branch_to_clone

then create a new git branch from this branch

git checkout -b new_cloned_branch
Switched to branch 'new_cloned_branch'

come back to original branch and continue:

git checkout branch_to_clone

Assuming you screwed up and need to restore something from backup branch :

git checkout new_cloned_branch -- <filepath>  #notice the space before and after "--"

Best part if anything is screwed up, you can just delete the source branch and move back to backup branch!!

Programmatically extract contents of InstallShield setup.exe

The free and open-source program called cabextract will list and extract the contents of not just .cab-files, but Macrovision's archives too:

% cabextract /tmp/QLWREL.EXE
Extracting cabinet: /tmp/QLWREL.EXE
  extracting ikernel.dll
  extracting IsProBENT.tlb
  ....
  extracting IScript.dll
  extracting iKernel.rgs

All done, no errors.

libc++abi.dylib: terminating with uncaught exception of type NSException (lldb)

In my case, it was XCode getting tired and failing to start app with this message, due to an assertion failing (that was set by our code).

Running on another device showed the assertion failure, which we were able to fix, and everything went back to normal.

How to upgrade Angular CLI project?

To update Angular CLI to a new version, you must update both the global package and your project's local package.

Global package:

npm uninstall -g @angular/cli
npm cache clean
npm install -g @angular/cli@latest

Local project package:

rm -rf node_modules dist # use rmdir /S/Q node_modules dist in Windows Command Prompt; use rm -r -fo node_modules,dist in Windows PowerShell
npm install --save-dev @angular/cli@latest
npm install

See the reference https://github.com/angular/angular-cli

Equivalent of *Nix 'which' command in PowerShell?

A quick-and-dirty match to Unix which is

New-Alias which where.exe

But it returns multiple lines if they exist so then it becomes

function which {where.exe command | select -first 1}

Concatenate two char* strings in a C program

strcat concats str2 onto str1

You'll get runtime errors because str1 is not being properly allocated for concatenation

Find text string using jQuery?

Normally jQuery selectors do not search within the "text nodes" in the DOM. However if you use the .contents() function, text nodes will be included, then you can use the nodeType property to filter only the text nodes, and the nodeValue property to search the text string.

    $('*', 'body')
        .andSelf()
        .contents()
        .filter(function(){
            return this.nodeType === 3;
        })
        .filter(function(){
            // Only match when contains 'simple string' anywhere in the text
            return this.nodeValue.indexOf('simple string') != -1;
        })
        .each(function(){
            // Do something with this.nodeValue
        });

How to compile LEX/YACC files on Windows?

There are ports of flex and bison for windows here: http://gnuwin32.sourceforge.net/

flex is the free implementation of lex. bison is the free implementation of yacc.

How to restrict SSH users to a predefined set of commands after login?

GNU Rush may be the most flexible and secure way to accomplish this:

GNU Rush is a Restricted User Shell, designed for sites that provide limited remote access to their resources, such as svn or git repositories, scp, or the like. Using a sophisticated configuration file, GNU Rush gives you complete control over the command lines that users execute, as well as over the usage of system resources, such as virtual memory, CPU time, etc.

Getting an attribute value in xml element

How about:

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

public class Demo {

    public static void main(String[] args) throws Exception {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document document = db.parse(new File("input.xml"));
        NodeList nodeList = document.getElementsByTagName("Item");
        for(int x=0,size= nodeList.getLength(); x<size; x++) {
            System.out.println(nodeList.item(x).getAttributes().getNamedItem("name").getNodeValue());
        }
    }
}

Better/Faster to Loop through set or list?

Just use a set. Its semantics are exactly what you want: a collection of unique items.

Technically you'll be iterating through the list twice: once to create the set, once for your actual loop. But you'd be doing just as much work or more with any other approach.

GoogleTest: How to skip a test?

You can also run a subset of tests, according to the documentation:

Running a Subset of the Tests

By default, a Google Test program runs all tests the user has defined. Sometimes, you want to run only a subset of the tests (e.g. for debugging or quickly verifying a change). If you set the GTEST_FILTER environment variable or the --gtest_filter flag to a filter string, Google Test will only run the tests whose full names (in the form of TestCaseName.TestName) match the filter.

The format of a filter is a ':'-separated list of wildcard patterns (called the positive patterns) optionally followed by a '-' and another ':'-separated pattern list (called the negative patterns). A test matches the filter if and only if it matches any of the positive patterns but does not match any of the negative patterns.

A pattern may contain '*' (matches any string) or '?' (matches any single character). For convenience, the filter '*-NegativePatterns' can be also written as '-NegativePatterns'.

For example:

./foo_test Has no flag, and thus runs all its tests.
./foo_test --gtest_filter=* Also runs everything, due to the single match-everything * value.
./foo_test --gtest_filter=FooTest.* Runs everything in test case FooTest.
./foo_test --gtest_filter=*Null*:*Constructor* Runs any test whose full name contains either "Null" or "Constructor".
./foo_test --gtest_filter=-*DeathTest.* Runs all non-death tests.
./foo_test --gtest_filter=FooTest.*-FooTest.Bar Runs everything in test case FooTest except FooTest.Bar. 

Not the prettiest solution, but it works.

UnicodeEncodeError: 'ascii' codec can't encode character u'\xef' in position 0: ordinal not in range(128)

The actual best answer for this problem depends on your environment, specifically what encoding your terminal expects.

The quickest one-line solution is to encode everything you print to ASCII, which your terminal is almost certain to accept, while discarding characters that you cannot print:

print ch #fails
print ch.encode('ascii', 'ignore')

The better solution is to change your terminal's encoding to utf-8, and encode everything as utf-8 before printing. You should get in the habit of thinking about your unicode encoding EVERY time you print or read a string.

Jenkins vs Travis-CI. Which one would you use for a Open Source project?

Travis-ci and Jenkins, while both are tools for continuous integration are very different.

Travis is a hosted service (free for open source) while you have to host, install and configure Jenkins.

Travis does not have jobs as in Jenkins. The commands to run to test the code are taken from a file named .travis.yml which sits along your project code. This makes it easy to have different test code per branch since each branch can have its own version of the .travis.yml file.

You can have a similar feature with Jenkins if you use one of the following plugins:

  • Travis YML Plugin - warning: does not seem to be popular, probably not feature complete in comparison to the real Travis.
  • Jervis - a modification of Jenkins to make it read create jobs from a .jervis.yml file found at the root of project code. If .jervis.yml does not exist, it will fall back to using .travis.yml file instead.

There are other hosted services you might also consider for continuous integration (non exhaustive list):


How to choose ?

You might want to stay with Jenkins because you are familiar with it or don't want to depend on 3rd party for your continuous integration system. Else I would drop Jenkins and go with one of the free hosted CI services as they save you a lot of trouble (host, install, configure, prepare jobs)

Depending on where your code repository is hosted I would make the following choices:

  • in-house ? Jenkins or gitlab-ci
  • Github.com ? Travis-CI

To setup Travis-CI on a github project, all you have to do is:

  • add a .travis.yml file at the root of your project
  • create an account at travis-ci.com and activate your project

The features you get are:

  • Travis will run your tests for every push made on your repo
  • Travis will run your tests on every pull request contributors will make

How to install plugin for Eclipse from .zip

The accepted answer from Konstantin worked, but there were a few additional steps. After restarting Eclipse, you still have to go into software updates, find your newly available software, check the box(es) for it, and click the "install" button. Then it'll prompt you to restart again and only then will you see your new views or functionality.

Additionally, you can check the "Error Log" view for any problems with your new plugin that eclipse is complaining about.

java.net.UnknownHostException: Unable to resolve host "<url>": No address associated with hostname and End of input at character 0 of

I encountered this problem too, reconnecting the WiFi can solve this.

For us ,we can check if the phone can resolve the host to IP when we start application. If it cannot resolve, tell the user to check the WiFi and then exit.

I hope it helps.

How can I change eclipse's Internal Browser from IE to Firefox on Windows XP?

I don't know if this will help, but here's the SWT FAQ question How do I use Mozilla as the Browser's underlying renderer?

Edit: Having researched this further, it sounds like this isn't possible in Eclipse 3.4, but may be slated for a later release.

Changing background color of selected cell?

Works for me

UIView *customColorView = [[UIView alloc] init];
    customColorView.backgroundColor = [UIColor colorWithRed:180/255.0 
                                                      green:138/255.0 
                                                       blue:171/255.0 
                                                      alpha:0.5];
    cell.selectedBackgroundView =  customColorView;

SVN Commit failed, access forbidden

My issue was my SVN permissions.

I had the same problem "Access to '/svn/[my path]/!svn/me' forbidden" when trying to commit files to a project I had been working on daily for several months. After trying the steps above, I could not resolve the issue. I also tried pulling the project down from scratch, logging in/out of SVN, etc. Finally I contacted my company's IT department and there was a permissions issue that spontaneously emerged which changed my access from read/write to read-only access. The IT department refreshed my permissions and this solved the problem.

How to remove the last character from a bash grep output

don't have to chain so many tools. Just one awk command does the job

 COMPANY_NAME=$(awk -F"=" '/company_name/{gsub(/;$/,"",$2) ;print $2}' file.txt)

How do Mockito matchers work?

Just a small addition to Jeff Bowman's excellent answer, as I found this question when searching for a solution to one of my own problems:

If a call to a method matches more than one mock's when trained calls, the order of the when calls is important, and should be from the most wider to the most specific. Starting from one of Jeff's examples:

when(foo.quux(anyInt(), anyInt())).thenReturn(true);
when(foo.quux(anyInt(), eq(5))).thenReturn(false);

is the order that ensures the (probably) desired result:

foo.quux(3 /*any int*/, 8 /*any other int than 5*/) //returns true
foo.quux(2 /*any int*/, 5) //returns false

If you inverse the when calls then the result would always be true.

Unique Key constraints for multiple columns in Entity Framework

With Entity Framework 6.1, you can now do this:

[Index("IX_FirstAndSecond", 1, IsUnique = true)]
public int FirstColumn { get; set; }

[Index("IX_FirstAndSecond", 2, IsUnique = true)]
public int SecondColumn { get; set; }

The second parameter in the attribute is where you can specify the order of the columns in the index.
More information: MSDN

Python class returning value

class MyClass():
    def __init__(self, a, b):
        self.value1 = a
        self.value2 = b

    def __call__(self):
        return [self.value1, self.value2]

Testing:

>>> x = MyClass('foo','bar')
>>> x()
['foo', 'bar']

Including dependencies in a jar with Maven

Thanks I have added below snippet in POM.xml file and Mp problem resolved and create fat jar file that include all dependent jars.

<plugin>
    <artifactId>maven-assembly-plugin</artifactId>
        <executions>
            <execution>
                <phase>package</phase>
                <goals>
                    <goal>single</goal>
                </goals>
            </execution>
        </executions>
        <configuration>
            <descriptorRefs>
                <descriptorRef>dependencies</descriptorRef>
            </descriptorRefs>
        </configuration>
    </plugin>
</plugins>

SharePoint : How can I programmatically add items to a custom list instance

To put it simple you will need to follow the step.

  1. You need to reference the Microsoft.SharePoint.dll to the application.
  2. Assuming the List Name is Test and it has only one Field "Title" here is the code.

            using (SPSite oSite=new SPSite("http://mysharepoint"))
        {
            using (SPWeb oWeb=oSite.RootWeb)
            {
                SPList oList = oWeb.Lists["Test"];
                SPListItem oSPListItem = oList.Items.Add();
                oSPListItem["Title"] = "Hello SharePoint";
                oSPListItem.Update();
            }
    
        }
    
  3. Note that you need to run this application in the Same server where the SharePoint is installed.

  4. You dont need to create a Custom Class for Custom Content Type

git remove merge commit from history

There are two ways to tackle this based on what you want:

Solution 1: Remove purple commits, preserving history (incase you want to roll back)

git revert -m 1 <SHA of merge>

-m 1 specifies which parent line to choose

Purple commits will still be there in history but since you have reverted, you will not see code from those commits.


Solution 2: Completely remove purple commits (disruptive change if repo is shared)

git rebase -i <SHA before branching out>

and delete (remove lines) corresponding to purple commits.

This would be less tricky if commits were not made after merge. Additional commits increase the chance of conflicts during revert/rebase.

Introducing FOREIGN KEY constraint may cause cycles or multiple cascade paths - why?

Make your Foreign key attributes nullable. That will work.

How to check if a user is logged in (how to properly use user.is_authenticated)?

Update for Django 1.10+:

is_authenticated is now an attribute in Django 1.10.

The method was removed in Django 2.0.

For Django 1.9 and older:

is_authenticated is a function. You should call it like

if request.user.is_authenticated():
    # do something if the user is authenticated

As Peter Rowell pointed out, what may be tripping you up is that in the default Django template language, you don't tack on parenthesis to call functions. So you may have seen something like this in template code:

{% if user.is_authenticated %}

However, in Python code, it is indeed a method in the User class.

Avoid trailing zeroes in printf()

I search the string (starting rightmost) for the first character in the range 1 to 9 (ASCII value 49-57) then null (set to 0) each char right of it - see below:

void stripTrailingZeros(void) { 
    //This finds the index of the rightmost ASCII char[1-9] in array
    //All elements to the left of this are nulled (=0)
    int i = 20;
    unsigned char char1 = 0; //initialised to ensure entry to condition below

    while ((char1 > 57) || (char1 < 49)) {
        i--;
        char1 = sprintfBuffer[i];
    }

    //null chars left of i
    for (int j = i; j < 20; j++) {
        sprintfBuffer[i] = 0;
    }
}

How to find NSDocumentDirectory in Swift?

The modern recommendation is to use NSURLs for files and directories instead of NSString based paths:

enter image description here

So to get the Document directory for the app as an NSURL:

func databaseURL() -> NSURL? {

    let fileManager = NSFileManager.defaultManager()

    let urls = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)

    if let documentDirectory: NSURL = urls.first as? NSURL {
        // This is where the database should be in the documents directory
        let finalDatabaseURL = documentDirectory.URLByAppendingPathComponent("items.db")

        if finalDatabaseURL.checkResourceIsReachableAndReturnError(nil) {
            // The file already exists, so just return the URL
            return finalDatabaseURL
        } else {
            // Copy the initial file from the application bundle to the documents directory
            if let bundleURL = NSBundle.mainBundle().URLForResource("items", withExtension: "db") {
                let success = fileManager.copyItemAtURL(bundleURL, toURL: finalDatabaseURL, error: nil)
                if success {
                    return finalDatabaseURL
                } else {
                    println("Couldn't copy file to final location!")
                }
            } else {
                println("Couldn't find initial database in the bundle!")
            }
        }
    } else {
        println("Couldn't get documents directory!")
    }

    return nil
}

This has rudimentary error handling, as that sort of depends on what your application will do in such cases. But this uses file URLs and a more modern api to return the database URL, copying the initial version out of the bundle if it does not already exist, or a nil in case of error.

How to Troubleshoot Intermittent SQL Timeout Errors

You are on the right track with your tracing and profiling. what you need to do is look for what the queries that time-out have in common - it is likely they will all be hitting a small subset of tables or indexes. I suspect some application has a long-running update/insert that affects queries on tables that use indexes affected by the updates/inserts.

You have to work backwards a little - given the subset of tables you see timing out, see what indexes are on those tables. Look for other queries that are running at the smae time that touch those tables/indexes. I'm betting you will find a small set of updates/inserts doing this.

Then you have some decisions to make. One option is to changing the locking hints on the queries that are timing out. But that is geenrally bad practice because it will mask the real problem for a while. While you mgiht see the timeouts go away for a while, depending on the hint you choose you might end up with dirty reads and then bogus data coming back from those queries. That might turn out to be worse than the timeouts - hard to say.

Best bet is to figure out which of your applications are submitting the update/inserts you found and dig in to figure out why they take so long.

Handling click events on a drawable within an EditText

    final TextView mTvTitle = (TextView)findViewById(R.id.tvTitle1);

    mTvTitle.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            final int DRAWABLE_LEFT = 0;
            final int DRAWABLE_TOP = 1;
            final int DRAWABLE_RIGHT = 2;
            final int DRAWABLE_BOTTOM = 3;

            if(event.getAction() == MotionEvent.ACTION_UP) {
                if(event.getRawX() <= (mTvTitle.getCompoundDrawables()[DRAWABLE_LEFT].getBounds().width()))  {
                    // your action here
                    Intent intent = new Intent(DeAddExpences.this,DeHomeActivity.class);
                    startActivity(intent);
                    return true;
                }
            }
            return true;
        }
    });

What's the difference between size_t and int in C++?

From the friendly Wikipedia:

The stdlib.h and stddef.h header files define a datatype called size_t which is used to represent the size of an object. Library functions that take sizes expect them to be of type size_t, and the sizeof operator evaluates to size_t.

The actual type of size_t is platform-dependent; a common mistake is to assume size_t is the same as unsigned int, which can lead to programming errors, particularly as 64-bit architectures become more prevalent.

Also, check Why size_t matters

How to make a HTTP request using Ruby on Rails?

OpenURI is the best; it's as simple as

require 'open-uri'
response = open('http://example.com').read

Authentication plugin 'caching_sha2_password' is not supported

None of the above solution work for me. I tried and very frustrated until I watched the following video: https://www.youtube.com/watch?v=tGinfzlp0fE

pip uninstall mysql-connector work on some computer and it might not work for other computer.

I did the followings:

The mysql-connector causes problem.

  1. pip uninstall mysql-connector

    The following may not need but I removed both connector completely.

  2. pip uninstall mysql-connector-python

    re-install mysql-conenct-python connector.

  3. pip install mysql-connector-python

AngularJs: How to check for changes in file input fields?

I have done it like this;

<!-- HTML -->
<button id="uploadFileButton" class="btn btn-info" ng-click="vm.upload()">    
<span  class="fa fa-paperclip"></span></button>
<input type="file" id="txtUploadFile" name="fileInput" style="display: none;" />
// self is the instance of $scope or this
self.upload = function () {
   var ctrl = angular.element("#txtUploadFile");
   ctrl.on('change', fileNameChanged);
   ctrl.click();
}

function fileNameChanged(e) {
    console.log(self.currentItem);
    alert("select file");
}

Xcode Error: "The app ID cannot be registered to your development team."

You have to rename Organization Identifier on Bundle Identifier on settings tab.

enter image description here

Only by renaming the Organization Identifier error will remove.

IndexError: tuple index out of range ----- Python

Probably one of the indexes is wrong, either the inner one or the outer one.

I suspect you mean to say [0] where you say [1] and [1] where you say [2]. Indexes are 0-based in Python.

Tool to compare directories (Windows 7)

I use WinMerge. It is free and works pretty well (works for files and directories).

How can I run Android emulator for Intel x86 Atom without hardware acceleration on Windows 8 for API 21 and 19?

I've run into the same problem, I found the solution at http://developer.android.com/tools/devices/emulator.html#vm-windows

Just follow this simple steps:

  1. Start the Android SDK Manager, select Extras and then select Intel Hardware Accelerated Execution Manager.

  2. After the download completes, run [sdk]/extras/intel/Hardware_Accelerated_Execution_Manager/IntelHAXM.exe

  3. Follow the on-screen instructions to complete installation.

UILabel - auto-size label to fit text?

Fits everytime! :)

    name.text = @"Hi this the text I want to fit to"
    UIFont * font = 14.0f;
    CGSize size = [name.text sizeWithAttributes:@{NSFontAttributeName: font}];
    nameOfAssessment.frame = CGRectMake(400, 0, size.width, 44);
    nameOfAssessment.font = [UIFont systemFontOfSize:font];

difference between variables inside and outside of __init__()

class User(object):
    email = 'none'
    firstname = 'none'
    lastname = 'none'

    def __init__(self, email=None, firstname=None, lastname=None):
        self.email = email
        self.firstname = firstname
        self.lastname = lastname

    @classmethod
    def print_var(cls, obj):
        print ("obj.email obj.firstname obj.lastname")
        print(obj.email, obj.firstname, obj.lastname)
        print("cls.email cls.firstname cls.lastname")
        print(cls.email, cls.firstname, cls.lastname)

u1 = User(email='abc@xyz', firstname='first', lastname='last')
User.print_var(u1)

In the above code, the User class has 3 global variables, each with value 'none'. u1 is the object created by instantiating this class. The method print_var prints the value of class variables of class User and object variables of object u1. In the output shown below, each of the class variables User.email, User.firstname and User.lastname has value 'none', while the object variables u1.email, u1.firstname and u1.lastname have values 'abc@xyz', 'first' and 'last'.

obj.email obj.firstname obj.lastname
('abc@xyz', 'first', 'last')
cls.email cls.firstname cls.lastname
('none', 'none', 'none')

What should I set JAVA_HOME environment variable on macOS X 10.6?

Skipping Terminal setup since you mentioned applications, permanent system environment variable set up (works for macOS Sierra; should work for El Capitan too):

launchctl setenv JAVA_HOME $(/usr/libexec/java_home -v 1.8)

(this will set JAVA_HOME to the latest 1.8 JDK, chances are you have gone through serveral updates e.g. javac 1.8.0_101, javac 1.8.0_131)
Of course, change 1.8 to 1.7 or 1.6 (really?) to suit your need and your system

How to set a value of a variable inside a template code?

The best solution for this is to write a custom assignment_tag. This solution is more clean than using a with tag because it achieves a very clear separation between logic and styling.

Start by creating a template tag file (eg. appname/templatetags/hello_world.py):

from django import template

register = template.Library()

@register.assignment_tag
def get_addressee():
    return "World"

Now you may use the get_addressee template tag in your templates:

{% load hello_world %}

{% get_addressee as addressee %}

<html>
    <body>
        <h1>hello {{addressee}}</h1>
    </body>
</html>

Why does jQuery or a DOM method such as getElementById not find the element?

If the element you are trying to access is inside an iframe and you try to access it outside the context of the iframe this will also cause it to fail.

If you want to get an element in an iframe you can find out how here.

Use CASE statement to check if column exists in table - SQL Server

SELECT *
FROM ...
WHERE EXISTS(SELECT 1 
        FROM sys.columns c
        WHERE c.[object_id] = OBJECT_ID('dbo.Tags')
            AND c.name = 'ModifiedByUser'
    )

CentOS: Enabling GD Support in PHP Installation

With CentOS 6.5+ and PHP 5.5:

yum install php55u-gd
service httpd restart

If you get an error like: cannot map zero-fill pages: Cannot allocate memory in Unknown on line 0, it could be because you don't have a swap file. I suggest you take a look at the tutorial mentioned in this answer: https://stackoverflow.com/a/20275282/828366

Tutorial: https://www.digitalocean.com/community/articles/how-to-add-swap-on-centos-6

Triggering a checkbox value changed event in DataGridView

I found a combination of the first two answers gave me what I needed. I used the CurrentCellDirtyStateChanged event and inspected the EditedFormattedValue.

private void dgv_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
   DataGridView dgv = (DataGridView)sender;
   DataGridViewCell cell = dgv.CurrentCell;
   if (cell.RowIndex >= 0 && cell.ColumnIndex == 3) // My checkbox column
     {
        // If checkbox checked, copy value from col 1 to col 2
        if (dgv.Rows[cell.RowIndex].Cells[cell.ColumnIndex].EditedFormattedValue != null && dgv.Rows[cell.RowIndex].Cells[cell.ColumnIndex].EditedFormattedValue.Equals(true))
        {
           dgv.Rows[cell.RowIndex].Cells[1].Value = dgv.Rows[cell.RowIndex].Cells[2].Value;
        }
     }
}

How to change Maven local repository in eclipse

In Eclipse Photon navigate to Windows > Preferences > Maven > User Settings > User Setting

For "User settings" Browse to the settings.xml of the maven. ex. in my case maven it is located on the path C:\Program Files\Apache Software Distribution\apache-maven-3.5.4\conf\Settings.xml

Depending on the Settings.xml the Local Repository gets automatically configured to the specified location. Click here for screenshot

How to position a Bootstrap popover?

I've created a jQuery plugin that provides 4 additonal placements: topLeft, topRight, bottomLeft, bottomRight

You just include either the minified js or unminified js and have the matching css (minified vs unminified) in the same folder.

https://github.com/dkleehammer/bootstrap-popover-extra-placements

Get CPU Usage from Windows Command Prompt

The following works correctly on Windows 7 Ultimate from an elevated command prompt:

C:\Windows\system32>typeperf "\Processor(_Total)\% Processor Time"

"(PDH-CSV 4.0)","\\vm\Processor(_Total)\% Processor Time"
"02/01/2012 14:10:59.361","0.648721"
"02/01/2012 14:11:00.362","2.986384"
"02/01/2012 14:11:01.364","0.000000"
"02/01/2012 14:11:02.366","0.000000"
"02/01/2012 14:11:03.367","1.038332"

The command completed successfully.

C:\Windows\system32>

Or for a snapshot:

C:\Windows\system32>wmic cpu get loadpercentage
LoadPercentage
8

Python: Converting from ISO-8859-1/latin1 to UTF-8

Try decoding it first, then encoding:

apple.decode('iso-8859-1').encode('utf8')

Counter increment in Bash loop not working

Source script has some problem with subshell. First example, you probably do not need subshell. But We don't know what is hidden under "Some more action". The most popular answer has hidden bug, that will increase I/O, and won't work with subshell, because it restores couter inside loop.

Do not fortot add '\' sign, it will inform bash interpreter about line continuation. I hope it will help you or anybody. But in my opinion this script should be fully converted to AWK script, or else rewritten to python using regexp, or perl, but perl popularity over years is degraded. Better do it with python.

Corrected Version without subshell:

#!/bin/bash
WFY_PATH=/var/log/nginx
WFY_FILE=error.log
COUNTER=0
grep 'GET /log_' $WFY_PATH/$WFY_FILE | grep 'upstream timed out' |\
awk -F ', ' '{print $2,$4,$0}' |\
awk '{print "http://example.com"$5"&ip="$2"&date="$7"&time="$8"&end=1"}' |\
awk -F '&end=1' '{print $1"&end=1"}' |\
#(  #unneeded bracket
while read WFY_URL
do
    echo $WFY_URL #Some more action
    COUNTER=$((COUNTER+1))
done
# ) unneeded bracket

echo $COUNTER # output = 0

Version with subshell if it is really needed

#!/bin/bash

TEMPFILE=/tmp/$$.tmp  #I've got it from the most popular answer
WFY_PATH=/var/log/nginx
WFY_FILE=error.log
COUNTER=0
grep 'GET /log_' $WFY_PATH/$WFY_FILE | grep 'upstream timed out' |\
awk -F ', ' '{print $2,$4,$0}' |\
awk '{print "http://example.com"$5"&ip="$2"&date="$7"&time="$8"&end=1"}' |\
awk -F '&end=1' '{print $1"&end=1"}' |\
(
while read WFY_URL
do
    echo $WFY_URL #Some more action
    COUNTER=$((COUNTER+1))
done
echo $COUNTER > $TEMPFILE  #store counter only once, do it after loop, you will save I/O
)

COUNTER=$(cat $TEMPFILE)  #restore counter
unlink $TEMPFILE
echo $COUNTER # output = 0

Error: «Could not load type MvcApplication»

I have fallen into this. I have read and tested all the possible solutions that were given before. Checking build path, build, rebuild, clean, restarting IIS and VS2015, reinstall all nuget packages, compiling them one by one, etc,...

I suddenly remembered that VS keeps some ASP temporary files in system folders... I think I should give it a try, after all, that could get no worse. So I emptied:

C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files
C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files

And all is working again... Weird that this problem has such different possible solutions...

What is the difference between origin and upstream on GitHub?

after cloning a fork you have to explicitly add a remote upstream, with git add remote "the original repo you forked from". This becomes your upstream, you mostly fetch and merge from your upstream. Any other business such as pushing from your local to upstream should be done using pull request.

How to simulate key presses or a click with JavaScript?

For simulating keyboard events in Chrome:

There is a related bug in webkit that keyboard events when initialized with initKeyboardEvent get an incorrect keyCode and charCode of 0: https://bugs.webkit.org/show_bug.cgi?id=16735

A working solution for it is posted in this SO answer.

how to delete files from amazon s3 bucket?

Try to look for an updated method, since Boto3 might change from time to time. I used my_bucket.delete_objects():

import boto3
from boto3.session import Session

session = Session(aws_access_key_id='your_key_id',
                  aws_secret_access_key='your_secret_key')

# s3_client = session.client('s3')
s3_resource = session.resource('s3')
my_bucket = s3_resource.Bucket("your_bucket_name")

response = my_bucket.delete_objects(
    Delete={
        'Objects': [
            {
                'Key': "your_file_name_key"   # the_name of_your_file
            }
        ]
    }
)

Reset Windows Activation/Remove license key

On Windows XP -

  1. Reboot into "Safe mode with Command Prompt"
  2. Type "explorer" in the command prompt that comes up and push [Enter]
  3. Click on Start>Run, and type the following :

    rundll32.exe syssetup,SetupOobeBnk

Reboot, and login as normal.

This will reset the 30 day timer for activation back to 30 days so you can enter in the key normally.

Get month name from Date

If you don't mind extending the Date prototype (and there are some good reasons to not want to do this), you can actually come up with a very easy method:

Date.prototype.monthNames = [
    "January", "February", "March",
    "April", "May", "June",
    "July", "August", "September",
    "October", "November", "December"
];

Date.prototype.getMonthName = function() {
    return this.monthNames[this.getMonth()];
};
Date.prototype.getShortMonthName = function () {
    return this.getMonthName().substr(0, 3);
};

// usage:
var d = new Date();
alert(d.getMonthName());      // "October"
alert(d.getShortMonthName()); // "Oct"

These functions will then apply to all javascript Date objects.

How to get the name of the current Windows user in JavaScript

JavaScript runs in the context of the current HTML document, so it won't be able to determine anything about a current user unless it's in the current page or you do AJAX calls to a server-side script to get more information.

JavaScript will not be able to determine your Windows user name.

HTML / CSS Popup div on text click

You can simply use jQuery UI Dialog

Example:

_x000D_
_x000D_
$(function() {_x000D_
  $("#dialog").dialog();_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<html lang="en">_x000D_
_x000D_
<head>_x000D_
  <meta charset="utf-8" />_x000D_
  <title>jQuery UI Dialog - Default functionality</title>_x000D_
  <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />_x000D_
  <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>_x000D_
  <link rel="stylesheet" href="/resources/demos/style.css" />_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <div id="dialog" title="Basic dialog">_x000D_
    <p>This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.</p>_x000D_
  </div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Conditional Formatting using Excel VBA code

This will get you to an answer for your simple case, but can you expand on how you'll know which columns will need to be compared (B and C in this case) and what the initial range (A1:D5 in this case) will be? Then I can try to provide a more complete answer.

Sub setCondFormat()
    Range("B3").Select
    With Range("B3:H63")
        .FormatConditions.Add Type:=xlExpression, Formula1:= _
          "=IF($D3="""",FALSE,IF($F3>=$E3,TRUE,FALSE))"
        With .FormatConditions(.FormatConditions.Count)
            .SetFirstPriority
            With .Interior
                .PatternColorIndex = xlAutomatic
                .Color = 5287936
                .TintAndShade = 0
            End With
        End With
    End With
End Sub

Note: this is tested in Excel 2010.

Edit: Updated code based on comments.

Angular 2 optional route parameter

I can't comment, but in reference to: Angular 2 optional route parameter

an update for Angular 6:

import {map} from "rxjs/operators"

constructor(route: ActivatedRoute) {
  let paramId = route.params.pipe(map(p => p.id));

  if (paramId) {
    ...
  }
}

See https://angular.io/api/router/ActivatedRoute for additional information on Angular6 routing.

How to obtain the location of cacerts of the default java installation?

In High Sierra, the cacerts is located at : /Library/Java/JavaVirtualMachines/jdk1.8.0_25.jdk/Contents/Home/jre/lib/security/cacerts

VBA - how to conditionally skip a for loop iteration

Couldn't you just do something simple like this?

For i = LBound(Schedule, 1) To UBound(Schedule, 1)
  If (Schedule(i, 1) < ReferenceDate) Then
     PrevCouponIndex = i
  Else
     DF = Application.Run("SomeFunction"....)
     PV = PV + (DF * Coupon / CouponFrequency)
  End If
Next

Receiving JSON data back from HTTP request

Install this nuget package from Microsoft System.Net.Http.Json. It contains extension methods.

Then add using System.Net.Http.Json

Now, you'll be able to see these methods:

enter image description here

So you can now do this:

await httpClient.GetFromJsonAsync<IList<WeatherForecast>>("weatherforecast");

Source: https://www.stevejgordon.co.uk/sending-and-receiving-json-using-httpclient-with-system-net-http-json

Repeating a function every few seconds

For this the System.Timers.Timer works best

// Create a timer
myTimer = new System.Timers.Timer();
// Tell the timer what to do when it elapses
myTimer.Elapsed += new ElapsedEventHandler(myEvent);
// Set it to go off every five seconds
myTimer.Interval = 5000;
// And start it        
myTimer.Enabled = true;

// Implement a call with the right signature for events going off
private void myEvent(object source, ElapsedEventArgs e) { }

See Timer Class (.NET 4.6 and 4.5) for details

Python 2,3 Convert Integer to "bytes" Cleanly

You can use the struct's pack:

In [11]: struct.pack(">I", 1)
Out[11]: '\x00\x00\x00\x01'

The ">" is the byte-order (big-endian) and the "I" is the format character. So you can be specific if you want to do something else:

In [12]: struct.pack("<H", 1)
Out[12]: '\x01\x00'

In [13]: struct.pack("B", 1)
Out[13]: '\x01'

This works the same on both python 2 and python 3.

Note: the inverse operation (bytes to int) can be done with unpack.

How to enter special characters like "&" in oracle database?

Justin's answer is the way to go, but also as an FYI you can use the chr() function with the ascii value of the character you want to insert. For this example it would be:

INSERT INTO STUDENT(name, class_id) VALUES ('Samantha', 'Java_22 '||chr(38)||' Oracle_14'); 

How can I find the maximum value and its index in array in MATLAB?

The function is max. To obtain the first maximum value you should do

[val, idx] = max(a);

val is the maximum value and idx is its index.

iPhone app could not be installed at this time

For me Setting Build Active Architecture to NO... works and installed successfully

Git reset --hard and push to remote repository

For users of GitHub, this worked for me:

  1. In any branch protection rules where you wish to make the change, make sure Allow force pushes is enabled
  2. git reset --hard <full_hash_of_commit_to_reset_to>
  3. git push --force

This will "correct" the branch history on your local machine and the GitHub server, but anyone who has sync'ed this branch with the server since the bad commit will have the history on their local machine. If they have permission to push to the branch directly then these commits will show right back up when they sync.

All everyone else needs to do is the git reset command from above to "correct" the branch on their local machine. Of course they would need to be wary of any local commits made to this branch after the target hash. Cherry pick/backup and reapply those as necessary, but if you are in a protected branch then the number of people who can commit directly to it is likely limited.

How to parse a JSON object to a TypeScript Object

i like to use a littly tiny library called class-transformer.

it can handle nested-objects, map strings to date-objects and handle different json-property-names a lot more.

Maybe worth a look.

import { Type, plainToClass, Expose } from "class-transformer";
import 'reflect-metadata';

export class Employee{
    @Expose({ name: "uid" })
    id: number;

    firstname: string;
    lastname: string;
    birthdate: Date;
    maxWorkHours: number;
    department: string;

    @Type(() => Permission)
    permissions: Permission[] = [];
    typeOfEmployee: string;
    note: string;

    @Type(() => Date)
    lastUpdate: Date;
}

export class Permission {
  type : string;
}

let json:string = {
    "uid": 123,
    "department": "<anystring>",
    "typeOfEmployee": "<anystring>",
    "firstname": "<anystring>",
    "lastname": "<anystring>",
    "birthdate": "<anydate>",
    "maxWorkHours": 1,
    "username": "<anystring>",
    "permissions": [
      {'type' : 'read'},
      {'type' : 'write'}
    ],
    "lastUpdate": "2020-05-08"
}

console.log(plainToClass(Employee, json));

```

How do I increase the cell width of the Jupyter/ipython notebook in my browser?

What I do usually after new installation is to modify the main css file where all visual styles are stored. I use Miniconda but location is similar with others C:\Miniconda3\Lib\site-packages\notebook\static\style\style.min.css

With some screens these resolutions are different and more than 1. To be on the safe side I change all to 98% so if I disconnect from my external screens on my laptop I still have 98% screen width.

Then just replace 1140px with 98% of the screen width.

@media (min-width: 1200px) {
  .container {
    width: 1140px;
  }
}

enter image description here

After editing

@media (min-width: 1200px) {
  .container {
    width: 98%;
  }
}

enter image description here Save and restart your notebook


Update

Recently had to wider Jupyter cells on an environment it is installed, which led me to come back here and remind myself.

If you need to do it in virtual env you installed jupyter on. You can find the css file in this subdir

env/lib/python3.6/site-packages/notebook/static/style/stye.min.css

How do I verify that an Android apk is signed with a release certificate?

Use console command:

apksigner verify --print-certs application-development-release.apk

You could find apksigner in ../sdk/build-tools/24.0.3/apksigner.bat. Only for build tools v. 24.0.3 and higher.

Also read google docs: https://developer.android.com/studio/command-line/apksigner.html

How to prevent browser to invoke basic auth popup and handle 401 error using Jquery?

I was facing this issue recently, too. Since you can't change the browser's default behavior of showing the popup in case of a 401 (basic or digest authentication), there are two ways to fix this:

  • Change the server response to not return a 401. Return a 200 code instead and handle this in your jQuery client.
  • Change the method that you're using for authorization to a custom value in your header. Browsers will display the popup for Basic and Digest. You have to change this on both the client and the server.

    headers : {
      "Authorization" : "BasicCustom"
    }
    

Please also take a look at this for an example of using jQuery with Basic Auth.

How to use Python to login to a webpage and retrieve cookies for later usage?

Here's a version using the excellent requests library:

from requests import session

payload = {
    'action': 'login',
    'username': USERNAME,
    'password': PASSWORD
}

with session() as c:
    c.post('http://example.com/login.php', data=payload)
    response = c.get('http://example.com/protected_page.php')
    print(response.headers)
    print(response.text)

Python3 project remove __pycache__ folders and .pyc files

Using PyCharm

To remove Python compiled files

  1. In the Project Tool Window, right-click a project or directory, where Python compiled files should be deleted from.

  2. On the context menu, choose Clean Python compiled files.

The .pyc files residing in the selected directory are silently deleted.

Responsive timeline UI with Bootstrap3

_x000D_
_x000D_
.timeline {_x000D_
  list-style: none;_x000D_
  padding: 20px 0 20px;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
.timeline:before {_x000D_
  top: 0;_x000D_
  bottom: 0;_x000D_
  position: absolute;_x000D_
  content: " ";_x000D_
  width: 3px;_x000D_
  background-color: #eeeeee;_x000D_
  left: 50%;_x000D_
  margin-left: -1.5px;_x000D_
}_x000D_
_x000D_
.timeline > li {_x000D_
  margin-bottom: 20px;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
.timeline > li:before,_x000D_
.timeline > li:after {_x000D_
  content: " ";_x000D_
  display: table;_x000D_
}_x000D_
_x000D_
.timeline > li:after {_x000D_
  clear: both;_x000D_
}_x000D_
_x000D_
.timeline > li:before,_x000D_
.timeline > li:after {_x000D_
  content: " ";_x000D_
  display: table;_x000D_
}_x000D_
_x000D_
.timeline > li:after {_x000D_
  clear: both;_x000D_
}_x000D_
_x000D_
.timeline > li > .timeline-panel {_x000D_
  width: 46%;_x000D_
  float: left;_x000D_
  border: 1px solid #d4d4d4;_x000D_
  border-radius: 2px;_x000D_
  padding: 20px;_x000D_
  position: relative;_x000D_
  -webkit-box-shadow: 0 1px 6px rgba(0, 0, 0, 0.175);_x000D_
  box-shadow: 0 1px 6px rgba(0, 0, 0, 0.175);_x000D_
}_x000D_
_x000D_
.timeline > li > .timeline-panel:before {_x000D_
  position: absolute;_x000D_
  top: 26px;_x000D_
  right: -15px;_x000D_
  display: inline-block;_x000D_
  border-top: 15px solid transparent;_x000D_
  border-left: 15px solid #ccc;_x000D_
  border-right: 0 solid #ccc;_x000D_
  border-bottom: 15px solid transparent;_x000D_
  content: " ";_x000D_
}_x000D_
_x000D_
.timeline > li > .timeline-panel:after {_x000D_
  position: absolute;_x000D_
  top: 27px;_x000D_
  right: -14px;_x000D_
  display: inline-block;_x000D_
  border-top: 14px solid transparent;_x000D_
  border-left: 14px solid #fff;_x000D_
  border-right: 0 solid #fff;_x000D_
  border-bottom: 14px solid transparent;_x000D_
  content: " ";_x000D_
}_x000D_
_x000D_
.timeline > li > .timeline-badge {_x000D_
  color: #fff;_x000D_
  width: 50px;_x000D_
  height: 50px;_x000D_
  line-height: 50px;_x000D_
  font-size: 1.4em;_x000D_
  text-align: center;_x000D_
  position: absolute;_x000D_
  top: 16px;_x000D_
  left: 50%;_x000D_
  margin-left: -25px;_x000D_
  background-color: #999999;_x000D_
  z-index: 100;_x000D_
  border-top-right-radius: 50%;_x000D_
  border-top-left-radius: 50%;_x000D_
  border-bottom-right-radius: 50%;_x000D_
  border-bottom-left-radius: 50%;_x000D_
}_x000D_
_x000D_
.timeline > li.timeline-inverted > .timeline-panel {_x000D_
  float: right;_x000D_
}_x000D_
_x000D_
.timeline > li.timeline-inverted > .timeline-panel:before {_x000D_
  border-left-width: 0;_x000D_
  border-right-width: 15px;_x000D_
  left: -15px;_x000D_
  right: auto;_x000D_
}_x000D_
_x000D_
.timeline > li.timeline-inverted > .timeline-panel:after {_x000D_
  border-left-width: 0;_x000D_
  border-right-width: 14px;_x000D_
  left: -14px;_x000D_
  right: auto;_x000D_
}_x000D_
_x000D_
.timeline-badge.primary {_x000D_
  background-color: #2e6da4 !important;_x000D_
}_x000D_
_x000D_
.timeline-badge.success {_x000D_
  background-color: #3f903f !important;_x000D_
}_x000D_
_x000D_
.timeline-badge.warning {_x000D_
  background-color: #f0ad4e !important;_x000D_
}_x000D_
_x000D_
.timeline-badge.danger {_x000D_
  background-color: #d9534f !important;_x000D_
}_x000D_
_x000D_
.timeline-badge.info {_x000D_
  background-color: #5bc0de !important;_x000D_
}_x000D_
_x000D_
.timeline-title {_x000D_
  margin-top: 0;_x000D_
  color: inherit;_x000D_
}_x000D_
_x000D_
.timeline-body > p,_x000D_
.timeline-body > ul {_x000D_
  margin-bottom: 0;_x000D_
}_x000D_
_x000D_
.timeline-body > p + p {_x000D_
  margin-top: 5px;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="page-header">_x000D_
    <h1 id="timeline">Timeline</h1>_x000D_
  </div>_x000D_
  <ul class="timeline">_x000D_
    <li>_x000D_
      <div class="timeline-badge"><i class="glyphicon glyphicon-check"></i></div>_x000D_
      <div class="timeline-panel">_x000D_
         <p><small class="text-muted"><i class="glyphicon glyphicon-time"></i> 11 hours ago via Twitter</small></p>_x000D_
        <div class="timeline-heading">_x000D_
          <h4 class="timeline-title">Mussum ipsum cacilds</h4>_x000D_
          <p><small class="text-muted"><i class="glyphicon glyphicon-time"></i> 11 hours ago via Twitter</small></p>_x000D_
        </div>_x000D_
        <div class="timeline-body">_x000D_
          <p>Mussum ipsum cacilds, vidis litro abertis. Consetis adipiscings elitis. Pra lá , depois divoltis porris, paradis. Paisis, filhis, espiritis santis. Mé faiz elementum girarzis, nisi eros vermeio, in elementis mé pra quem é amistosis quis leo._x000D_
            Manduma pindureta quium dia nois paga. Sapien in monti palavris qui num significa nadis i pareci latim. Interessantiss quisso pudia ce receita de bolis, mais bolis eu num gostis.</p>_x000D_
        </div>_x000D_
      </div>_x000D_
    </li>_x000D_
    <li class="timeline-inverted">_x000D_
      <div class="timeline-badge warning"><i class="glyphicon glyphicon-credit-card"></i></div>_x000D_
      <div class="timeline-panel">_x000D_
        <div class="timeline-heading">_x000D_
          <h4 class="timeline-title">Mussum ipsum cacilds</h4>_x000D_
        </div>_x000D_
        <div class="timeline-body">_x000D_
          <p>Mussum ipsum cacilds, vidis litro abertis. Consetis adipiscings elitis. Pra lá , depois divoltis porris, paradis. Paisis, filhis, espiritis santis. Mé faiz elementum girarzis, nisi eros vermeio, in elementis mé pra quem é amistosis quis leo._x000D_
            Manduma pindureta quium dia nois paga. Sapien in monti palavris qui num significa nadis i pareci latim. Interessantiss quisso pudia ce receita de bolis, mais bolis eu num gostis.</p>_x000D_
          <p>Suco de cevadiss, é um leite divinis, qui tem lupuliz, matis, aguis e fermentis. Interagi no mé, cursus quis, vehicula ac nisi. Aenean vel dui dui. Nullam leo erat, aliquet quis tempus a, posuere ut mi. Ut scelerisque neque et turpis posuere_x000D_
            pulvinar pellentesque nibh ullamcorper. Pharetra in mattis molestie, volutpat elementum justo. Aenean ut ante turpis. Pellentesque laoreet mé vel lectus scelerisque interdum cursus velit auctor. Lorem ipsum dolor sit amet, consectetur adipiscing_x000D_
            elit. Etiam ac mauris lectus, non scelerisque augue. Aenean justo massa.</p>_x000D_
        </div>_x000D_
      </div>_x000D_
    </li>_x000D_
    <li>_x000D_
      <div class="timeline-badge danger"><i class="glyphicon glyphicon-credit-card"></i></div>_x000D_
      <div class="timeline-panel">_x000D_
        <div class="timeline-heading">_x000D_
          <h4 class="timeline-title">Mussum ipsum cacilds</h4>_x000D_
        </div>_x000D_
        <div class="timeline-body">_x000D_
          <p>Mussum ipsum cacilds, vidis litro abertis. Consetis adipiscings elitis. Pra lá , depois divoltis porris, paradis. Paisis, filhis, espiritis santis. Mé faiz elementum girarzis, nisi eros vermeio, in elementis mé pra quem é amistosis quis leo._x000D_
            Manduma pindureta quium dia nois paga. Sapien in monti palavris qui num significa nadis i pareci latim. Interessantiss quisso pudia ce receita de bolis, mais bolis eu num gostis.</p>_x000D_
        </div>_x000D_
      </div>_x000D_
    </li>_x000D_
    <li class="timeline-inverted">_x000D_
      <div class="timeline-panel">_x000D_
        <div class="timeline-heading">_x000D_
          <h4 class="timeline-title">Mussum ipsum cacilds</h4>_x000D_
        </div>_x000D_
        <div class="timeline-body">_x000D_
          <p>Mussum ipsum cacilds, vidis litro abertis. Consetis adipiscings elitis. Pra lá , depois divoltis porris, paradis. Paisis, filhis, espiritis santis. Mé faiz elementum girarzis, nisi eros vermeio, in elementis mé pra quem é amistosis quis leo._x000D_
            Manduma pindureta quium dia nois paga. Sapien in monti palavris qui num significa nadis i pareci latim. Interessantiss quisso pudia ce receita de bolis, mais bolis eu num gostis.</p>_x000D_
        </div>_x000D_
      </div>_x000D_
    </li>_x000D_
    <li>_x000D_
      <div class="timeline-badge info"><i class="glyphicon glyphicon-floppy-disk"></i></div>_x000D_
      <div class="timeline-panel">_x000D_
        <div class="timeline-heading">_x000D_
          <h4 class="timeline-title">Mussum ipsum cacilds</h4>_x000D_
        </div>_x000D_
        <div class="timeline-body">_x000D_
          <p>Mussum ipsum cacilds, vidis litro abertis. Consetis adipiscings elitis. Pra lá , depois divoltis porris, paradis. Paisis, filhis, espiritis santis. Mé faiz elementum girarzis, nisi eros vermeio, in elementis mé pra quem é amistosis quis leo._x000D_
            Manduma pindureta quium dia nois paga. Sapien in monti palavris qui num significa nadis i pareci latim. Interessantiss quisso pudia ce receita de bolis, mais bolis eu num gostis.</p>_x000D_
          <hr>_x000D_
          <div class="btn-group">_x000D_
            <button type="button" class="btn btn-primary btn-sm dropdown-toggle" data-toggle="dropdown">_x000D_
              <i class="glyphicon glyphicon-cog"></i> <span class="caret"></span>_x000D_
            </button>_x000D_
            <ul class="dropdown-menu" role="menu">_x000D_
              <li><a href="#">Action</a></li>_x000D_
              <li><a href="#">Another action</a></li>_x000D_
              <li><a href="#">Something else here</a></li>_x000D_
              <li class="divider"></li>_x000D_
              <li><a href="#">Separated link</a></li>_x000D_
            </ul>_x000D_
          </div>_x000D_
        </div>_x000D_
      </div>_x000D_
    </li>_x000D_
    <li>_x000D_
      <div class="timeline-panel">_x000D_
        <div class="timeline-heading">_x000D_
          <h4 class="timeline-title">Mussum ipsum cacilds</h4>_x000D_
        </div>_x000D_
        <div class="timeline-body">_x000D_
          <p>Mussum ipsum cacilds, vidis litro abertis. Consetis adipiscings elitis. Pra lá , depois divoltis porris, paradis. Paisis, filhis, espiritis santis. Mé faiz elementum girarzis, nisi eros vermeio, in elementis mé pra quem é amistosis quis leo._x000D_
            Manduma pindureta quium dia nois paga. Sapien in monti palavris qui num significa nadis i pareci latim. Interessantiss quisso pudia ce receita de bolis, mais bolis eu num gostis.</p>_x000D_
        </div>_x000D_
      </div>_x000D_
    </li>_x000D_
    <li class="timeline-inverted">_x000D_
      <div class="timeline-badge success"><i class="glyphicon glyphicon-thumbs-up"></i></div>_x000D_
      <div class="timeline-panel">_x000D_
        <div class="timeline-heading">_x000D_
          <h4 class="timeline-title">Mussum ipsum cacilds</h4>_x000D_
        </div>_x000D_
        <div class="timeline-body">_x000D_
          <p>Mussum ipsum cacilds, vidis litro abertis. Consetis adipiscings elitis. Pra lá , depois divoltis porris, paradis. Paisis, filhis, espiritis santis. Mé faiz elementum girarzis, nisi eros vermeio, in elementis mé pra quem é amistosis quis leo._x000D_
            Manduma pindureta quium dia nois paga. Sapien in monti palavris qui num significa nadis i pareci latim. Interessantiss quisso pudia ce receita de bolis, mais bolis eu num gostis.</p>_x000D_
        </div>_x000D_
      </div>_x000D_
    </li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

http://codepen.io/bsngr/pen/Ifvbi/

How to define a variable in a Dockerfile?

To my knowledge, only ENV allows that, as mentioned in "Environment replacement"

Environment variables (declared with the ENV statement) can also be used in certain instructions as variables to be interpreted by the Dockerfile.

They have to be environment variables in order to be redeclared in each new containers created for each line of the Dockerfile by docker build.

In other words, those variables aren't interpreted directly in a Dockerfile, but in a container created for a Dockerfile line, hence the use of environment variable.


This day, I use both ARG (docker 1.10+, and docker build --build-arg var=value) and ENV.
Using ARG alone means your variable is visible at build time, not at runtime.

My Dockerfile usually has:

ARG var
ENV var=${var}

In your case, ARG is enough: I use it typically for setting http_proxy variable, that docker build needs for accessing internet at build time.

Why do we check up to the square root of a prime number to determine if it is prime?

Let n be non-prime. Therefore, it has at least two integer factors greater than 1. Let f be the smallest of n's such factors. Suppose f > sqrt n. Then n/f is an integer LTE sqrt n, thus smaller than f. Therefore, f cannot be n's smallest factor. Reductio ad absurdum; n's smallest factor must be LTE sqrt n.

How do I do a not equal in Django queryset filtering?

You can use Q objects for this. They can be negated with the ~ operator and combined much like normal Python expressions:

from myapp.models import Entry
from django.db.models import Q

Entry.objects.filter(~Q(id=3))

will return all entries except the one(s) with 3 as their ID:

[<Entry: Entry object>, <Entry: Entry object>, <Entry: Entry object>, ...]

Select a date from date picker using Selenium webdriver

try this,

http://seleniumcapsules.blogspot.com/2012/10/design-of-datepicker.html

  1. an icon used as a trigger;
  2. display a calendar when the icon is clicked;
  3. Previous Year button(<<), optional;
  4. Next Year Button(>>), optional;
  5. Previous Month button(<);
  6. Next Month button(>);
  7. day buttons;
  8. Weekday indicators;
  9. Calendar title i.e. "September, 2011" which representing current month and current year.

How to encode Doctrine entities to JSON in Symfony 2.0 AJAX application?

You can automatically encode into Json, your complex entity with:

use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
use Symfony\Component\Serializer\Encoder\JsonEncoder;

$serializer = new Serializer(array(new GetSetMethodNormalizer()), array('json' => new 
JsonEncoder()));
$json = $serializer->serialize($entity, 'json');

Explain ExtJS 4 event handling

Let's start by describing DOM elements' event handling.

DOM node event handling

First of all you wouldn't want to work with DOM node directly. Instead you probably would want to utilize Ext.Element interface. For the purpose of assigning event handlers, Element.addListener and Element.on (these are equivalent) were created. So, for example, if we have html:

<div id="test_node"></div>

and we want add click event handler.
Let's retrieve Element:

var el = Ext.get('test_node');

Now let's check docs for click event. It's handler may have three parameters:

click( Ext.EventObject e, HTMLElement t, Object eOpts )

Knowing all this stuff we can assign handler:

//       event name      event handler
el.on(    'click'        , function(e, t, eOpts){
  // handling event here
});

Widgets event handling

Widgets event handling is pretty much similar to DOM nodes event handling.

First of all, widgets event handling is realized by utilizing Ext.util.Observable mixin. In order to handle events properly your widget must containg Ext.util.Observable as a mixin. All built-in widgets (like Panel, Form, Tree, Grid, ...) has Ext.util.Observable as a mixin by default.

For widgets there are two ways of assigning handlers. The first one - is to use on method (or addListener). Let's for example create Button widget and assign click event to it. First of all you should check event's docs for handler's arguments:

click( Ext.button.Button this, Event e, Object eOpts )

Now let's use on:

var myButton = Ext.create('Ext.button.Button', {
  text: 'Test button'
});
myButton.on('click', function(btn, e, eOpts) {
  // event handling here
  console.log(btn, e, eOpts);
});

The second way is to use widget's listeners config:

var myButton = Ext.create('Ext.button.Button', {
  text: 'Test button',
  listeners : {
    click: function(btn, e, eOpts) {
      // event handling here
      console.log(btn, e, eOpts);
    }
  }
});

Notice that Button widget is a special kind of widgets. Click event can be assigned to this widget by using handler config:

var myButton = Ext.create('Ext.button.Button', {
  text: 'Test button',
  handler : function(btn, e, eOpts) {
    // event handling here
    console.log(btn, e, eOpts);
  }
});

Custom events firing

First of all you need to register an event using addEvents method:

myButton.addEvents('myspecialevent1', 'myspecialevent2', 'myspecialevent3', /* ... */);

Using the addEvents method is optional. As comments to this method say there is no need to use this method but it provides place for events documentation.

To fire your event use fireEvent method:

myButton.fireEvent('myspecialevent1', arg1, arg2, arg3, /* ... */);

arg1, arg2, arg3, /* ... */ will be passed into handler. Now we can handle your event:

myButton.on('myspecialevent1', function(arg1, arg2, arg3, /* ... */) {
  // event handling here
  console.log(arg1, arg2, arg3, /* ... */);
});

It's worth mentioning that the best place for inserting addEvents method call is widget's initComponent method when you are defining new widget:

Ext.define('MyCustomButton', {
  extend: 'Ext.button.Button',
  // ... other configs,
  initComponent: function(){
    this.addEvents('myspecialevent1', 'myspecialevent2', 'myspecialevent3', /* ... */);
    // ...
    this.callParent(arguments);
  }
});
var myButton = Ext.create('MyCustomButton', { /* configs */ });

Preventing event bubbling

To prevent bubbling you can return false or use Ext.EventObject.preventDefault(). In order to prevent browser's default action use Ext.EventObject.stopPropagation().

For example let's assign click event handler to our button. And if not left button was clicked prevent default browser action:

myButton.on('click', function(btn, e){
  if (e.button !== 0)
    e.preventDefault();
});

How to target only IE (any version) within a stylesheet?

For targeting IE only in my stylesheets, I use this Sass Mixin :

@mixin ie-only {
  @media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {
    @content;
  }
}

Get method arguments using Spring AOP?

Yes, the value of any argument can be found using getArgs

@Before("execution(* com.mkyong.customer.bo.CustomerBo.addCustomer(..))")
public void logBefore(JoinPoint joinPoint) {

   Object[] signatureArgs = thisJoinPoint.getArgs();
   for (Object signatureArg: signatureArgs) {
      System.out.println("Arg: " + signatureArg);
      ...
   }
}

What is the difference between Python's list methods append and extend?

append(): It is basically used in Python to add one element.

Example 1:

>> a = [1, 2, 3, 4]
>> a.append(5)
>> print(a)
>> a = [1, 2, 3, 4, 5]

Example 2:

>> a = [1, 2, 3, 4]
>> a.append([5, 6])
>> print(a)
>> a = [1, 2, 3, 4, [5, 6]]

extend(): Where extend(), is used to merge two lists or insert multiple elements in one list.

Example 1:

>> a = [1, 2, 3, 4]
>> b = [5, 6, 7, 8]
>> a.extend(b)
>> print(a)
>> a = [1, 2, 3, 4, 5, 6, 7, 8]

Example 2:

>> a = [1, 2, 3, 4]
>> a.extend([5, 6])
>> print(a)
>> a = [1, 2, 3, 4, 5, 6]

How to check cordova android version of a cordova/phonegap project?

The current platform version of a cordova app can be checked by the following command

cordova platform version android

And can be upgraded using the command

cordova platform update android

You can replace android by any of your platform choice like "ios" or some else.

This only applies to android platform. I have not checked. You can try replacing android in the code segments to try for other platforms.

JavaScript OR (||) variable assignment explanation

Its called Short circuit operator.

Short-circuit evaluation says, the second argument is executed or evaluated only if the first argument does not suffice to determine the value of the expression. when the first argument of the OR (||) function evaluates to true, the overall value must be true.

It could also be used to set a default value for function argument.`

function theSameOldFoo(name){ 
  name = name || 'Bar' ;
  console.log("My best friend's name is " + name);
}
theSameOldFoo();  // My best friend's name is Bar
theSameOldFoo('Bhaskar');  // My best friend's name is Bhaskar`

Slicing a dictionary

the dictionary

d = {1:2, 3:4, 5:6, 7:8}

the subset of keys I'm interested in

l = (1,5)

answer

{key: d[key] for key in l}

sys.stdin.readline() reads without prompt, returning 'nothing in between'

Try this ...

import sys
buffer = []
while True:
    userinput = sys.stdin.readline().rstrip('\n')
    if userinput == 'quit':
        break
    else:
        buffer.append(userinput)

How to create a file in Linux from terminal window?

Depending on what you want the file to contain:

  • touch /path/to/file for an empty file
  • somecommand > /path/to/file for a file containing the output of some command.

      eg: grep --help > randomtext.txt
          echo "This is some text" > randomtext.txt
    
  • nano /path/to/file or vi /path/to/file (or any other editor emacs,gedit etc)
    It either opens the existing one for editing or creates & opens the empty file to enter, if it doesn't exist


Create the file using cat

$ cat > myfile.txt

Now, just type whatever you want in the file:

Hello World!

CTRL-D to save and exit


There are several possible solutions:

Create an empty file

touch file

>file

echo -n > file

printf '' > file

The echo version will work only if your version of echo supports the -n switch to suppress newlines. This is a non-standard addition. The other examples will all work in a POSIX shell.

Create a file containing a newline and nothing else

echo '' > file

printf '\n' > file

This is a valid "text file" because it ends in a newline.

Write text into a file

"$EDITOR" file

echo 'text' > file

cat > file <<END \
text
END

printf 'text\n' > file

These are equivalent. The $EDITOR command assumes that you have an interactive text editor defined in the EDITOR environment variable and that you interactively enter equivalent text. The cat version presumes a literal newline after the \ and after each other line. Other than that these will all work in a POSIX shell.

Of course there are many other methods of writing and creating files, too.

Converting date between DD/MM/YYYY and YYYY-MM-DD?

#case_date= 03/31/2020   

#Above is the value stored in case_date in format(mm/dd/yyyy )

demo=case_date.split("/")
new_case_date = demo[1]+"-"+demo[0]+"-"+demo[2]
#new format of date is (dd/mm/yyyy) test by printing it 
print(new_case_date)

jQuery.css() - marginLeft vs. margin-left?

jQuery's underlying code passes these strings to the DOM, which allows you to specify the CSS property name or the DOM property name in a very similar way:

element.style.marginLeft = "10px";

is equivalent to:

element.style["margin-left"] = "10px";

Why has jQuery allowed for marginLeft as well as margin-left? It seems pointless and uses more resources to be converted to the CSS margin-left?

jQuery's not really doing anything special. It may alter or proxy some strings that you pass to .css(), but in reality there was no work put in from the jQuery team to allow either string to be passed. There's no extra resources used because the DOM does the work.

Getting a directory name from a filename

I'm so surprised no one has mentioned the standard way in Posix

Please use basename / dirname constructs.

man basename

The ternary (conditional) operator in C

It's syntatic sugar and a handy shorthand for brief if/else blocks that only contain one statement. Functionally, both constructs should perform identically.

How to use executables from a package installed locally in node_modules?

Update: I no longer recommend this method, both for the mentioned security reasons and not the least the newer npm bin command. Original answer below:

As you have found out, any locally installed binaries are in ./node_modules/.bin. In order to always run binaries in this directory rather than globally available binaries, if present, I suggest you put ./node_modules/.bin first in your path:

export PATH="./node_modules/.bin:$PATH"

If you put this in your ~/.profile, coffee will always be ./node_modules/.bin/coffee if available, otherwise /usr/local/bin/coffee (or whatever prefix you are installing node modules under).

Execute a shell function with timeout

As Douglas Leeder said you need a separate process for timeout to signal to. Workaround by exporting function to subshells and running subshell manually.

export -f echoFooBar
timeout 10s bash -c echoFooBar

How to use data-binding with Fragment

You are actually encouraged to use the inflate method of your generated Binding and not the DataBindingUtil:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    MainFragmentBinding binding = MainFragmentBinding.inflate(inflater, container, false);
    //set variables in Binding
    return binding.getRoot();
}

Docs for DataBindingUtil.inflate():

Use this version only if layoutId is unknown in advance. Otherwise, use the generated Binding's inflate method to ensure type-safe inflation.

How do I search for a pattern within a text file using Python combining regex & string/file operations and store instances of the pattern?

Doing it in one bulk read:

import re

textfile = open(filename, 'r')
filetext = textfile.read()
textfile.close()
matches = re.findall("(<(\d{4,5})>)?", filetext)

Line by line:

import re

textfile = open(filename, 'r')
matches = []
reg = re.compile("(<(\d{4,5})>)?")
for line in textfile:
    matches += reg.findall(line)
textfile.close()

But again, the matches that returns will not be useful for anything except counting unless you added an offset counter:

import re

textfile = open(filename, 'r')
matches = []
offset = 0
reg = re.compile("(<(\d{4,5})>)?")
for line in textfile:
    matches += [(reg.findall(line),offset)]
    offset += len(line)
textfile.close()

But it still just makes more sense to read the whole file in at once.

How to extract extension from filename string in Javascript?

Use the lastIndexOf method to find the last period in the string, and get the part of the string after that:

var ext = fileName.substr(fileName.lastIndexOf('.') + 1);

SQL Data Reader - handling Null column values

Old question but maybe someone still need an answer

in real i worked around this issue like that

For int :

public static object GatDataInt(string Query, string Column)
    {
        SqlConnection DBConn = new SqlConnection(ConnectionString);
        if (DBConn.State == ConnectionState.Closed)
            DBConn.Open();
        SqlCommand CMD = new SqlCommand(Query, DBConn);
        SqlDataReader RDR = CMD.ExecuteReader();
        if (RDR.Read())
        {
            var Result = RDR[Column];
            RDR.Close();
            DBConn.Close();
            return Result;
        }
        return 0;
    }

the same for string just return "" instead of 0 as "" is empty string

so you can use it like

int TotalPoints = GatDataInt(QueryToGetTotalPoints, TotalPointColumn) as int?;

and

string Email = GatDatastring(QueryToGetEmail, EmailColumn) as string;

very flexible so you can insert any query to read any column and it'll never return with error

Android: View.setID(int id) programmatically - how to avoid ID conflicts?

I use:

public synchronized int generateViewId() {
    Random rand = new Random();
    int id;
    while (findViewById(id = rand.nextInt(Integer.MAX_VALUE) + 1) != null);
    return id;
}

By using a random number I always have a huge chance of getting the unique id in first attempt.

Php header location redirect not working

Neer to specify exit code here so php not execute further

if ((isset($_POST['cancel'])) && ($_POST['cancel'] == 'cancel'))
{
    header('Location: page1.php');        
    exit(0); // require to exit here 
}

Export javascript data to CSV file without server interaction

There's always the HTML5 download attribute :

This attribute, if present, indicates that the author intends the hyperlink to be used for downloading a resource so that when the user clicks on the link they will be prompted to save it as a local file.

If the attribute has a value, the value will be used as the pre-filled file name in the Save prompt that opens when the user clicks on the link.

var A = [['n','sqrt(n)']];

for(var j=1; j<10; ++j){ 
    A.push([j, Math.sqrt(j)]);
}

var csvRows = [];

for(var i=0, l=A.length; i<l; ++i){
    csvRows.push(A[i].join(','));
}

var csvString = csvRows.join("%0A");
var a         = document.createElement('a');
a.href        = 'data:attachment/csv,' +  encodeURIComponent(csvString);
a.target      = '_blank';
a.download    = 'myFile.csv';

document.body.appendChild(a);
a.click();

FIDDLE

Tested in Chrome and Firefox, works fine in the newest versions (as of July 2013).
Works in Opera as well, but does not set the filename (as of July 2013).
Does not seem to work in IE9 (big suprise) (as of July 2013).

An overview over what browsers support the download attribute can be found Here
For non-supporting browsers, one has to set the appropriate headers on the serverside.


Apparently there is a hack for IE10 and IE11, which doesn't support the download attribute (Edge does however).

var A = [['n','sqrt(n)']];

for(var j=1; j<10; ++j){ 
    A.push([j, Math.sqrt(j)]);
}

var csvRows = [];

for(var i=0, l=A.length; i<l; ++i){
    csvRows.push(A[i].join(','));
}

var csvString = csvRows.join("%0A");

if (window.navigator.msSaveOrOpenBlob) {
    var blob = new Blob([csvString]);
    window.navigator.msSaveOrOpenBlob(blob, 'myFile.csv');
} else {
    var a         = document.createElement('a');
    a.href        = 'data:attachment/csv,' +  encodeURIComponent(csvString);
    a.target      = '_blank';
    a.download    = 'myFile.csv';
    document.body.appendChild(a);
    a.click();
}

In Bash, how to add "Are you sure [Y/n]" to any command or alias?

To avoid explicitly checking for these variants of 'yes' you could use the bash regular expression operator '=~' with a regular expression:

read -p "Are you sure you want to continue? <y/N> " prompt
if [[ $prompt =~ [yY](es)* ]]
then
(etc...)

That tests whether the user input starts with 'y' or 'Y' and is followed by zero or more 'es's.

insert datetime value in sql database with c#

 DateTime time = DateTime.Now;              // Use current time
 string format = "yyyy-MM-dd HH:mm:ss";    // modify the format depending upon input required in the column in database 
 string insert = @" insert into Table(DateTime Column) values ('" + time.ToString(format) + "')"; 

and execute the query. DateTime.Now is to insert current Datetime..

C# with MySQL INSERT parameters

Try adjusting the code at "SqlDbType" to match your DB type if necessary and use this code:

comm.Parameters.Add("@person",SqlDbType.VarChar).Value=MyName;

or:

comm.Parameters.AddWithValue("@person", Myname);

That should work but remember with Command.Parameters.Add(), you can define the specific SqlDbType and with Command.Parameters.AddWithValue(), it will try get the SqlDbType based on parameter value implicitly which can break sometimes if it can not implicitly convert the datatype.

Hope this helps.

C# Get a control's position on a form

In my testing, both Hans Kesting's and Fredrik Mörk's solutions gave the same answer. But:

I found an interesting discrepancy in the answer using the methods of Raj More and Hans Kesting, and thought I'd share. Thanks to both though for their help; I can't believe such a method is not built into the framework.

Please note that Raj didn't write code and therefore my implementation could be different than he meant.

The difference I found was that the method from Raj More would often be two pixels greater (in both X and Y) than the method from Hans Kesting. I have not yet determined why this occurs. I'm pretty sure it has something to do with the fact that there seems to be a two-pixel border around the contents of a Windows form (as in, inside the form's outermost borders). In my testing, which was certainly not exhaustive to any extent, I've only come across it on controls that were nested. However, not all nested controls exhibit it. For example, I have a TextBox inside a GroupBox which exhibits the discrepancy, but a Button inside the same GroupBox does not. I cannot explain why.

Note that when the answers are equivalent, they consider the point (0, 0) to be inside the content border I mentioned above. Therefore I believe I'll consider the solutions from Hans Kesting and Fredrik Mörk to be correct but don't think I'll trust the solution I've implemented of Raj More's.

I also wondered exactly what code Raj More would have written, since he gave an idea but didn't provide code. I didn't fully understand the PointToScreen() method until I read this post: http://social.msdn.microsoft.com/Forums/en-US/netfxcompact/thread/aa91d4d8-e106-48d1-8e8a-59579e14f495

Here's my method for testing. Note that 'Method 1' mentioned in the comments is slightly different than Hans Kesting's.

private Point GetLocationRelativeToForm(Control c)
{
  // Method 1: walk up the control tree
  Point controlLocationRelativeToForm1 = new Point();
  Control currentControl = c;
  while (currentControl.Parent != null)
  {
    controlLocationRelativeToForm1.Offset(currentControl.Left, currentControl.Top);
    currentControl = currentControl.Parent;
  }

  // Method 2: determine absolute position on screen of control and form, and calculate difference
  Point controlScreenPoint = c.PointToScreen(Point.Empty);
  Point formScreenPoint = PointToScreen(Point.Empty);
  Point controlLocationRelativeToForm2 = controlScreenPoint - new Size(formScreenPoint);

  // Method 3: combine PointToScreen() and PointToClient()
  Point locationOnForm = c.FindForm().PointToClient(c.Parent.PointToScreen(c.Location));

  // Theoretically they should be the same
  Debug.Assert(controlLocationRelativeToForm1 == controlLocationRelativeToForm2);
  Debug.Assert(locationOnForm == controlLocationRelativeToForm1);
  Debug.Assert(locationOnForm == controlLocationRelativeToForm2);

  return controlLocationRelativeToForm1;
}

How to expire a cookie in 30 minutes using jQuery?

I had issues getting the above code to work within cookie.js. The following code managed to create the correct timestamp for the cookie expiration in my instance.

var inFifteenMinutes = new Date(new Date().getTime() + 15 * 60 * 1000);

This was from the FAQs for Cookie.js

Copy entire directory contents to another directory?

Neither FileUtils.copyDirectory() nor Archimedes's answer copy directory attributes (file owner, permissions, modification times, etc).

https://stackoverflow.com/a/18691793/14731 provides a complete JDK7 solution that does precisely that.

How can I replace a newline (\n) using sed?

Here is sed without buffers (good for real time output).
Example: replacing \n with <br/> break in HTML

echo -e "1\n2\n3" | sed 's/.*$/&<br\/>/'

ASP.NET MVC: What is the correct way to redirect to pages/actions in MVC?

1) When the user logs out (Forms signout in Action) I want to redirect to a login page.

public ActionResult Logout() {
    //log out the user
    return RedirectToAction("Login");
}

2) In a Controller or base Controller event eg Initialze, I want to redirect to another page (AbsoluteRootUrl + Controller + Action)

Why would you want to redirect from a controller init?

the routing engine automatically handles requests that come in, if you mean you want to redirect from the index action on a controller simply do:

public ActionResult Index() {
    return RedirectToAction("whateverAction", "whateverController");
}

Visual Studio Code cannot detect installed git

Version control

First install Git onto your desktop, then Add the encircled extension in vscode, as seen in the picture.

That helped me fix the same issue you have.

How to get rows count of internal table in abap?

The functional module EM_GET_NUMBER_OF_ENTRIES will also provide the row count. It takes 1 parameter - the table name.

How to access array elements in a Django template?

You can access sequence elements with arr.0 arr.1 and so on. See The Django template system chapter of the django book for more information.

check if directory exists and delete in one command unix

Why not just use rm -rf /some/dir? That will remove the directory if it's present, otherwise do nothing. Unlike rm -r /some/dir this flavor of the command won't crash if the folder doesn't exist.

How would I get a cron job to run every 30 minutes?

If your cron job is running on Mac OS X only, you may want to use launchd instead.

From Scheduling Timed Jobs (official Apple docs):

Note: Although it is still supported, cron is not a recommended solution. It has been deprecated in favor of launchd.

You can find additional information (such as the launchd Wikipedia page) with a simple web search.

How to clear the text of all textBoxes in the form?

Try this:

var t = this.Controls.OfType<TextBox>().AsEnumerable<TextBox>();
foreach (TextBox item in t)
{
    item.Text = "";
}

Can't fix Unsupported major.minor version 52.0 even after fixing compatibility

Several possiblies that causes this problem. The root cause is mismatched of compiler version between projects and IDE. For windows environment you can refer to this blog to do the detail troubleshooting.

Send XML data to webservice using php curl

After Struggling a bit with Arzoo International flight API, I've finally found the solution and the code simply works absolutely great with me. Here are the complete working code:

//Store your XML Request in a variable
    $input_xml = '<AvailRequest>
            <Trip>ONE</Trip>
            <Origin>BOM</Origin>
            <Destination>JFK</Destination>
            <DepartDate>2013-09-15</DepartDate>
            <ReturnDate>2013-09-16</ReturnDate>
            <AdultPax>1</AdultPax>
            <ChildPax>0</ChildPax>
            <InfantPax>0</InfantPax>
            <Currency>INR</Currency>
            <PreferredClass>E</PreferredClass>
            <Eticket>true</Eticket>
            <Clientid>777ClientID</Clientid>
            <Clientpassword>*Your API Password</Clientpassword>
            <Clienttype>ArzooINTLWS1.0</Clienttype>
            <PreferredAirline></PreferredAirline>
    </AvailRequest>';

Now I've made a little changes in the above curl_setopt declaration as follows:

    $url = "http://59.162.33.102:9301/Avalability";

        //setting the curl parameters.
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
// Following line is compulsary to add as it is:
        curl_setopt($ch, CURLOPT_POSTFIELDS,
                    "xmlRequest=" . $input_xml);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 300);
        $data = curl_exec($ch);
        curl_close($ch);

        //convert the XML result into array
        $array_data = json_decode(json_encode(simplexml_load_string($data)), true);

        print_r('<pre>');
        print_r($array_data);
        print_r('</pre>');

That's it the code works absolutely fine for me. I really appreciate @hakre & @Lucas For their wonderful support.

What's sizeof(size_t) on 32-bit vs the various 64-bit data models?

EDIT: Thanks for the comments - I looked it up in the C99 standard, which says in section 6.5.3.4:

The value of the result is implementation-defined, and its type (an unsigned integer type) is size_t, defined in <stddef.h> (and other headers)

So, the size of size_t is not specified, only that it has to be an unsigned integer type. However, an interesting specification can be found in chapter 7.18.3 of the standard:

limit of size_t

SIZE_MAX 65535

Which basically means that, irrespective of the size of size_t, the allowed value range is from 0-65535, the rest is implementation dependent.

Highlight a word with jQuery

$(function () {
    $("#txtSearch").keyup(function (event) {
        var txt = $("#txtSearch").val()
        if (txt.length > 3) {
            $("span.hilightable").each(function (i, v) {
                v.innerHTML = v.innerText.replace(txt, "<hilight>" + txt + "</hilight>");
            });

        }
    });
});

Jfiddle here

How can I find script's directory?

import os,sys
# Store current working directory
pwd = os.path.dirname(__file__)
# Append current directory to the python path
sys.path.append(pwd)

Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in

$result2 is resource link not a string to echo it or to replace some of its parts with str_replace().

http://php.net/manual/en/function.mysql-query.php

AngularJS - How to use $routeParams in generating the templateUrl?

templateUrl can be use as function with returning generated URL. We can manipulate url with passing argument which takes routeParams.

See the example.

.when('/:screenName/list',{
    templateUrl: function(params){
         return params.screenName +'/listUI'
    }
})

Hope this help.

$_POST vs. $_SERVER['REQUEST_METHOD'] == 'POST'

They both work the same way, but $_POST should be used as it is cleaner. You can add isset() to it to check it exists.

Set LIMIT with doctrine 2?

$limit=5; // for exemple

$query = $this->getDoctrine()->getEntityManager()->createQuery(
           '// your request')

->setMaxResults($limit);

 $results = $query->getResult();

// Done

Javascript/jQuery: Set Values (Selection) in a multiple Select

Pure JavaScript ES5 solution

For some reason you don't use jQuery nor ES6? This might help you:

_x000D_
_x000D_
var values = "Test,Prof,Off";_x000D_
var splitValues = values.split(',');_x000D_
var multi = document.getElementById('strings');_x000D_
_x000D_
multi.value = null; // Reset pre-selected options (just in case)_x000D_
var multiLen = multi.options.length;_x000D_
for (var i = 0; i < multiLen; i++) {_x000D_
  if (splitValues.indexOf(multi.options[i].value) >= 0) {_x000D_
    multi.options[i].selected = true;_x000D_
  }_x000D_
}
_x000D_
<select name='strings' id="strings" multiple style="width:100px;">_x000D_
    <option value="Test">Test</option>_x000D_
    <option value="Prof">Prof</option>_x000D_
    <option value="Live">Live</option>_x000D_
    <option value="Off">Off</option>_x000D_
    <option value="On" selected>On</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

How to use jQuery in AngularJS

You have to do binding in a directive. Look at this:

angular.module('ng', []).
directive('sliderRange', function($parse, $timeout){
    return {
        restrict: 'A',
        replace: true,
        transclude: false,
        compile: function(element, attrs) {            
            var html = '<div class="slider-range"></div>';
            var slider = $(html);
            element.replaceWith(slider);
            var getterLeft = $parse(attrs.ngModelLeft), setterLeft = getterLeft.assign;
            var getterRight = $parse(attrs.ngModelRight), setterRight = getterRight.assign;

            return function (scope, slider, attrs, controller) {
                var vsLeft = getterLeft(scope), vsRight = getterRight(scope), f = vsLeft || 0, t = vsRight || 10;                        

                var processChange = function() {
                    var vs = slider.slider("values"), f = vs[0], t = vs[1];                                        
                    setterLeft(scope, f);
                    setterRight(scope, t);                    
                }                 
                slider.slider({
                    range: true,
                    min: 0,
                    max: 10,
                    step: 1,
                    change: function() { setTimeout(function () { scope.$apply(processChange); }, 1) }
                }).slider("values", [f, t]);                    
            };            
        }
    };
});

This shows you an example of a slider range, done with jQuery UI. Example usage:

<div slider-range ng-model-left="question.properties.range_from" ng-model-right="question.properties.range_to"></div>

How to format a duration in java? (e.g format H:MM:SS)

This is easier since Java 9. A Duration still isn’t formattable, but methods for getting the hours, minutes and seconds are added, which makes the task somewhat more straightforward:

    LocalDateTime start = LocalDateTime.of(2019, Month.JANUARY, 17, 15, 24, 12);
    LocalDateTime end = LocalDateTime.of(2019, Month.JANUARY, 18, 15, 43, 33);
    Duration diff = Duration.between(start, end);
    String hms = String.format("%d:%02d:%02d", 
                                diff.toHours(), 
                                diff.toMinutesPart(), 
                                diff.toSecondsPart());
    System.out.println(hms);

The output from this snippet is:

24:19:21

How to style a div to have a background color for the entire width of the content, and not just for the width of the display?

It is because you set the width:100% which by definition only spans the width of the screen. You want to set the min-width:100% which sets it to the width of the screen... with the ability to grow beyond that.

Also make sure you set min-width:100% for body and html.

How to get the selected date of a MonthCalendar control in C#

I just noticed that if you do:

monthCalendar1.SelectionRange.Start.ToShortDateString() 

you will get only the date (e.g. 1/25/2014) from a MonthCalendar control.

It's opposite to:

monthCalendar1.SelectionRange.Start.ToString()

//The OUTPUT will be (e.g. 1/25/2014 12:00:00 AM)

Because these MonthCalendar properties are of type DateTime. See the msdn and the methods available to convert to a String representation. Also this may help to convert from a String to a DateTime object where applicable.

Python Requests - No connection adapters

One more reason, maybe your url include some hiden characters, such as '\n'.

If you define your url like below, this exception will raise:

url = '''
http://google.com
'''

because there are '\n' hide in the string. The url in fact become:

\nhttp://google.com\n

How to display Wordpress search results?

Basically, you need to include the Wordpress loop in your search.php template to loop through the search results and show them as part of the template.

Below is a very basic example from The WordPress Theme Search Template and Page Template over at ThemeShaper.

<?php
/**
 * The template for displaying Search Results pages.
 *
 * @package Shape
 * @since Shape 1.0
 */

get_header(); ?>

        <section id="primary" class="content-area">
            <div id="content" class="site-content" role="main">

            <?php if ( have_posts() ) : ?>

                <header class="page-header">
                    <h1 class="page-title"><?php printf( __( 'Search Results for: %s', 'shape' ), '<span>' . get_search_query() . '</span>' ); ?></h1>
                </header><!-- .page-header -->

                <?php shape_content_nav( 'nav-above' ); ?>

                <?php /* Start the Loop */ ?>
                <?php while ( have_posts() ) : the_post(); ?>

                    <?php get_template_part( 'content', 'search' ); ?>

                <?php endwhile; ?>

                <?php shape_content_nav( 'nav-below' ); ?>

            <?php else : ?>

                <?php get_template_part( 'no-results', 'search' ); ?>

            <?php endif; ?>

            </div><!-- #content .site-content -->
        </section><!-- #primary .content-area -->

<?php get_sidebar(); ?>
<?php get_footer(); ?>

PHP GuzzleHttp. How to make a post request with params?

Note in Guzzle V6.0+, another source of getting the following error may be incorrect use of JSON as an array:

Passing in the "body" request option as an array to send a POST request has been deprecated. Please use the "form_params" request option to send a application/x-www-form-urlencoded request, or a the "multipart" request option to send a multipart/form-data request.

Incorrect:

$response = $client->post('http://example.com/api', [
    'body' => [
        'name' => 'Example name',
    ]
])

Correct:

$response = $client->post('http://example.com/api', [
    'json' => [
        'name' => 'Example name',
    ]
])

Correct:

$response = $client->post('http://example.com/api', [
    'headers' => ['Content-Type' => 'application/json'],
    'body' => json_encode([
        'name' => 'Example name',
    ])
])

How to test whether a service is running from the command line

Try

sc query state= all 

for a list of services and whether they are running or not.

How do I delete multiple rows in Entity Framework (without foreach)

You can execute sql queries directly as follows :

    private int DeleteData()
{
    using (var ctx = new MyEntities(this.ConnectionString))
    {
        if (ctx != null)
        {

            //Delete command
            return ctx.ExecuteStoreCommand("DELETE FROM ALARM WHERE AlarmID > 100");

        }
    }
    return 0;
}

For select we may use

using (var context = new MyContext()) 
{ 
    var blogs = context.MyTable.SqlQuery("SELECT * FROM dbo.MyTable").ToList(); 
}

using CASE in the WHERE clause

This is working Oracle example but it should work in MySQL too.

You are missing smth - see IN after END Replace 'IN' with '=' sign for a single value.

SELECT empno, ename, job
  FROM scott.emp
 WHERE (CASE WHEN job = 'MANAGER' THEN '1'  
         WHEN job = 'CLERK'   THEN '2' 
         ELSE '0'  END) IN (1, 2)

Javadoc link to method in other class

So the solution to the original problem is that you don't need both the "@see" and the "{@link...}" references on the same line. The "@link" tag is self-sufficient and, as noted, you can put it anywhere in the javadoc block. So you can mix the two approaches:

/**
 * some javadoc stuff
 * {@link com.my.package.Class#method()}
 * more stuff
 * @see com.my.package.AnotherClass
 */

Python check if list items are integers?

You can use exceptional handling as str.digit will only work for integers and can fail for something like this too:

>>> str.isdigit(' 1')
False

Using a generator function:

def solve(lis):                                        
    for x in lis:
        try:
            yield float(x)
        except ValueError:    
            pass

>>> mylist = ['1','orange','2','3','4','apple', '1.5', '2.6']
>>> list(solve(mylist))                                    
[1.0, 2.0, 3.0, 4.0, 1.5, 2.6]   #returns converted values

or may be you wanted this:

def solve(lis):
    for x in lis:
        try:
            float(x)
            return True
        except:
            return False
...         
>>> mylist = ['1','orange','2','3','4','apple', '1.5', '2.6']
>>> [x for x in mylist if solve(x)]
['1', '2', '3', '4', '1.5', '2.6']

or using ast.literal_eval, this will work for all types of numbers:

>>> from ast import literal_eval
>>> def solve(lis):
    for x in lis:
        try:
            literal_eval(x)
            return True
        except ValueError:   
             return False
...         
>>> mylist=['1','orange','2','3','4','apple', '1.5', '2.6', '1+0j']
>>> [x for x in mylist if solve(x)]                               
['1', '2', '3', '4', '1.5', '2.6', '1+0j']

How to loop through an array containing objects and access their properties

Accepted answer uses normal function. So posting the same code with slight modification using arrow function on forEach

  yourArray.forEach(arrayItem => {
      var x = arrayItem.prop1 + 2;
      console.log(x);
  });

Also in $.each you can use arrow function like below

 $.each(array, (item, index) => {
       console.log(index, item);
 });

How to debug "ImagePullBackOff"?

You can use the 'describe pod' syntax

For OpenShift use:

oc describe pod <pod-id>  

For vanilla Kubernetes:

kubectl describe pod <pod-id>  

Examine the events of the output. In my case it shows Back-off pulling image coredns/coredns:latest

In this case the image coredns/coredns:latest can not be pulled from the Internet.

Events:
  FirstSeen LastSeen    Count   From                SubObjectPath           Type        Reason      Message
  --------- --------    -----   ----                -------------           --------    ------      -------
  5m        5m      1   {default-scheduler }                        Normal      Scheduled   Successfully assigned coredns-4224169331-9nhxj to 192.168.122.190
  5m        1m      4   {kubelet 192.168.122.190}   spec.containers{coredns}    Normal      Pulling     pulling image "coredns/coredns:latest"
  4m        26s     4   {kubelet 192.168.122.190}   spec.containers{coredns}    Warning     Failed      Failed to pull image "coredns/coredns:latest": Network timed out while trying to connect to https://index.docker.io/v1/repositories/coredns/coredns/images. You may want to check your internet connection or if you are behind a proxy.
  4m        26s     4   {kubelet 192.168.122.190}                   Warning     FailedSync  Error syncing pod, skipping: failed to "StartContainer" for "coredns" with ErrImagePull: "Network timed out while trying to connect to https://index.docker.io/v1/repositories/coredns/coredns/images. You may want to check your Internet connection or if you are behind a proxy."

  4m    2s  7   {kubelet 192.168.122.190}   spec.containers{coredns}    Normal  BackOff     Back-off pulling image "coredns/coredns:latest"
  4m    2s  7   {kubelet 192.168.122.190}                   Warning FailedSync  Error syncing pod, skipping: failed to "StartContainer" for "coredns" with ImagePullBackOff: "Back-off pulling image \"coredns/coredns:latest\""

Additional debuging steps

  1. try to pull the docker image and tag manually on your computer
  2. Identify the node by doing a 'kubectl/oc get pods -o wide'
  3. ssh into the node (if you can) that can not pull the docker image
  4. check that the node can resolve the DNS of the docker registry by performing a ping.
  5. try to pull the docker image manually on the node
  6. If you are using a private registry, check that your secret exists and the secret is correct. Your secret should also be in the same namespace. Thanks swenzel
  7. Some registries have firewalls that limit ip address access. The firewall may block the pull
  8. Some CIs create deployments with temporary docker secrets. So the secret expires after a few days (You are asking for production failures...)

Jquery DatePicker Set default date

Code to display current date in element input or datepicker with ID="mydate"

Don't forget add reference to jquery-ui-*.js

    $(document).ready(function () {
        var dateNewFormat, onlyDate, today = new Date();

        dateNewFormat = today.getFullYear() + '-' + (today.getMonth() + 1);

        onlyDate = today.getDate();

        if (onlyDate.toString().length == 2) {
            dateNewFormat += '-' + onlyDate;
        }
        else {
            dateNewFormat += '-0' + onlyDate;
        }
        $('#mydate').val(dateNewFormat);
    });

Android: ScrollView vs NestedScrollView

I think one Benefit of using Nested Scroll view is that the cooridinator layout only listens for nested scroll events. So if for ex. you want the toolbar to scroll down when you scroll you content of activity, it will only scroll down when you are using nested scroll view in your layout. If you use a normal scroll view in your layout, the toolbar wont scroll when the user scrolls the content.

Edit Crystal report file without Crystal Report software

My dad moved his office after 30 year and they need to update the address in the header of their Crystal Reports 7 (1997!) based billing system.

After buying old copies of Access 97 and Visual Studio 2003 Pro, I found out that both programs were too new - they could open the RPT files, but they saved them with an updated version that would not open in the billing system.

I ended up being able to make the changes using this life-saver program...

http://www.softwareforces.com/Products/rpt-inspector-professional-suite-for-crystal-reports

It was available with a 10 day free trial, and I only needed about 10 minutes to make my changes. That said, I would have happily paid whatever they asked for it. :)

Some hints:

  1. When I opened my RPT files, I got an error saving the database could not be found. I ignored this error and everything worked fine.
  2. Because my RPT files were Crystal Reports version 7, I had to go into Options->Misc and tell the program to save in the old format...

enter image description here

Error: "Input is not proper UTF-8, indicate encoding !" using PHP's simplexml_load_string

Your 0xED 0x6E 0x2C 0x20 bytes correspond to "ín, " in ISO-8859-1, so it looks like your content is in ISO-8859-1, not UTF-8. Tell your data provider about it and ask them to fix it, because if it doesn't work for you it probably doesn't work for other people either.

Now there are a few ways to work it around, which you should only use if you cannot load the XML normally. One of them would be to use utf8_encode(). The downside is that if that XML contains both valid UTF-8 and some ISO-8859-1 then the result will contain mojibake. Or you can try to convert the string from UTF-8 to UTF-8 using iconv() or mbstring, and hope they'll fix it for you. (they won't, but you can at least ignore the invalid characters so you can load your XML)

Or you can take the long, long road and validate/fix the sequences by yourself. That will take you a while depending on how familiar you are with UTF-8. Perhaps there are libraries out there that would do that, although I don't know any.

Either way, notify your data provider that they're sending invalid data so that they can fix it.


Here's a partial fix. It will definitely not fix everything, but will fix some of it. Hopefully enough for you to get by until your provider fix their stuff.

function fix_latin1_mangled_with_utf8_maybe_hopefully_most_of_the_time($str)
{
    return preg_replace_callback('#[\\xA1-\\xFF](?![\\x80-\\xBF]{2,})#', 'utf8_encode_callback', $str);
}

function utf8_encode_callback($m)
{
    return utf8_encode($m[0]);
}

How to add extension methods to Enums

According to this site:

Extension methods provide a way to write methods for existing classes in a way other people on your team might actually discover and use. Given that enums are classes like any other it shouldn’t be too surprising that you can extend them, like:

enum Duration { Day, Week, Month };

static class DurationExtensions 
{
  public static DateTime From(this Duration duration, DateTime dateTime) 
  {
    switch (duration) 
    {
      case Day:   return dateTime.AddDays(1);
      case Week:  return dateTime.AddDays(7);
      case Month: return dateTime.AddMonths(1);
      default:    throw new ArgumentOutOfRangeException("duration");
    }
  }
}

I think enums are not the best choice in general but at least this lets you centralize some of the switch/if handling and abstract them away a bit until you can do something better. Remember to check the values are in range too.

You can read more here at Microsft MSDN.

Output data from all columns in a dataframe in pandas

you can also use DataFrame.head(x) / .tail(x) to display the first / last x rows of the DataFrame.

Find all files in a directory with extension .txt in Python

To get all '.txt' file names inside 'dataPath' folder as a list in a Pythonic way:

from os import listdir
from os.path import isfile, join
path = "/dataPath/"
onlyTxtFiles = [f for f in listdir(path) if isfile(join(path, f)) and  f.endswith(".txt")]
print onlyTxtFiles

PKIX path building failed in Java application

If you are using Eclipse just cross check in Eclipse Windows--> preferences---->java---> installed JREs is pointing the current JRE and the JRE where you have configured your certificate. If not remove the JRE and add the jre where your certificate is installed

Calling async method on button click

use below code

 Task.WaitAll(Task.Run(async () => await GetResponse<MyObject>("my url")));

How to remove the arrows from input[type="number"] in Opera

There is no way.

This question is basically a duplicate of Is there a way to hide the new HTML5 spinbox controls shown in Google Chrome & Opera? but maybe not a full duplicate, since the motivation is given.

If the purpose is “browser's awareness of the content being purely numeric”, then you need to consider what that would really mean. The arrows, or spinners, are part of making numeric input more comfortable in some cases. Another part is checking that the content is a valid number, and on browsers that support HTML5 input enhancements, you might be able to do that using the pattern attribute. That attribute may also affect a third input feature, namely the type of virtual keyboard that may appear.

For example, if the input should be exactly five digits (like postal numbers might be, in some countries), then <input type="text" pattern="[0-9]{5}"> could be adequate. It is of course implementation-dependent how it will be handled.

Removing address bar from browser (to view on Android)

The one below works for me every time..

This site also has a few other suggestions, but this no-nonsense, no-worry one is available in a github:gist and answers your question (pasted here for convenience):

function hideAddressBar()
{
  if(!window.location.hash)
  {
      if(document.height < window.outerHeight)
      {
          document.body.style.height = (window.outerHeight + 50) + 'px';
      }

      setTimeout( function(){ window.scrollTo(0, 1); }, 50 );
  }
}

window.addEventListener("load", function(){ if(!window.pageYOffset){ hideAddressBar(); } } );
window.addEventListener("orientationchange", hideAddressBar );

As far as I can tell, the combination of extra height added to the page (which caused problems for you) and the scrollTo() statement make the address bar disappear.

From the same site the 'simplest' solution to hiding the address bar is using the scrollTo() method:

window.addEventListener("load", function() { window.scrollTo(0, 1); });

This will hide the address bar until the user scrolls.

This site places the same method inside a timeout function (the justification is not explained, but it claims the code doesn't work well without it):

// When ready...
window.addEventListener("load",function() {
  // Set a timeout...
  setTimeout(function(){
    // Hide the address bar!
     window.scrollTo(0, 1);
  }, 0);
});

How can I do an OrderBy with a dynamic string parameter?

Look at this blog here. It describes a way to do this, by defining an EntitySorter<T>.

It allows you to pass in an IEntitySorter<T> into your service methods and use it like this:

public static Person[] GetAllPersons(IEntitySorter<Person> sorter)
{
    using (var db = ContextFactory.CreateContext())
    {
        IOrderedQueryable<Person> sortedList = sorter.Sort(db.Persons);

        return sortedList.ToArray();
    }
}

And you can create an EntitiySorter like this:

IEntitySorter<Person> sorter = EntitySorter<Person>
    .OrderBy(p => p.Name)
    .ThenByDescending(p => p.Id);

Or like this:

var sorter = EntitySorter<Person>
     .OrderByDescending("Address.City")
     .ThenBy("Id");

How to normalize a histogram in MATLAB?

Since 2014b, Matlab has these normalization routines embedded natively in the histogram function (see the help file for the 6 routines this function offers). Here is an example using the PDF normalization (the sum of all the bins is 1).

data = 2*randn(5000,1) + 5;             % generate normal random (m=5, std=2)
h = histogram(data,'Normalization','pdf')   % PDF normalization

The corresponding PDF is

Nbins = h.NumBins;
edges = h.BinEdges; 
x = zeros(1,Nbins);
for counter=1:Nbins
    midPointShift = abs(edges(counter)-edges(counter+1))/2;
    x(counter) = edges(counter)+midPointShift;
end

mu = mean(data);
sigma = std(data);

f = exp(-(x-mu).^2./(2*sigma^2))./(sigma*sqrt(2*pi));

The two together gives

hold on;
plot(x,f,'LineWidth',1.5)

enter image description here

An improvement that might very well be due to the success of the actual question and accepted answer!


EDIT - The use of hist and histc is not recommended now, and histogram should be used instead. Beware that none of the 6 ways of creating bins with this new function will produce the bins hist and histc produce. There is a Matlab script to update former code to fit the way histogram is called (bin edges instead of bin centers - link). By doing so, one can compare the pdf normalization methods of @abcd (trapz and sum) and Matlab (pdf).

The 3 pdf normalization method give nearly identical results (within the range of eps).

TEST:

A = randn(10000,1);
centers = -6:0.5:6;
d = diff(centers)/2;
edges = [centers(1)-d(1), centers(1:end-1)+d, centers(end)+d(end)];
edges(2:end) = edges(2:end)+eps(edges(2:end));

figure;
subplot(2,2,1);
hist(A,centers);
title('HIST not normalized');

subplot(2,2,2);
h = histogram(A,edges);
title('HISTOGRAM not normalized');

subplot(2,2,3)
[counts, centers] = hist(A,centers); %get the count with hist
bar(centers,counts/trapz(centers,counts))
title('HIST with PDF normalization');


subplot(2,2,4)
h = histogram(A,edges,'Normalization','pdf')
title('HISTOGRAM with PDF normalization');

dx = diff(centers(1:2))
normalization_difference_trapz = abs(counts/trapz(centers,counts) - h.Values);
normalization_difference_sum = abs(counts/sum(counts*dx) - h.Values);

max(normalization_difference_trapz)
max(normalization_difference_sum)

enter image description here

The maximum difference between the new PDF normalization and the former one is 5.5511e-17.

How to code a BAT file to always run as admin mode?

You use runas to launch a program as a specific user:

runas /user:Administrator Example1Server.exe

MVC which submit button has been pressed

Can you not find out using Request.Form Collection? If process is clicked the request.form["process"] will not be empty

Excel VBA to Export Selected Sheets to PDF

Once you have Selected a group of sheets, you can use Selection

Consider:

Sub luxation()
    ThisWorkbook.Sheets(Array("Sheet1", "Sheet2", "Sheet3")).Select
    Selection.ExportAsFixedFormat _
        Type:=xlTypePDF, _
        Filename:="C:\TestFolder\temp.pdf", _
        Quality:=xlQualityStandard, _
        IncludeDocProperties:=True, _
        IgnorePrintAreas:=False, _
        OpenAfterPublish:=True
End Sub

EDIT#1:

Further testing has reveled that this technique depends on the group of cells selected on each worksheet. To get a comprehensive output, use something like:

Sub Macro1()

   Sheets("Sheet1").Activate
   ActiveSheet.UsedRange.Select
   Sheets("Sheet2").Activate
   ActiveSheet.UsedRange.Select
   Sheets("Sheet3").Activate
   ActiveSheet.UsedRange.Select

   ThisWorkbook.Sheets(Array("Sheet1", "Sheet2", "Sheet3")).Select
   Selection.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
      "C:\Users\James\Desktop\pdfmaker.pdf", Quality:=xlQualityStandard, _
      IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
      True
End Sub

LINQ Inner-Join vs Left-Join

You need to get the joined objects into a set and then apply DefaultIfEmpty as JPunyon said:

Person magnus = new Person { Name = "Hedlund, Magnus" };
Person terry = new Person { Name = "Adams, Terry" };
Person charlotte = new Person { Name = "Weiss, Charlotte" };

Pet barley = new Pet { Name = "Barley", Owner = terry };
List<Person> people = new List<Person> { magnus, terry, charlotte };
List<Pet> pets = new List<Pet>{barley};

var results =
    from person in people
    join pet in pets on person.Name equals pet.Owner.Name into ownedPets
    from ownedPet in ownedPets.DefaultIfEmpty(new Pet())
    orderby person.Name
    select new { OwnerName = person.Name, ownedPet.Name };


foreach (var item in results)
{
    Console.WriteLine(
        String.Format("{0,-25} has {1}", item.OwnerName, item.Name ) );
}

Outputs:

Adams, Terry              has Barley
Hedlund, Magnus           has
Weiss, Charlotte          has

How to print float to n decimal places including trailing 0s?

Floating point numbers lack precision to accurately represent "1.6" out to that many decimal places. The rounding errors are real. Your number is not actually 1.6.

Check out: http://docs.python.org/library/decimal.html

__FILE__ macro shows full path

I have just thought of a great solution to this that works with both source and header files, is very efficient and works on compile time in all platforms without compiler-specific extensions. This solution also preserves the relative directory structure of your project, so you know in which folder the file is in, and only relative to the root of your project.

The idea is to get the size of the source directory with your build tool and just add it to the __FILE__ macro, removing the directory entirely and only showing the file name starting at your source directory.

The following example is implemented using CMake, but there's no reason it wouldn't work with any other build tools, because the trick is very simple.

On the CMakeLists.txt file, define a macro that has the length of the path to your project on CMake:

# The additional / is important to remove the last character from the path.
# Note that it does not matter if the OS uses / or \, because we are only
# saving the path size.
string(LENGTH "${CMAKE_SOURCE_DIR}/" SOURCE_PATH_SIZE)
add_definitions("-DSOURCE_PATH_SIZE=${SOURCE_PATH_SIZE}")

On your source code, define a __FILENAME__ macro that just adds the source path size to the __FILE__ macro:

#define __FILENAME__ (__FILE__ + SOURCE_PATH_SIZE)

Then just use this new macro instead of the __FILE__ macro. This works because the __FILE__ path will always start with the path to your CMake source dir. By removing it from the __FILE__ string the preprocessor will take care of specifying the correct file name and it will all be relative to the root of your CMake project.

If you care about the performance, this is as efficient as using __FILE__, because both __FILE__ and SOURCE_PATH_SIZE are known compile time constants, so it can be optimized away by the compiler.

The only place where this would fail is if you're using this on generated files and they're on a off-source build folder. Then you'll probably have to create another macro using the CMAKE_BUILD_DIR variable instead of CMAKE_SOURCE_DIR.

Display progress bar while doing some work in C#?

Here is another sample code to use BackgroundWorker to update ProgressBar, just add BackgroundWorker and Progressbar to your main form and use below code:

public partial class Form1 : Form
{
    public Form1()
    {
      InitializeComponent();
      Shown += new EventHandler(Form1_Shown);

    // To report progress from the background worker we need to set this property
    backgroundWorker1.WorkerReportsProgress = true;
    // This event will be raised on the worker thread when the worker starts
    backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
    // This event will be raised when we call ReportProgress
    backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
}
void Form1_Shown(object sender, EventArgs e)
{
    // Start the background worker
    backgroundWorker1.RunWorkerAsync();
}
// On worker thread so do our thing!
void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    // Your background task goes here
    for (int i = 0; i <= 100; i++)
    {
        // Report progress to 'UI' thread
        backgroundWorker1.ReportProgress(i);
        // Simulate long task
        System.Threading.Thread.Sleep(100);
    }
}
// Back on the 'UI' thread so we can update the progress bar
void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    // The progress percentage is a property of e
    progressBar1.Value = e.ProgressPercentage;
}
}

refrence:from codeproject

How to return more than one value from a function in Python?

You separate the values you want to return by commas:

def get_name():
   # you code
   return first_name, last_name

The commas indicate it's a tuple, so you could wrap your values by parentheses:

return (first_name, last_name)

Then when you call the function you a) save all values to one variable as a tuple, or b) separate your variable names by commas

name = get_name() # this is a tuple
first_name, last_name = get_name()
(first_name, last_name) = get_name() # You can put parentheses, but I find it ugly

Is it valid to replace http:// with // in a <script src="http://...">?

are there any cases where it doesn't work?

If the parent page was loaded from file://, then it probably does not work (it will try to get file://cdn.example.com/js_file.js, which of course you could provide locally as well).

Conversion from byte array to base64 and back

The reason the encoded array is longer by about a quarter is that base-64 encoding uses only six bits out of every byte; that is its reason of existence - to encode arbitrary data, possibly with zeros and other non-printable characters, in a way suitable for exchange through ASCII-only channels, such as e-mail.

The way you get your original array back is by using Convert.FromBase64String:

 byte[] temp_backToBytes = Convert.FromBase64String(temp_inBase64);

datetime datatype in java

java.time

The java.time framework built into Java 8 and later supplants both the old date-time classes bundled with the earliest versions of Java and the Joda-Time library. The java.time classes have been back-ported to Java 6 & 7 and to Android.

The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds.

Instant instant = Instant.now();

Apply an offset-from-UTC (a number of hours and possible minutes and seconds) to get an OffsetDateTime.

ZoneOffset offset = ZoneOffset.of( "-04:00" );
OffsetDateTime odt = OffsetDateTime.ofInstant( instant , offset );

Better yet is applying a full time zone which is an offset plus a set of rules for handling anomalies such as Daylight Saving Time (DST).

ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );

Database

Hopefully the JDBC drivers will be updated to work directly with the java.time classes. Until then we must use the java.sql classes to move date-time values to/from the database. But limit your use of the java.sql classes to the chore of database transit. Do not use them for business logic. As part of the old date-time classes they are poorly designed, confusing, and troublesome.

Use new methods added to the old classes to convert to/from java.time. Look for to… and valueOf methods.

Use the java.sql.Timestamp class for date-time values.

java.sql.Timestamp ts = java.sql.Timestamp.valueOf( instant );

And going the other direction…

Instant instant = ts.toInstant();

For date-time data you virtually always want the TIMESTAMP WITH TIME ZONE data type rather than WITHOUT when designing your table columns in your database.

HTML text-overflow ellipsis detection

My implementation)

_x000D_
_x000D_
const items = Array.from(document.querySelectorAll('.item'));_x000D_
items.forEach(item =>{_x000D_
    item.style.color = checkEllipsis(item) ? 'red': 'black'_x000D_
})_x000D_
_x000D_
function checkEllipsis(el){_x000D_
  const styles = getComputedStyle(el);_x000D_
  const widthEl = parseFloat(styles.width);_x000D_
  const ctx = document.createElement('canvas').getContext('2d');_x000D_
  ctx.font = `${styles.fontSize} ${styles.fontFamily}`;_x000D_
  const text = ctx.measureText(el.innerText);_x000D_
  return text.width > widthEl;_x000D_
}
_x000D_
.item{_x000D_
  width: 60px;_x000D_
  overflow: hidden;_x000D_
  text-overflow: ellipsis;_x000D_
}
_x000D_
      <div class="item">Short</div>_x000D_
      <div class="item">Loooooooooooong</div>
_x000D_
_x000D_
_x000D_

SQL order string as number

If possible you should change the data type of the column to a number if you only store numbers anyway.

If you can't do that then cast your column value to an integer explicitly with

select col from yourtable
order by cast(col as unsigned)

or implicitly for instance with a mathematical operation which forces a conversion to number

select col from yourtable
order by col + 0

BTW MySQL converts strings from left to right. Examples:

string value  |  integer value after conversion
--------------+--------------------------------
'1'           |  1
'ABC'         |  0   /* the string does not contain a number, so the result is 0 */
'123miles'    |  123 
'$123'        |  0   /* the left side of the string does not start with a number */