Programs & Examples On #Dna sequence

A string representing the nucleotide sequence of the deoxyribonucleic acid, the molecule that holds the genes that constitute the genetic code.

How to call a RESTful web service from Android?

Using Spring for Android with RestTemplate

// The connection URL 
String url = "" + 

// Create a new RestTemplate instance
RestTemplate restTemplate = new RestTemplate();

// Add the String message converter
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());

// Make the HTTP GET request, marshaling the response to a String
String result = restTemplate.getForObject(url, String.class, "Android");

Android transparent status bar and actionbar

I'm developing an app that needs to look similar in all devices with >= API14 when it comes to actionbar and statusbar customization. I've finally found a solution and since it took a bit of my time I'll share it to save some of yours. We start by using an appcompat-21 dependency.

Transparent Actionbar:


<style name="AppTheme" parent="Theme.AppCompat.Light">

<style name="AppTheme.ActionBar.Transparent" parent="AppTheme">
    <item name="android:windowContentOverlay">@null</item>
    <item name="windowActionBarOverlay">true</item>
    <item name="colorPrimary">@android:color/transparent</item>

<style name="AppTheme.ActionBar" parent="AppTheme">
    <item name="windowActionBarOverlay">false</item>
    <item name="colorPrimary">@color/default_yellow</item>


<style name="AppTheme" parent="Theme.AppCompat.Light">

<style name="AppTheme.ActionBar.Transparent" parent="AppTheme">
    <item name="colorPrimary">@android:color/transparent</item>

<style name="AppTheme.ActionBar" parent="AppTheme">
    <item name="colorPrimaryDark">@color/bg_colorPrimaryDark</item>
    <item name="colorPrimary">@color/default_yellow</item>

Now you can use these themes in your AndroidManifest.xml to specify which activities will have a transparent or colored ActionBar:



enter image description here enter image description here enter image description here enter image description here enter image description here

Note: in API>=21 to get the Actionbar transparent you need to get the Statusbar transparent too, otherwise will not respect your colour styles and will stay light-grey.

Transparent Statusbar (only works with API>=19):
This one it's pretty simple just use the following code:

protected void setStatusBarTranslucent(boolean makeTranslucent) {
        if (makeTranslucent) {
        } else {

But you'll notice a funky result: enter image description here

This happens because when the Statusbar is transparent the layout will use its height. To prevent this we just need to:

Add this line android:fitsSystemWindows="true" in your layout view container of whatever you want to be placed bellow the Actionbar:


Add a few lines to our previous method:

protected void setStatusBarTranslucent(boolean makeTranslucent) {
        View v = findViewById(;
        if (v != null) {
            int paddingTop = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT ? MyScreenUtils.getStatusBarHeight(this) : 0;
            TypedValue tv = new TypedValue();
            getTheme().resolveAttribute(, tv, true);
            paddingTop += TypedValue.complexToDimensionPixelSize(, getResources().getDisplayMetrics());
            v.setPadding(0, makeTranslucent ? paddingTop : 0, 0, 0);

        if (makeTranslucent) {
        } else {

Where will be the layout container view id of whatever we want to be placed bellow the Actionbar:


enter image description here

So this is it, it think I'm not forgetting something. In this example I didn't use a Toolbar but I think it'll have the same result. This is how I customize my Actionbar:

    protected void onCreate(Bundle savedInstanceState) {
        View vg = getActionBarView();
        getWindow().requestFeature(vg != null ? Window.FEATURE_ACTION_BAR : Window.FEATURE_NO_TITLE);


        if (vg != null) {
            getSupportActionBar().setCustomView(vg, new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));

Note: this is an abstract class that extends ActionBarActivity
Hope it helps!

How to pass a form input value into a JavaScript function

Give your inputs names it will make it easier

<input type="text" id="formValueId" name="valueId"/>
<input type="button" onclick="foo(this.form.valueId.value)"/>


If you give your button an id things can be even easier:

<input type="text" id="formValueId" name="valueId"/>
<input type="button" id="theButton"/>


var button = document.getElementById("theButton"),
value =  button.form.valueId.value;
button.onclick = function() {

What to do on TransactionTooLargeException

Our app also has this problem. After testing, it is found that when the application memory is insufficient and the activity is recycled, the system calls the onSaveInstanceState method to save a large amount of bundle data, and the data becomes large every time, and finally a TransactionTooLargeException error will be reported, so I think of this method should be able to solve this problem.

public final int MAX_BUNDLE_SIZE = 300;
protected void onSaveInstanceState(@NonNull Bundle outState) {
     long bundleSize = getBundleSize(outState);
     if (bundleSize > MAX_BUNDLE_SIZE * 1024) {

private long getBundleSize(Bundle bundle) {
     long dataSize;
     Parcel obtain = Parcel.obtain();
     try {
         dataSize = obtain.dataSize();
     } finally {
     return dataSize;

Make hibernate ignore class variables that are not mapped

JPA will use all properties of the class, unless you specifically mark them with @Transient:

private String agencyName;

The @Column annotation is purely optional, and is there to let you override the auto-generated column name. Furthermore, the length attribute of @Column is only used when auto-generating table definitions, it has no effect on the runtime.

Type definition in object literal in TypeScript

I'm surprised that no-one's mentioned this but you could just create an interface called ObjectLiteral, that accepts key: value pairs of type string: any:

interface ObjectLiteral {
  [key: string]: any;

Then you'd use it, like this:

let data: ObjectLiteral = {
  hello: "world",
  goodbye: 1,
  // ...

An added bonus is that you can re-use this interface many times as you need, on as many objects you'd like.

Good luck.

android: changing option menu items programmatically

For anyone needs to change the options of the menu dynamically:

private Menu menu;

// ...

public boolean onCreateOptionsMenu(Menu menu)
{ = menu;
    getMenuInflater().inflate(, menu);
    return true;

// ...

private void hideOption(int id)
    MenuItem item = menu.findItem(id);

private void showOption(int id)
    MenuItem item = menu.findItem(id);

private void setOptionTitle(int id, String title)
    MenuItem item = menu.findItem(id);

private void setOptionIcon(int id, int iconRes)
    MenuItem item = menu.findItem(id);

Swift: print() vs println() vs NSLog()

  1. NSLog - add meta info (like timestamp and identifier) and allows you to output 1023 symbols. Also print message into Console. The slowest method
@import Foundation
  1. print - prints all string to Xcode. Has better performance than previous
@import Foundation
  1. println (only available Swift v1) and add \n at the end of string
  2. os_log (from iOS v10) - prints 32768 symbols also prints to console. Has better performance than previous
@import os.log
os_log("SomeIntro: %@", log: .default, type: .info, "someString")
  1. Logger (from iOS v14) - prints 32768 symbols also prints to console. Has better performance than previous
@import os
let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "someCategory")

Form inside a form, is that alright?

No we can't nest forms within another form like this

<form name='form1'>
      <form name='form2'>
            //some code here

it will work in some cases but it is not recommended for universal platforms. You can use plenty of SUBMIT buttons inside a single form, but you can't manage a nested form appropriately.

Change the borderColor of the TextBox

set Text box Border style to None then write this code to container form "paint" event

private void Form1_Paint(object sender, PaintEventArgs e)
    System.Drawing.Rectangle rect = new Rectangle(TextBox1.Location.X, 
    TextBox1.Location.Y, TextBox1.ClientSize.Width, TextBox1.ClientSize.Height);
                rect.Inflate(1, 1); // border thickness
                System.Windows.Forms.ControlPaint.DrawBorder(e.Graphics, rect, 
    Color.DeepSkyBlue, ButtonBorderStyle.Solid);

How does Facebook disable the browser's integrated Developer Tools?

I located the Facebook's console buster script using Chrome developer tools. Here is the script with minor changes for readability. I have removed the bits that I could not understand:

Object.defineProperty(window, "console", {
    value: console,
    writable: false,
    configurable: false

var i = 0;
function showWarningAndThrow() {
    if (!i) {
        setTimeout(function () {
            console.log("%cWarning message", "font: 2em sans-serif; color: yellow; background-color: red;");
        }, 1);
        i = 1;
    throw "Console is disabled";

var l, n = {
        set: function (o) {
            l = o;
        get: function () {
            return l;
Object.defineProperty(console, "_commandLineAPI", n);
Object.defineProperty(console, "__commandLineAPI", n);

With this, the console auto-complete fails silently while statements typed in console will fail to execute (the exception will be logged).


Selecting empty text input using jQuery


After trying a lots of version I found this the most logical.

Note that text is case-sensitive.

MaxJsonLength exception in ASP.NET MVC during JavaScriptSerializer

You can put this code in cshtml if you are returning view from controller and you want to increase the length of view bag data while encoding in json in cshtml

    var jss = new System.Web.Script.Serialization.JavaScriptSerializer();
    jss.MaxJsonLength = Int32.MaxValue;
    var userInfoJson = jss.Serialize(ViewBag.ActionObj);

var dataJsonOnActionGrid1 = @Html.Raw(userInfoJson);

Now, dataJsonOnActionGrid1 will be accesible on js page and you will get proper result.


Rotate camera in Three.js with mouse

Take a look at THREE.PointerLockControls

ES6 export all values from object

export const a = 1;
export const b = 2;
export const c = 3;

This will work w/ Babel transforms today and should take advantage of all the benefits of ES2016 modules whenever that feature actually lands in a browser.

You can also add export default {a, b, c}; which will allow you to import all the values as an object w/o the * as, i.e. import myModule from 'my-module';


How can I get a Unicode character's code?

Just convert it to int:

char registered = '®';
int code = (int) registered;

In fact there's an implicit conversion from char to int so you don't have to specify it explicitly as I've done above, but I would do so in this case to make it obvious what you're trying to do.

This will give the UTF-16 code unit - which is the same as the Unicode code point for any character defined in the Basic Multilingual Plane. (And only BMP characters can be represented as char values in Java.) As Andrzej Doyle's answer says, if you want the Unicode code point from an arbitrary string, use Character.codePointAt().

Once you've got the UTF-16 code unit or Unicode code points, but of which are integers, it's up to you what you do with them. If you want a string representation, you need to decide exactly what kind of representation you want. (For example, if you know the value will always be in the BMP, you might want a fixed 4-digit hex representation prefixed with U+, e.g. "U+0020" for space.) That's beyond the scope of this question though, as we don't know what the requirements are.

Reload an iframe with jQuery

If the iframe was not on a different domain, you could do something like this:


But since the iframe is on a different domain, you will be denied access to the iframe's contentDocument property by the same-origin policy.

But you can hackishly force the cross-domain iframe to reload if your code is running on the iframe's parent page, by setting it's src attribute to itself. Like this:

// hackishly force iframe to reload
var iframe = document.getElementById(FrameId);
iframe.src = iframe.src;

If you are trying to reload the iframe from another iframe, you are out of luck, that is not possible.

TypeScript: Property does not exist on type '{}'

        contextParamers : {
            param1: any,
            param2: string
            param3: string          
          contextParamers.param1 = contextParamers.param1+ 'canChange';
          //contextParamers.param4 = "CannotChange";
          var contextParamers2 : any = contextParamers;// lost the typescript on the new object of type any
          contextParamers2.param4 =  'canChange';
          return contextParamers2;

Quick way to create a list of values in C#?

You can do that with

var list = new List<string>{ "foo", "bar" };

Here are some other common instantiations of other common Data Structures:


var dictionary = new Dictionary<string, string> 
    { "texas",   "TX" },
    { "utah",    "UT" },
    { "florida", "FL" }

Array list

var array = new string[] { "foo", "bar" };


var queque = new Queue<int>(new[] { 1, 2, 3 });


var queque = new Stack<int>(new[] { 1, 2, 3 });

As you can see for the majority of cases it is merely adding the values in curly braces, or instantiating a new array followed by curly braces and values.

How to read single Excel cell value

You need to cast it to a string (not an array of string) since it's a single value.

var cellValue = (string)(excelWorksheet.Cells[10, 2] as Excel.Range).Value;

php artisan migrate throwing [PDO Exception] Could not find driver - Using Laravel

for those users of windows 10 and WAMP that found this post, i have a solution.Please go visit this link. It worked for me and it was difficult to come to the solution but i hope it might be of help for others in the future.

(13: Permission denied) while connecting to upstream:[nginx]

  1. Check the user in /etc/nginx/nginx.conf
  2. Change ownership to user.
sudo chown -R nginx:nginx /var/lib/nginx

Now see the magic.

Using LINQ to group by multiple properties and sum

Linus is spot on in the approach, but a few properties are off. It looks like 'AgencyContractId' is your Primary Key, which is unrelated to the output you want to give the user. I think this is what you want (assuming you change your ViewModel to match the data you say you want in your view).

var agencyContracts = _agencyContractsRepository.AgencyContracts
    .GroupBy(ac => new
    .Select(ac => new AgencyContractViewModel
                       AgencyId = ac.Key.AgencyID,
                       VendorId = ac.Key.VendorID,
                       RegionId = ac.Key.RegionID,
                       Total = ac.Sum(acs => acs.Amount) + ac.Sum(acs => acs.Fee)

Retrieve filename from file descriptor in C

You can use fstat() to get the file's inode by struct stat. Then, using readdir() you can compare the inode you found with those that exist (struct dirent) in a directory (assuming that you know the directory, otherwise you'll have to search the whole filesystem) and find the corresponding file name. Nasty?

How to overlay density plots in R?

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

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

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

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

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

Then add a legend to the top right corner

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

Angular2 QuickStart npm start is not working correctly

This answer is in relation to the excellent Pluralsight course "Angular 2 Fundamentals" by Jim Cooper.

If like me you are having trouble getting started running the command npm start on a Windows 10 machine then I suggest the following:

Start git bash as administrator (follow the steps in the video) Navigate to the project directory (ng2-fundamentals) and then type the following commands:

npm config get registry

npm cache clean

npm install

Once the installation is complete you will need to modify the get-shell.js file located in the spawn-default-shell module inside the node_modules folder as follows:

Change the following:

const DETECT_SH_REGEX = /sh$/;

to this:

const DETECT_SH_REGEX = /sh/;

Note the $ removed from the end of the sh string (credit to the original author of this fix alfian777 who posted the solution on github)

Save the file and then go to your git bash console and type npm start

You shouldn't see any errors now and the localhost page will start up in your default browser (alternatively open your browser and navigate to http://localhost:8808/).

What's the best way to join on the same table twice?

First, I would try and refactor these tables to get away from using phone numbers as natural keys. I am not a fan of natural keys and this is a great example why. Natural keys, especially things like phone numbers, can change and frequently so. Updating your database when that change happens will be a HUGE, error-prone headache. *

Method 1 as you describe it is your best bet though. It looks a bit terse due to the naming scheme and the short aliases but... aliasing is your friend when it comes to joining the same table multiple times or using subqueries etc.

I would just clean things up a bit:

SELECT t.PhoneNumber1, t.PhoneNumber2, 
   t1.SomeOtherFieldForPhone1, t2.someOtherFieldForPhone2
FROM Table1 t
JOIN Table2 t1 ON t1.PhoneNumber = t.PhoneNumber1
JOIN Table2 t2 ON t2.PhoneNumber = t.PhoneNumber2

What i did:

  • No need to specify INNER - it's implied by the fact that you don't specify LEFT or RIGHT
  • Don't n-suffix your primary lookup table
  • N-Suffix the table aliases that you will use multiple times to make it obvious

*One way DBAs avoid the headaches of updating natural keys is to not specify primary keys and foreign key constraints which further compounds the issues with poor db design. I've actually seen this more often than not.

Add newly created specific folder to .gitignore in Git

I'm incredibly lazy. I just did a search hoping to find a shortcut to this problem but didn't get an answer so I knocked this up.


# Usage: IGNORE_ALL <commit message>                                                                                                                             
git status --porcelain | grep '^??' | cut -f2 -d' ' >> .gitignore              
git commit -m "$*" .gitignore 

EG: IGNORE_ALL added stat ignores

This will just append all the ignore files to your .gitignore and commit. note you might want to add annotations to the file afterwards.

How to create batch file in Windows using "start" with a path and command with spaces

Surrounding the path and the argument with spaces inside quotes as in your example should do. The command may need to handle the quotes when the parameters are passed to it, but it usually is not a big deal.

How can I tell if I'm running in 64-bit JVM or 32-bit JVM (from within a program)?

This is the way JNA solves this with Platform.is64Bit() (

 public static final boolean is64Bit() {
        String model = System.getProperty("",
        if (model != null) {
            return "64".equals(model);
        if ("x86-64".equals(ARCH)
            || "ia64".equals(ARCH)
            || "ppc64".equals(ARCH) || "ppc64le".equals(ARCH)
            || "sparcv9".equals(ARCH)
            || "mips64".equals(ARCH) || "mips64el".equals(ARCH)
            || "amd64".equals(ARCH)
            || "aarch64".equals(ARCH)) {
            return true;
        return Native.POINTER_SIZE == 8;

ARCH = getCanonicalArchitecture(System.getProperty("os.arch"), osType);

static String getCanonicalArchitecture(String arch, int platform) {
        arch = arch.toLowerCase().trim();
        if ("powerpc".equals(arch)) {
            arch = "ppc";
        else if ("powerpc64".equals(arch)) {
            arch = "ppc64";
        else if ("i386".equals(arch) || "i686".equals(arch)) {
            arch = "x86";
        else if ("x86_64".equals(arch) || "amd64".equals(arch)) {
            arch = "x86-64";
        // Work around OpenJDK mis-reporting os.arch
        if ("ppc64".equals(arch) && "little".equals(System.getProperty("sun.cpu.endian"))) {
            arch = "ppc64le";
        // Map arm to armel if the binary is running as softfloat build
        if("arm".equals(arch) && platform == Platform.LINUX && isSoftFloat()) {
            arch = "armel";

        return arch;

static {
        String osName = System.getProperty("");
        if (osName.startsWith("Linux")) {
            if ("dalvik".equals(System.getProperty("").toLowerCase())) {
                osType = ANDROID;
                // Native libraries on android must be bundled with the APK
                System.setProperty("jna.nounpack", "true");
            else {
                osType = LINUX;
        else if (osName.startsWith("AIX")) {
            osType = AIX;
        else if (osName.startsWith("Mac") || osName.startsWith("Darwin")) {
            osType = MAC;
        else if (osName.startsWith("Windows CE")) {
            osType = WINDOWSCE;
        else if (osName.startsWith("Windows")) {
            osType = WINDOWS;
        else if (osName.startsWith("Solaris") || osName.startsWith("SunOS")) {
            osType = SOLARIS;
        else if (osName.startsWith("FreeBSD")) {
            osType = FREEBSD;
        else if (osName.startsWith("OpenBSD")) {
            osType = OPENBSD;
        else if (osName.equalsIgnoreCase("gnu")) {
            osType = GNU;
        else if (osName.equalsIgnoreCase("gnu/kfreebsd")) {
            osType = KFREEBSD;
        else if (osName.equalsIgnoreCase("netbsd")) {
            osType = NETBSD;
        else {
            osType = UNSPECIFIED;

How to call Android contacts list?

I do it this way for Android 2.2 Froyo release: basically use eclipse to create a class like: public class SomePickContactName extends Activity

then insert this code. Remember to add the private class variables and CONSTANTS referenced in my version of the code:

protected void onCreate(Bundle savedInstanceState) 
  Intent intentContact = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI); 
  startActivityForResult(intentContact, PICK_CONTACT);

public void onActivityResult(int requestCode, int resultCode, Intent intent) 

  if (requestCode == PICK_CONTACT)
    // Your class variables now have the data, so do something with it. 

protected void getContactInfo(Intent intent)

   Cursor cursor =  managedQuery(intent.getData(), null, null, null, null);      
   while (cursor.moveToNext()) 
       String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
       name = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME)); 

       String hasPhone = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));

       if ( hasPhone.equalsIgnoreCase("1"))
           hasPhone = "true";
           hasPhone = "false" ;

       if (Boolean.parseBoolean(hasPhone)) 
        Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId,null, null);
        while (phones.moveToNext()) 
          phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

       // Find Email Addresses
       Cursor emails = getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,null,ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = " + contactId,null, null);
       while (emails.moveToNext()) 
        emailAddress = emails.getString(emails.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));

    Cursor address = getContentResolver().query(
                ContactsContract.CommonDataKinds.StructuredPostal.CONTACT_ID + " = " + contactId,
                null, null);
    while (address.moveToNext()) 
      // These are all private class variables, don't forget to create them.
      poBox      = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POBOX));
      street     = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET));
      city       = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY));
      state      = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.REGION));
      postalCode = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE));
      country    = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY));
      type       = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.TYPE));
    }  //address.moveToNext()   
  }  //while (cursor.moveToNext())        

Updating address bar with new URL without hash or reloading the page

Update to Davids answer to even detect browsers that do not support pushstate:

if (history.pushState) {
  window.history.pushState("object or string", "Title", "/new-url");
} else {
  document.location.href = "/new-url";

How to push JSON object in to array using javascript

var postdata = {created_at: "2017-03-14T01:00:32Z", entry_id: 33358, field1: "4", field2: "4", field3: "0"};

var data = [];


Python module os.chmod(file, 664) does not change the permission to rw-rw-r-- but -w--wx----

Using the stat.* bit masks does seem to me the most portable and explicit way of doing this. But on the other hand, I often forget how best to handle that. So, here's an example of masking out the 'group' and 'other' permissions and leaving 'owner' permissions untouched. Using bitmasks and subtraction is a useful pattern.

import os
import stat
def chmodme(pn):
    """Removes 'group' and 'other' perms. Doesn't touch 'owner' perms."""
    mode = os.stat(pn).st_mode
    mode -= (mode & (stat.S_IRWXG | stat.S_IRWXO))
    os.chmod(pn, mode)

Angular 6 Material mat-select change method removed

The changed it from change to selectionChange.

<mat-select (change)="doSomething($event)">

is now

<mat-select (selectionChange)="doSomething($event)">

Find the min/max element of an array in JavaScript

.apply is often used when the intention is to invoke a variadic function with a list of argument values, e.g.

The Math.max([value1[,value2, ...]]) function returns the largest of zero or more numbers.

Math.max(10, 20); // 20
Math.max(-10, -20); // -10
Math.max(-10, 20); // 20

The Math.max() method doesn't allow you to pass in an array. If you have a list of values of which you need to get the largest, you would normally call this function using Function.prototype.apply(), e.g.

Math.max.apply(null, [10, 20]); // 20
Math.max.apply(null, [-10, -20]); // -10
Math.max.apply(null, [-10, 20]); // 20

However, as of the ECMAScript 6 you can use the spread operator:

The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected.

Using the spread operator, the above can be rewritten as such:

Math.max(...[10, 20]); // 20
Math.max(...[-10, -20]); // -10
Math.max(...[-10, 20]); // 20

When calling a function using the variadic operator, you can even add additional values, e.g.

Math.max(...[10, 20], 50); // 50
Math.max(...[-10, -20], 50); // 50


Spread operator enables you to use the array literal syntax to create new arrays in situations where in ES5 you would need to fall back to imperative code, using a combination of push, splice, etc.

let foo = ['b', 'c'];
let bar = ['a',, 'd', 'e']; // ['a', 'b', 'c', 'd', 'e']

How do I set a fixed background image for a PHP file?

I found my answer.

$profpic = "bg.jpg";

<style type="text/css">

body {
background-image: url('<?php echo $profpic;?>');

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

How can I include all JavaScript files in a directory via JavaScript file?

You can't do that in Javascript from the browser... If I were you, I would use something like browserify. Write your code using commonjs modules and then compile the javascript file into one.

In your html load the javascript file that you compiled.

Multiple conditions with CASE statements

Another way based on amadan:

    SELECT * FROM [Purchasing].[Vendor] WHERE  

      ( (@url IS null OR @url = '' OR @url = 'ALL') and   PurchasingWebServiceURL LIKE '%')

       ( @url = 'blank' and  PurchasingWebServiceURL = '')
        (@url = 'fail' and  PurchasingWebServiceURL NOT LIKE '%treyresearch%')
    or( (@url not in ('fail','blank','','ALL') and @url is not null and 
          PurchasingWebServiceUrl Like '%'+@ur+'%') 

How do I view 'git diff' output with my preferred diff tool/ viewer?


For reference I'd like to include my variation on VonC's answer. Keep in mind that I am using the MSys version of Git ( at this time) with modified PATH, and running Git itself from Powershell (or cmd.exe), not the Bash shell.

I introduced a new command, gitdiff. Running this command temporarily redirects git diff to use a visual diff program of your choice (as opposed to VonC's solution that does it permanently). This allows me to have both the default Git diff functionality (git diff) as well as visual diff functionality (gitdiff). Both commands take the same parameters, so for example to visually diff changes in a particular file you can type

gitdiff path/file.txt


Note that $GitInstall is used as a placeholder for the directory where Git is installed.

  1. Create a new file, $GitInstall\cmd\gitdiff.cmd

    @echo off
    for /F "delims=" %%I in ("%~dp0..") do @set path=%%~fI\bin;%%~fI\mingw\bin;%PATH%
    if "%HOME%"=="" @set HOME=%USERPROFILE%
    set GIT_EXTERNAL_DIFF=git-diff-visual.cmd
    set GIT_PAGER=cat
    git diff %*
  2. Create a new file, $GitInstall\bin\git-diff-visual.cmd (replacing [visual_diff_exe] placeholder with full path to the diff program of your choice)

    @echo off
    rem diff is called by git with 7 parameters:
    rem path old-file old-hex old-mode new-file new-hex new-mode
    echo Diffing "%5"
    "[visual_diff_exe]" "%2" "%5"
    exit 0
  3. You're now done. Running gitdiff from within a Git repository should now invoke your visual diff program for every file that was changed.

How to sum digits of an integer in java?

shouldn't you be able to do it recursively something like so? I'm kinda new to programming but I traced this out and I think it works.

int sum(int n){
return n%10 + sum(n/10);

How to insert an element after another element in JavaScript without using a library?

2018 Solution (Bad Practice, go to 2020)

I know this question is Ancient, but for any future users, heres a modified prototype this is just a micro polyfill for the .insertAfter function that doesnt exist this prototype directly adds a new function baseElement.insertAfter(element); to the Element prototype:

Element.prototype.insertAfter = function(new) {
    this.parentNode.insertBefore(new, this.nextSibling);

Once youve placed the polyfill in a library, gist, or just in your code (or anywhere else where it can be referenced) Just write document.getElementById('foo').insertAfter(document.createElement('bar'));

2019 Solution (Ugly, go to 2020)

You SHOULD NOT USE PROTOTYPES. They overwrite the default codebase and arent very efficient or safe and can cause compatibility errors, but if its for non-commercial projects, it shouldnt matter. if you want a safe function for commercial use, just use a default function. its not pretty but it works:

function insertAfter(el, newEl) {
    el.parentNode.insertBefore(newEl, this.nextSibling);

// use

const el = document.body || document.querySelector("body");
// the || means "this OR that"

el.insertBefore(document.createElement("div"), el.nextSibling);
// Insert Before

insertAfter(el, document.createElement("div"));
// Insert After 

2020 Solution

Current Web Standards for ChildNode:

Its currently in the Living Standards and is SAFE.

For Unsupported Browsers, use this Polyfill:

Someone mentioned that the Polyfill uses Protos, when I said they were bad practice. They are, especially when they are used blindly and overwrited, like with my 2018 solution. However, that polyfill is on the MDN Documentation and uses a kind of initialization and execution that is safer.

How to use the 2020 Solution:

// Parent Element
const el = document.querySelector(".class");

// Create New Element
const newEl = document.createElement("div"); = "foo";

// Insert New Element BEFORE an Element

// Insert New Element AFTER an Element

// Remove an Element

// Even though it’s a created element,
// newEl is still a reference to the HTML,
// so using .remove() on it should work
// if you have already appended it somewhere

How to draw a standard normal distribution in R

Something like this perhaps?

x<-rnorm(100000,mean=10, sd=2)
abline(v=10, lwd=5)
abline(v=c(4,6,8,12,14,16), lwd=3,lty=3)

Running Selenium WebDriver python bindings in chrome

For Linux

  1. Check you have installed latest version of chrome brwoser-> chromium-browser -version

  2. If not, install latest version of chrome sudo apt-get install chromium-browser

  3. get appropriate version of chrome driver from here

  4. Unzip the

  5. Move the file to /usr/bin directory sudo mv chromedriver /usr/bin

  6. Goto /usr/bin directory cd /usr/bin

  7. Now, you would need to run something like sudo chmod a+x chromedriver to mark it executable.

  8. finally you can execute the code.

    from selenium import webdriver
    driver = webdriver.Chrome()
    print driver.page_source.encode('utf-8')

How do I print an IFrame from javascript in Safari/Chrome

Here is my complete, cross browser solution:

In the iframe page:

function printPage() { print(); }

In the main page

function printIframe(id)
    var iframe = document.frames
        ? document.frames[id]
        : document.getElementById(id);
    var ifWin = iframe.contentWindow || iframe;

    return false;

Update: Many people seem to be having problems with this in versions of IE released since I had this problem. I do not have the time to re-investigate this right now, but, if you are stuck I suggest you read all the comments in this entire thread!

bash: npm: command not found?

In my case it was entirely my fault (as usual) I was changing the system path under the environment variables, in Windows, and messed up the path for Node/NPM. So the solution is to either re-add the path for NPM, see this answer or the lazy option: re-install it which will re-add it for you.

jQuery DataTable overflow and text-wrapping issues

I'm way late here, but after reading @Greg Pettit's answer and a couple of blogs or other SO questions I unfortunately can't remember I decided to just make a couple of dataTables plugins to deal with this.

I put them on bitbucket in a Mercurial repo. I follwed the fnSetFilteringDelay plugin and just changed the comments and code inside, as I've never made a plugin for anything before. I made 2, and feel free to use them, contribute to them, or provide suggestions.

  • dataTables.TruncateCells - truncates each cell in a column down to a set number of characters, replacing the last 3 with an ellipses, and puts the full pre-truncated text in the cell's title attributed.

  • dataTables.BreakCellText - attempts to insert a break character every X, user defined, characters in each cell in the column. There are quirks regarding cells that contain both spaces and hyphens, you can get some weird looking results (like a couple of characters straggling after the last inserted
    character). Maybe someone can make that more robust, or you can just fiddle with the breakPos for the column to make it look alright with your data.

How to rename a table column in Oracle 10g

The syntax of the query is as follows:

Alter table <table name> rename column <column name> to <new column name>;


Alter table employee rename column eName to empName;

To rename a column name without space to a column name with space:

Alter table employee rename column empName to "Emp Name";

To rename a column with space to a column name without space:

Alter table employee rename column "emp name" to empName;

Replacing Pandas or Numpy Nan with a None to use with MysqlDB

df = df.replace({np.nan: None})

Credit goes to this guy here on this Github issue.

How to install PyQt5 on Windows?

To install the GPL version of PyQt5, run (see PyQt5 Project):

pip3 install pyqt5

This will install the Python wheel for your platform and your version of Python (assuming both are supported).

(The wheel will be automatically downloaded from the Python Package Index.)

The PyQt5 wheel includes the necessary parts of the LGPL version of Qt. There is no need to install Qt yourself.

(The required sip is packaged as a separate wheel and will be downloaded and installed automatically.)


If you get an error message saying something as

No downloads could be found that satisfy the requirement 

then you are probably using an unsupported version of Python.

How to read pickle file?

I developed a software tool that opens (most) Pickle files directly in your browser (nothing is transferred so it's 100% private):

NSPhotoLibraryUsageDescription key must be present in Info.plist to use camera roll

In order to save or retrieve an image from the camera roll. Additionally, you need to ask the user for the permission otherwise you'll get this error or your app may get crashed. To save yourself from this add this into your info.plist

<string>This app requires read and write permission from the user.</string>

In the case of Xamarin.iOS

 if you're adding it from the generic editor then "Privacy - Photo Library Additions Usage Description" will be the given option you will find out instead of "NSPhotoLibraryAddUsageDescription".

Padding characters in printf

This one is even simpler and execs no external commands.

$ printf "%-.20s [%s]\n" "${PROC_NAME}................................" "$PROC_STATUS"

JBoss............... [UP]

How to install the JDK on Ubuntu Linux

You can install via apt-get:

sudo add-apt-repository ppa:linuxuprising/java
sudo apt-get update
sudo apt-get install oracle-java11-installer

After, do not forget to check the version:

java -version

Android Studio - How to Change Android SDK Path

In Android Studio you can set the general Android SDK path in the file: %Home%.AndroidStudio2.1\config\options\jdk.table.xml

How to compare two floating point numbers in Bash?

You can use awk combined with a bash if condition:

if awk 'BEGIN {exit !('$d1' >= '$d2')}'; then
    echo "yes"
    echo "no"

Getting absolute URLs using ASP.NET Core

In a new ASP.Net 5 MVC project in a controller action you can still do this.Context and this.Context.Request It looks like on the Request there is no longer a Url property but the child properties (schema, host, etc) are all on the request object directly.

 public IActionResult About()
        ViewBag.Message = "Your application description page.";
        var schema = this.Context.Request.Scheme;

        return View();

Rather or not you want to use this.Context or inject the property is another conversation. Dependency Injection in ASP.NET vNext

Python loop that also accesses previous and next values

I think this works and not complicated

array= [1,5,6,6,3,2]
for i in range(0,len(array)):
    Current = array[i]
    Next = array[i+1]
    Prev = array[i-1]

What does int argc, char *argv[] mean?

The first parameter is the number of arguments provided and the second parameter is a list of strings representing those arguments.

Integer ASCII value to character in BASH using printf

One option is to directly input the character you're interested in using hex or octal notation:

printf "\x41\n"
printf "\101\n"

Difference between View and ViewGroup in Android

A ViewGroup describes the layout of the Views in its group. The two basic examples of ViewGroups are LinearLayout and RelativeLayout. Breaking LinearLayout even further, you can have either Vertical LinearLayout or Horizontal LinearLayout. If you choose Vertical LinearLayout, your Views will stack vertically on your screen. The two most basic examples of Views are TextView and Button. Thus, if you have a ViewGroup of Vertical LinearLayout, your Views (e.g. TextViews and Buttons) would line up vertically down your screen.

When the other posters show nested ViewGroups, what they mean is, for example, one of the rows in my Vertical LinearLayout might actually, at the lower level, be several items arranged horizontally. In that case, I'd have a Horizontal LinearLayout as one of the children of my top level Vertical LinearLayout.

Example of Nested ViewGroups:
Parent ViewGroup = Vertical LinearLayout

Row1: TextView1
Row2: Button1
Row3: Image TextView2 Button2 <-- Horizontal Linear nested in Vertical Linear
Row4: TextView3
Row5: Button3

IE6/IE7 css border on select element

I've worked around the inability to put a border on the select in IE7 (IE8 in compatibility mode)

By giving it a border as wel as a padding, it looks like something....

Not everything, but it's start...

When should I use double or single quotes in JavaScript?

Just to add my two cents: In working with both JavaScript and PHP a few years back, I've become accustomed to using single quotes so I can type the escape character ('') without having to escape it as well. I usually used it when typing raw strings with file paths, etc.

Anyhow, my convention ended up becoming the use of single quotes on identifier-type raw strings, such as if (typeof s == 'string') ... (in which escape characters would never be used - ever), and double quotes for texts, such as "Hey, what's up?". I also use single quotes in comments as a typographical convention to show identifier names. This is just a rule of thumb, and I break off only when needed, such as when typing HTML strings '<a href="#"> like so <a>' (though you could reverse the quotes here also). I'm also aware that, in the case of JSON, double quotes are used for the names - but outside that, personally, I prefer the single quotes when escaping is never required for the text between the quotes - like document.createElement('div').

The bottom line is, and as some have mentioned/alluded to, to pick a convention, stick with it, and only deviate when necessary.

How to change the background colour's opacity in CSS

Use RGBA like this: background-color: rgba(255, 0, 0, .5)

Aren't Python strings immutable? Then why does a + " " + b work?

The built-in function id() returns the identity of an object as an integer. This integer usually corresponds to the object’s location in memory.





Initially, 'a' is stored in 139831803293008 memory location, as the string object is immutable in python if you try to modify and reassign the reference will be removed and will be a pointer to a new memory location(139831803293120).

find without recursion

If you look for POSIX compliant solution:

cd DirsRoot && find . -type f -print -o -name . -o -prune

-maxdepth is not POSIX compliant option. Received fatal alert: protocol_version

I have got that error after update to JDK 1.8. But the JAVA_HOME variable was hard coded furthermore to JDK 1.7. Thew modification solved the problem:

set JAVA_HOME=C:\Program Files\Java\jdk1.8.0_241

Play audio from a stream using C#

NAudio wraps the WaveOutXXXX API. I haven't looked at the source, but if NAudio exposes the waveOutWrite() function in a way that doesn't automatically stop playback on each call, then you should be able to do what you really want, which is to start playing the audio stream before you've received all the data.

Using the waveOutWrite() function allows you to "read ahead" and dump smaller chunks of audio into the output queue - Windows will automatically play the chunks seamlessly. Your code would have to take the compressed audio stream and convert it to small chunks of WAV audio on the fly; this part would be really difficult - all the libraries and components I've ever seen do MP3-to-WAV conversion an entire file at a time. Probably your only realistic chance is to do this using WMA instead of MP3, because you can write simple C# wrappers around the multimedia SDK.

AddTransient, AddScoped and AddSingleton Services Differences

In .NET's dependency injection there are three major lifetimes:

Singleton which creates a single instance throughout the application. It creates the instance for the first time and reuses the same object in the all calls.

Scoped lifetime services are created once per request within the scope. It is equivalent to a singleton in the current scope. For example, in MVC it creates one instance for each HTTP request, but it uses the same instance in the other calls within the same web request.

Transient lifetime services are created each time they are requested. This lifetime works best for lightweight, stateless services.

Here you can find and examples to see the difference:

ASP.NET 5 MVC6 Dependency Injection in 6 Steps (web archive link due to dead link)

Your Dependency Injection ready ASP.NET : ASP.NET 5

And this is the link to the official documentation:

Dependency injection in ASP.NET Core

how to remove css property using javascript?

You can use the styleSheets object:


Caveat #1: You have to know the index of your stylesheet and the index of your rule.

Caveat #2: This object is implemented inconsistently by the browsers; what works in one may not work in the others.

No Exception while type casting with a null in java

As others have written, you can cast null to everything. Normally, you wouldn't need that, you can write:

String nullString = null;

without putting the cast there.

But there are occasions where such casts make sense:

a) if you want to make sure that a specific method is called, like:

void foo(String bar) {  ... }
void foo(Object bar) {  ... }

then it would make a difference if you type

foo((String) null) vs. foo(null)

b) if you intend to use your IDE to generate code; for example I am typically writing unit tests like:

public testCtorWithNullWhatever() {
    new MyClassUnderTest((Whatever) null);

I am doing TDD; this means that the class "MyClassUnderTest" probably doesn't exist yet. By writing down that code, I can then use my IDE to first generate the new class; and to then generate a constructor accepting a "Whatever" argument "out of the box" - the IDE can figure from my test that the constructor should take exactly one argument of type Whatever.

Postgres - Transpose Rows to Columns

Use crosstab() from the tablefunc module.

SELECT * FROM crosstab(
   $$SELECT user_id, user_name, rn, email_address
     FROM  (
        SELECT u.user_id, u.user_name, e.email_address
             , row_number() OVER (PARTITION BY u.user_id
                            ORDER BY e.creation_date DESC NULLS LAST) AS rn
        FROM   usr u
        LEFT   JOIN email_tbl e USING (user_id)
        ) sub
     WHERE  rn < 4
     ORDER  BY user_id
  , 'VALUES (1),(2),(3)'
   ) AS t (user_id int, user_name text, email1 text, email2 text, email3 text);

I used dollar-quoting for the first parameter, which has no special meaning. It's just convenient if you have to escape single quotes in the query string which is a common case:

Detailed explanation and instructions here:

And in particular, for "extra columns":

The special difficulties here are:

  • The lack of key names.
    -> We substitute with row_number() in a subquery.

  • The varying number of emails.
    -> We limit to a max. of three in the outer SELECT
    and use crosstab() with two parameters, providing a list of possible keys.

Pay attention to NULLS LAST in the ORDER BY.

ASP.NET MVC - Find Absolute Path to the App_Data folder from Controller

I try to get in the habit of using HostingEnvironment instead of Server as it works within the context of WCF services too.

 HostingEnvironment.MapPath(@"~/App_Data/PriceModels.xml"); serialize/deserialize derived types?

You have to enable Type Name Handling and pass that to the (de)serializer as a settings parameter.

Base object1 = new Base() { Name = "Object1" };
Derived object2 = new Derived() { Something = "Some other thing" };
List<Base> inheritanceList = new List<Base>() { object1, object2 };

JsonSerializerSettings settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All };
string Serialized = JsonConvert.SerializeObject(inheritanceList, settings);
List<Base> deserializedList = JsonConvert.DeserializeObject<List<Base>>(Serialized, settings);

This will result in correct deserialization of derived classes. A drawback to it is that it will name all the objects you are using, as such it will name the list you are putting the objects in.

Convert Java Date to UTC String

If XStream is a dependency, try:

new com.thoughtworks.xstream.converters.basic.DateConverter().toString(date)

How to echo (or print) to the js console with php

<?php  echo "<script>console.log({$yourVariable})</script>"; ?>

How can I add a volume to an existing Docker container?

Jérôme Petazzoni has a pretty interesting blog post on how to Attach a volume to a container while it is running. This isn't something that's built into Docker out of the box, but possible to accomplish.

As he also points out

This will not work on filesystems which are not based on block devices.

It will only work if /proc/mounts correctly lists the block device node (which, as we saw above, is not necessarily true).

Also, I only tested this on my local environment; I didn’t even try on a cloud instance or anything like that


How do I add a foreign key to an existing SQLite table?

If you are using the Firefox add-on sqlite-manager you can do the following:

Instead of dropping and creating the table again one can just modify it like this.

In the Columns text box, right click on the last column name listed to bring up the context menu and select Edit Column. Note that if the last column in the TABLE definition is the PRIMARY KEY then it will be necessary to first add a new column and then edit the column type of the new column in order to add the FOREIGN KEY definition. Within the Column Type box , append a comma and the

FOREIGN KEY (parent_id) REFERENCES parent(id)

definition after data type. Click on the Change button and then click the Yes button on the Dangerous Operation dialog box.

Reference: Sqlite Manager

Array versus linked-list

Why would someone want to use a linked-list over an array?

This is only one reason - if you need a linked list data structure and a programming language you are using is not supports a pointers.

Trigger a keypress/keydown/keyup event in JS/jQuery?

You're now able to do:

var e = $.Event("keydown", {keyCode: 64});

Regex to extract URLs from href attribute in HTML with Python

The best answer is...

Don't use a regex

The expression in the accepted answer misses many cases. Among other things, URLs can have unicode characters in them. The regex you want is here, and after looking at it, you may conclude that you don't really want it after all. The most correct version is ten-thousand characters long.

Admittedly, if you were starting with plain, unstructured text with a bunch of URLs in it, then you might need that ten-thousand-character-long regex. But if your input is structured, use the structure. Your stated aim is to "extract the url, inside the anchor tag's href." Why use a ten-thousand-character-long regex when you can do something much simpler?

Parse the HTML instead

For many tasks, using Beautiful Soup will be far faster and easier to use:

>>> from bs4 import BeautifulSoup as Soup
>>> html = Soup(s, 'html.parser')           # Soup(s, 'lxml') if lxml is installed
>>> [a['href'] for a in html.find_all('a')]
['', '']

If you prefer not to use external tools, you can also directly use Python's own built-in HTML parsing library. Here's a really simple subclass of HTMLParser that does exactly what you want:

from html.parser import HTMLParser

class MyParser(HTMLParser):
    def __init__(self, output_list=None):
        if output_list is None:
            self.output_list = []
            self.output_list = output_list
    def handle_starttag(self, tag, attrs):
        if tag == 'a':


>>> p = MyParser()
>>> p.feed(s)
>>> p.output_list
['', '']

You could even create a new method that accepts a string, calls feed, and returns output_list. This is a vastly more powerful and extensible way than regular expressions to extract information from html.

Creating multiple objects with different names in a loop to store in an array list

You can use this code...

public class Main {

    public static void main(String args[]) {
        String[] names = {"First", "Second", "Third"};//You Can Add More Names
        double[] amount = {20.0, 30.0, 40.0};//You Can Add More Amount
        List<Customer> customers = new ArrayList<Customer>();
        int i = 0;
        while (i < names.length) {
            customers.add(new Customer(names[i], amount[i]));

Eclipse fonts and background color

Under Windows ? Preferences ? General ? Apperance you can find a dark theme.

@Autowired and static method

This builds upon @Pavel's answer, to solve the possibility of Spring context not being initialized when accessing from the static getBean method:

public class Spring {
  private static final Logger LOG = LoggerFactory.getLogger (Spring.class);

  private static Spring spring;

  private ApplicationContext context;

  public void registerInstance () {
    spring = this;

  private Spring (ApplicationContext context) {
    this.context = context;

  private static synchronized void initContext () {
    if (spring == null) { ("Initializing Spring Context...");
      ApplicationContext context = new AnnotationConfigApplicationContext (io.zeniq.spring.BaseConfig.class);
      spring = new Spring (context);

  public static <T> T getBean(String name, Class<T> className) throws BeansException {
    return spring.context.getBean(name, className);

  public static <T> T getBean(Class<T> className) throws BeansException {
    return spring.context.getBean(className);

  public static AutowireCapableBeanFactory getBeanFactory() throws IllegalStateException {
    return spring.context.getAutowireCapableBeanFactory ();

The important piece here is the initContext method. It ensures that the context will always get initialized. But, do note that initContext will be a point of contention in your code as it is synchronized. If your application is heavily parallelized (for eg: the backend of a high traffic site), this might not be a good solution for you.

What is the point of the diamond operator (<>) in Java 7?

This line causes the [unchecked] warning:

List<String> list = new LinkedList();

So, the question transforms: why [unchecked] warning is not suppressed automatically only for the case when new collection is created?

I think, it would be much more difficult task then adding <> feature.

UPD: I also think that there would be a mess if it were legally to use raw types 'just for a few things'.

Unsigned values in C

When you initialize unsigned int a to -1; it means that you are storing the 2's complement of -1 into the memory of a.
Which is nothing but 0xffffffff or 4294967295.

Hence when you print it using %x or %u format specifier you get that output.

By specifying signedness of a variable to decide on the minimum and maximum limit of value that can be stored.

Like with unsigned int: the range is from 0 to 4,294,967,295 and int: the range is from -2,147,483,648 to 2,147,483,647

For more info on signedness refer this

Serializing to JSON in jQuery

No, the standard way to serialize to JSON is to use an existing JSON serialization library. If you don't wish to do this, then you're going to have to write your own serialization methods.

If you want guidance on how to do this, I'd suggest examining the source of some of the available libraries.

EDIT: I'm not going to come out and say that writing your own serliazation methods is bad, but you must consider that if it's important to your application to use well-formed JSON, then you have to weigh the overhead of "one more dependency" against the possibility that your custom methods may one day encounter a failure case that you hadn't anticipated. Whether that risk is acceptable is your call.

Browser detection in JavaScript?

navigator.sayswho= (function(){
    var ua= navigator.userAgent, tem,
    M= ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
        tem=  /\brv[ :]+(\d+)/g.exec(ua) || [];
        return 'IE '+(tem[1] || '');
    if(M[1]=== 'Chrome'){
        tem= ua.match(/\b(OPR|Edge?)\/(\d+)/);
        if(tem!= null) return tem.slice(1).join(' ').replace('OPR', 'Opera').replace('Edg ', 'Edge ');            
    M= M[2]? [M[1], M[2]]: [navigator.appName, navigator.appVersion, '-?'];
    if((tem= ua.match(/version\/(\d+)/i))!= null) M.splice(1, 1, tem[1]);
    return M.join(' ');

As the name implies, this will tell you the name and version number supplied by the browser.

It is handy for sorting test and error results, when you are testing new code on multiple browsers.

Twitter API - Display all tweets with a certain hashtag?

UPDATE for v1.1:

Rather than giving q="search_string" give it q="hashtag" in URL encoded form to return results with HASHTAG ONLY. So your query would become:


%23 is URL encoded form of #. Try the link out in your browser and it should work.

You can optimize the query by adding since_id and max_id parameters detailed here. Hope this helps !

Note: Search API is now a OAUTH authenticated call, so please include your access_tokens to the above call


Twitter Search doc link:

Transform DateTime into simple Date in Ruby on Rails

I recently wrote a gem to simplify this process and to neaten up your views, etc etc.

Check it out at:

How to align texts inside of an input?

@Html.TextBoxFor(model => model.IssueDate, new { @class = "form-control", name = "inv_issue_date", id = "inv_issue_date", title = "Select Invoice Issue Date", placeholder = "dd/mm/yyyy", style = "text-align:center;" })

Where do I find the line number in the Xcode editor?

For Xcode 4 and higher, open the preferences (command+,) and check "Show: Line numbers" in the "Text Editing" section.

Xcode 9 enter image description here

Xcode 8 and below Xcode Text Editing Preferences screen capture with Text Editing and Line Numbers highlighted

How to embed small icon in UILabel

Swift 2.0 version:

//Get image and set it's size
let image = UIImage(named: "imageNameWithHeart")
let newSize = CGSize(width: 10, height: 10)

//Resize image
UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
image?.drawInRect(CGRectMake(0, 0, newSize.width, newSize.height))
let imageResized = UIGraphicsGetImageFromCurrentImageContext()

//Create attachment text with image
var attachment = NSTextAttachment()
attachment.image = imageResized
var attachmentString = NSAttributedString(attachment: attachment)
var myString = NSMutableAttributedString(string: "I love swift ")
myLabel.attributedText = myString

How to stop java process gracefully?

Here is a bit tricky, but portable solution:

  • In your application implement a shutdown hook
  • When you want to shut down your JVM gracefully, install a Java Agent that calls System.exit() using the Attach API.

I implemented the Java Agent. It is available on Github:

Detailed description about the solution is available here:

How to check if input is numeric in C++

Why not just using scanf("%i") and check its return?

How to plot a 2D FFT in Matlab?

Here is an example from my HOW TO Matlab page:

close all; clear all;

img   = imread('lena.tif','tif');
img   = fftshift(img(:,:,2));
F     = fft2(img);


imagesc(100*log(1+abs(fftshift(F)))); colormap(gray); 
title('magnitude spectrum');

imagesc(angle(F));  colormap(gray);
title('phase spectrum');

This gives the magnitude spectrum and phase spectrum of the image. I used a color image, but you can easily adjust it to use gray image as well.

ps. I just noticed that on Matlab 2012a the above image is no longer included. So, just replace the first line above with say

img = imread('ngc6543a.jpg');

and it will work. I used an older version of Matlab to make the above example and just copied it here.

On the scaling factor

When we plot the 2D Fourier transform magnitude, we need to scale the pixel values using log transform to expand the range of the dark pixels into the bright region so we can better see the transform. We use a c value in the equation

s = c log(1+r) 

There is no known way to pre detrmine this scale that I know. Just need to try different values to get on you like. I used 100 in the above example.

enter image description here

C# Return Different Types?

Let the method return a object from a common baseclass or interface.

public class TV:IMediaPlayer
   void Play(){};

public class Radio:IMediaPlayer
   void Play(){};

public interface IMediaPlayer
   void Play():

public class Test
  public void Main()
     IMediaPlayer player = GetMediaPlayer();

  private IMediaPlayer GetMediaPlayer()
        return new TV();
        return new Radio();

How can I clear the content of a file?

This is what I did to clear the contents of the file without creating a new file as I didn't want the file to display new time of creation even when the application just updated its contents.

FileStream fileStream = File.Open(<path>, FileMode.Open);

 * Set the length of filestream to 0 and flush it to the physical file.
 * Flushing the stream is important because this ensures that
 * the changes to the stream trickle down to the physical file.
fileStream.Close(); // This flushes the content, too.

When to use references vs. pointers

Disclaimer: other than the fact that references cannot be NULL nor "rebound" (meaning thay can't change the object they're the alias of), it really comes down to a matter of taste, so I'm not going to say "this is better".

That said, I disagree with your last statement in the post, in that I don't think the code loses clarity with references. In your example,


might be clearer than


since you know that most likely the value of a is going to change. On the other hand though, the signature of the function

void add_one(int* const n);

is somewhat not clear either: is n going to be a single integer or an array? Sometimes you only have access to (poorly documentated) headers, and signatures like

foo(int* const a, int b);

are not easy to interpret at first sight.

Imho, references are as good as pointers when no (re)allocation nor rebinding (in the sense explained before) is needed. Moreover, if a developer only uses pointers for arrays, functions signatures are somewhat less ambiguous. Not to mention the fact that operators syntax is way more readable with references.

Quicker way to get all unique values of a column in VBA?

PowerShell is a very powerful and efficient tool. This is cheating a little, but shelling PowerShell via VBA opens up lots of options

The bulk of the code below is simply to save the current sheet as a csv file. The output is another csv file with just the unique values

Sub AnotherWay()
Dim strPath As String
Dim strPath2 As String

Application.DisplayAlerts = False
strPath = "C:\Temp\test.csv"
strPath2 = "C:\Temp\testout.csv"
ActiveWorkbook.SaveAs strPath, xlCSV
x = Shell("powershell.exe $csv = import-csv -Path """ & strPath & """ -Header A | Select-Object -Unique A | Export-Csv """ & strPath2 & """ -NoTypeInformation", 0)
Application.DisplayAlerts = True

End Sub

OAuth: how to test with local URLs?

You can also use ngrok: I use it all the time to have a public server running on my localhost. Hope this helps.

Another options which even provides your own custom domain for free are and

Accessing UI (Main) Thread safely in WPF

The best way to go about it would be to get a SynchronizationContext from the UI thread and use it. This class abstracts marshalling calls to other threads, and makes testing easier (in contrast to using WPF's Dispatcher directly). For example:

class MyViewModel
    private readonly SynchronizationContext _syncContext;

    public MyViewModel()
        // we assume this ctor is called from the UI thread!
        _syncContext = SynchronizationContext.Current;

    // ...

    private void watcher_Changed(object sender, FileSystemEventArgs e)
         _syncContext.Post(o => DGAddRow(crp.Protocol, ft), null);

How to insert special characters into a database?

Use this: htmlentities($_POST['field']);

Enough only. This for special character:

Use for CI htmlentities($this->input->post('control_name'));

Change the column label? e.g.: change column "A" to column "Name"

What version of Excel?

In general, you cannot change the column letters. They are part of the Excel system.

You can use a row in the sheet to enter headers for a table that you are using. The table headers can be descriptive column names.

In Excel 2007 and later, you can convert a range of data into an Excel Table (Insert Ribbon > Table). An Excel Table can use structured table references instead of cell addresses, so the labels in the first row of the table now serve as a name reference for the data in the column.

If you have an Excel Table in your sheet (Excel 2007 and later) and scroll down, the column letters will be replaced with the column headers for the table column.

enter image description here

If this does not answer your question, please consider editing your question to include the detail you want to learn about.

How do browser cookie domains work?

Although there is the RFC 2965 (Set-Cookie2, had already obsoleted RFC 2109) that should define the cookie nowadays, most browsers don’t fully support that but just comply to the original specification by Netscape.

There is a distinction between the Domain attribute value and the effective domain: the former is taken from the Set-Cookie header field and the latter is the interpretation of that attribute value. According to the RFC 2965, the following should apply:

  • If the Set-Cookie header field does not have a Domain attribute, the effective domain is the domain of the request.
  • If there is a Domain attribute present, its value will be used as effective domain (if the value does not start with a . it will be added by the client).

Having the effective domain it must also domain-match the current requested domain for being set; otherwise the cookie will be revised. The same rule applies for choosing the cookies to be sent in a request.

Mapping this knowledge onto your questions, the following should apply:

  • Cookie with will be available for
  • Cookie with will be available for
  • Cookie with will be converted to and thus will also be available for
  • Cookie with will not be available for
  • will be able to set cookie for
  • will not be able to set cookie for
  • will not be able to set cookie for .com

And to set and read a cookie for/by and, set it for and respectively. But the first ( will only be accessible for other domains below that domain (e.g. or where can also be accessed by any other domain below (e.g. or

How can I check if a user is logged-in in php?

Any page you want to perform session-checks on needs to start with:


From there, you check your session array for a variable indicating they are logged in:

if (!$_SESSION["loggedIn"]) redirect_to_login();

Logging them in is nothing more than setting that value:

$_SESSION["loggedIn"] = true;

Convert INT to FLOAT in SQL

In oracle db there is a trick for casting int to float (I suppose, it should also work in mysql):

select myintfield + 0.0 as myfloatfield from mytable

While @Heximal's answer works, I don't personally recommend it.

This is because it uses implicit casting. Although you didn't type CAST, either the SUM() or the 0.0 need to be cast to be the same data-types, before the + can happen. In this case the order of precedence is in your favour, and you get a float on both sides, and a float as a result of the +. But SUM(aFloatField) + 0 does not yield an INT, because the 0 is being implicitly cast to a FLOAT.

I find that in most programming cases, it is much preferable to be explicit. Don't leave things to chance, confusion, or interpretation.

If you want to be explicit, I would use the following.

CAST(SUM( AS FLOAT) * cp.price
-- using MySQL CAST FLOAT  requires 8.0

I won't discuss whether NUMERIC or FLOAT *(fixed point, instead of floating point)* is more appropriate, when it comes to rounding errors, etc. I'll just let you google that if you need to, but FLOAT is so massively misused that there is a lot to read about the subject already out there.

You can try the following to see what happens...

CAST(SUM( AS NUMERIC(10,4)) * CAST(cp.price AS NUMERIC(10,4))

'cout' was not declared in this scope

Use std::cout, since cout is defined within the std namespace. Alternatively, add a using std::cout; directive.

cURL equivalent in Node.js?

Since looks like node-curl is dead, I've forked it, renamed, and modified to be more curl like and to compile under Windows.


Usage example:

var Curl = require( 'node-libcurl' ).Curl;

var curl = new Curl();

curl.setOpt( Curl.option.URL, '' );
curl.setOpt( 'FOLLOWLOCATION', true );

curl.on( 'end', function( statusCode, body, headers ) { statusCode ); '---' ); body.length ); '---' ); headers ); '---' ); this.getInfo( ) );


curl.on( 'error', function( err, curlErrorCode ) {

    console.error( err.message );
    console.error( '---' );
    console.error( curlErrorCode );




Perform is async, and there is no way to use it synchronous currently (and probably will never have).

It's still in alpha, but this is going to change soon, and help is appreciated.

Now it's possible to use Easy handle directly for sync requests, example:

var Easy = require( 'node-libcurl' ).Easy,
    Curl = require( 'node-libcurl' ).Curl,
    url = process.argv[2] || '',
    ret, ch;

ch = new Easy();

ch.setOpt( Curl.option.URL, url );

ch.setOpt( Curl.option.HEADERFUNCTION, function( buf, size, nmemb ) {

    console.log( buf );

    return size * nmemb;

ch.setOpt( Curl.option.WRITEFUNCTION, function( buf, size, nmemb ) {

    console.log( arguments );

    return size * nmemb;

// this call is sync!
ret = ch.perform();


console.log( ret, ret == Curl.code.CURLE_OK, Easy.strError( ret ) );

Also, the project is stable now!

Launch Failed. Binary not found. CDT on Eclipse Helios

If you still have an error even after building the project then try to do this:

  • click on Binaries in Project Explorer with the left button
  • click on green "Play" button (Run Debug)

"Error: Main method not found in class MyClass, please define the main method as..."

When you use the java command to run a Java application from the command line, e.g.,

java some.AppName arg1 arg2 ...

the command loads the class that you nominated and then looks for the entry point method called main. More specifically, it is looking for a method that is declared as follows:

package some;
public class AppName {
    public static void main(final String[] args) {
        // body of main method follows

The specific requirements for the entry point method are:

  1. The method must be in the nominated class.
  2. The name of the method must be "main" with exactly that capitalization1.
  3. The method must be public.
  4. The method must be static 2.
  5. The method's return type must be void.
  6. The method must have exactly one argument and argument's type must be String[] 3.

(The argument may be declared using varargs syntax; e.g. String... args. See this question for more information. The String[] argument is used to pass the arguments from the command line, and is required even if your application takes no command-line arguments.)

If anyone of the above requirements is not satisfied, the java command will fail with some variant of the message:

Error: Main method not found in class MyClass, please define the main method as:
   public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application

Or, if you are running an extremely old version of Java:

java.lang.NoSuchMethodError: main
Exception in thread "main"

If you encounter this error, check that you have a main method and that it satisfies all of the six requirements listed above.

1 - One really obscure variation of this is when one or more of the characters in "main" is NOT a LATIN-1 character … but a Unicode character that looks like the corresponding LATIN-1 character when displayed.

2 - Here is an explanation of why the method is required to be static.

3 - String must correspond to java.lang.String and not to a custom class named String hiding it.

Sorting list based on values from another list

You can create a pandas Series, using the primary list as data and the other list as index, and then just sort by the index:

import pandas as pd


['a', 'd', 'h', 'b', 'c', 'e', 'i', 'f', 'g']

What is the difference between String and string in C#?

It's a matter of convention, really. string just looks more like C/C++ style. The general convention is to use whatever shortcuts your chosen language has provided (int/Int for Int32). This goes for "object" and decimal as well.

Theoretically this could help to port code into some future 64-bit standard in which "int" might mean Int64, but that's not the point, and I would expect any upgrade wizard to change any int references to Int32 anyway just to be safe.

invalid operands of types int and double to binary 'operator%'

Because % is only defined for integer types. That's the modulus operator.

5.6.2 of the standard:

The operands of * and / shall have arithmetic or enumeration type; the operands of % shall have integral or enumeration type. [...]

As Oli pointed out, you can use fmod(). Don't forget to include math.h.

How can I hide the Android keyboard using JavaScript?

rdougan's post did not work for me but it was a good starting point for my solution.

function androidSoftKeyHideFix(selectorName){
    $(selectorName).on('focus', function (event) {
        $('body').on('touchend', function (event) {
            setTimeout(function() {

You need an input element at the top of the body, I classed as 'blurBox'. It must not be display:none. So give it opacity:0, and position:absolute. I tried placing it at the bottom of the body and it didn't work.

I found it necessary to repeat the .focus() .blur() sequence on the blurBox. I tried it without and it doesn't work.

This works on my 2.3 Android. I imagine that custom keyboard apps could still have issues.

I encountered a number of issues before arriving at this. There was a bizarre issue with subsequent focuses retriggering a blur/focus, which seemed like an android bug. I used a touchend listener instead of a blur listener to get around the function refiring closing the keyboard immediately after a non-initial opening. I also had an issue with keyboard typing making the scroll jump around...which is realted to a 3d transform used on a parent. That emerged from an attempt to workaround the blur-refiring issue, where I didn't unblur the blurBox at the end. So this is a delicate solution.

Data truncation: Data too long for column 'logo' at row 1

Following solution worked for me. When connecting to the db, specify that data should be truncated if they are too long (jdbcCompliantTruncation). My link looks like this:


If you increase the size of the strings, you may face the same problem in future if the string you are attempting to store into the DB is longer than the new size.

EDIT: STRICT_TRANS_TABLES has to be removed from sql_mode as well.

JavaScript Editor Plugin for Eclipse

Think that JavaScriptDevelopmentTools might do it. Although, I have eclipse indigo, and I'm pretty sure it does that kind of thing automatically.

error C2039: 'string' : is not a member of 'std', header file problem

Take care not to include

#include <string.h> 

but only

#include <string>

It took me 1 hour to find this in my code.

Hope this can help

What is the maximum possible length of a query string?

Although officially there is no limit specified by RFC 2616, many security protocols and recommendations state that maxQueryStrings on a server should be set to a maximum character limit of 1024. While the entire URL, including the querystring, should be set to a max of 2048 characters. This is to prevent the Slow HTTP Request DDOS vulnerability on a web server. This typically shows up as a vulnerability on the Qualys Web Application Scanner and other security scanners.

Please see the below example code for Windows IIS Servers with Web.config:

        <requestLimits maxQueryString="1024" maxUrl="2048">
              <add header="Content-type" sizeLimit="100" />

This would also work on a server level using machine.config.

Note: Limiting query string and URL length may not completely prevent Slow HTTP Requests DDOS attack but it is one step you can take to prevent it.

Capture event onclose browser

You're looking for the onclose event.


note that not all browsers support this (for example firefox 2)

how to make label visible/invisible?

You can set display attribute as none to hide a label.

<label id="excel-data-div" style="display: none;"></label>

Override and reset CSS style: auto or none don't work

Well, display: none; will not display the table at all, try display: inline-block; with the width and min-width declarations remaining 'auto'.

Twitter Bootstrap 3, vertically center content

Option 1 is to use display:table-cell. You need to unfloat the Bootstrap col-* using float:none..

.center {

Option 2 is display:flex to vertical align the row with flexbox: {
   display: flex;
   align-items: center;

Vertical centering is very different in Bootstrap 4. See this answer for Bootstrap 4

Can .NET load and parse a properties file equivalent to Java Properties class?

I don't know of any built-in way to do this. However, it would seem easy enough to do, since the only delimiters you have to worry about are the newline character and the equals sign.

It would be very easy to write a routine that will return a NameValueCollection, or an IDictionary given the contents of the file.

What's the easy way to auto create non existing dir in ansible

To ensure success with a full path use recurse=yes

- name: ensure custom facts directory exists
    file: >

How can I use Google's Roboto font on a website?

The src refers directly to the font files, therefore if you place all of them on /media/fonts/roboto you should refer to them in your main.css like this: src: url('../fonts/roboto/Roboto-ThinItalic-webfont.eot');

The .. goes one folder up, which means you're referring to the media folder if the main.css is in the /media/css folder.

You have to use ../fonts/roboto/ in all url references in the CSS (and be sure that the files are in this folder and not in subdirectories, such as roboto_black_macroman).

Basically (answering to your questions):

I have css in my media/css/main.css url. So where do i need to put that folder

You can leave it there, but be sure to use src: url('../fonts/roboto/

Do i need to extract all eot,svg etc from all sub folder and put in fonts folder

If you want to refer to those files directly (without placing the subdirectories in your CSS code), then yes.

Do i need to create css file fonts.css and include in my base template file

Not necessarily, you can just include that code in your main.css. But it's a good practice to separate fonts from your customized CSS.

Here's an example of a fonts LESS/CSS file I use:

@ttf: format('truetype');

@font-face {
  font-family: 'msb';
  src: url('../font/msb.ttf') @ttf;
.msb {font-family: 'msb';}

@font-face {
  font-family: 'Roboto';
  src: url('../font/Roboto-Regular.ttf') @ttf;
.rb {font-family: 'Roboto';}
@font-face {
  font-family: 'Roboto Black';
  src: url('../font/Roboto-Black.ttf') @ttf;
.rbB {font-family: 'Roboto Black';}
@font-face {
  font-family: 'Roboto Light';
  src: url('../font/Roboto-Light.ttf') @ttf;
.rbL {font-family: 'Roboto Light';}

(In this example I'm only using the ttf) Then I use @import "fonts"; in my main.less file (less is a CSS preprocessor, it makes things like this a little bit easier)

php convert datetime to UTC

Follow these steps to get UTC time of any timezone set in user's local system (This will be required for web applications to save different timezones to UTC):

  1. Javascript (client-side):

    var dateVar = new Date();
    var offset = dateVar.getTimezoneOffset();
    //getTimezoneOffset - returns the timezone difference between UTC and Local Time
    document.cookie = "offset="+offset;
  2. Php (server-side):

    public function convert_utc_time($date)
        $time_difference = isset($_COOKIE['offset'])?$_COOKIE['offset']:'';
        if($time_difference != ''){
            $time = strtotime($date);
            $time = $time + ($time_difference*60); //minutes * 60 seconds
            $date = date("Y-m-d H:i:s", $time);
        } //on failure of js, default timezone is set as UTC below
        return $date;
    //in my function
    $timezone = 'UTC';
    $date = $this->convert_utc_time($post_date); //$post_date('Y-m-d H:i:s')
    echo strtotime($date. ' '. $timezone)

Why is the use of alloca() not considered good practice?

If you accidentally write beyond the block allocated with alloca (due to a buffer overflow for example), then you will overwrite the return address of your function, because that one is located "above" on the stack, i.e. after your allocated block.

_alloca block on the stack

The consequence of this is two-fold:

  1. The program will crash spectacularly and it will be impossible to tell why or where it crashed (stack will most likely unwind to a random address due to the overwritten frame pointer).

  2. It makes buffer overflow many times more dangerous, since a malicious user can craft a special payload which would be put on the stack and can therefore end up executed.

In contrast, if you write beyond a block on the heap you "just" get heap corruption. The program will probably terminate unexpectedly but will unwind the stack properly, thereby reducing the chance of malicious code execution.

MySQL Error: #1142 - SELECT command denied to user

You need to give privileges to the particular user by giving the command mysql> GRANT ALL PRIVILEGES . To 'username'@'localhost'; and then give FLUSH PRIVILEGES; command. Then it won't give this error.., hope it helps thank you..!

Why doesn't calling a Python string method do anything unless you assign its output?

Example for String Methods

Given a list of filenames, we want to rename all the files with extension hpp to the extension h. To do this, we would like to generate a new list called newfilenames, consisting of the new filenames. Fill in the blanks in the code using any of the methods you’ve learned thus far, like a for loop or a list comprehension.

filenames = ["program.c", "stdio.hpp", "sample.hpp", "a.out", "math.hpp", "hpp.out"]
# Generate newfilenames as a list containing the new filenames
# using as many lines of code as your chosen method requires.
newfilenames = []
for i in filenames:
    if i.endswith(".hpp"):
        x = i.replace("hpp", "h")

# Should be ["program.c", "stdio.h", "sample.h", "a.out", "math.h", "hpp.out"]

How do I prevent an Android device from going to sleep programmatically?

If you are a Xamarin user, this is the solution:

   protected override void OnCreate(Bundle bundle)
        base.OnCreate(bundle); //always call superclass first


        LoadApplication(new App());

Get Filename Without Extension in Python

No need for regex. os.path.splitext is your friend:

>>> ('1.1.1', '.jpg')

Remote JMX connection

it seams that your ending quote comes too early. It should be after the last parameter.

This trick worked for me.

I noticed something interesting: when I start my application using the following command line:


If I try to connect to this port from a remote machine using jconsole, the TCP connection succeeds, some data is exchanged between remote jconsole and local jmx agent where my MBean is deployed, and then, jconsole displays a connect error message. I performed a wireshark capture, and it shows data exchange coming from both agent and jconsole.

Thus, this is not a network issue, if I perform a netstat -an with or without java.rmi.server.hostname system property, I have the following bindings:

 TCP               LISTENING
 TCP    [::]:9999              [::]:0                 LISTENING

It means that in both cases the socket created on port 9999 accepts connections from any host on any address.

I think the content of this system property is used somewhere at connection and compared with the actual IP address used by agent to communicate with jconsole. And if those address do not match, connection fails.

I did not have this problem while connecting from the same host using jconsole, only from real physical remote hosts. So, I suppose that this check is done only when connection is coming from the "outside".

Keep only date part when using pandas.to_datetime

I wanted to be able to change the type for a set of columns in a data frame and then remove the time keeping the day. round(), floor(), ceil() all work

df[date_columns] = df[date_columns].apply(pd.to_datetime)
df[date_columns] = df[date_columns].apply(lambda t: t.dt.floor('d'))

Strip Leading and Trailing Spaces From Java String

Use String#trim() method or String allRemoved = myString.replaceAll("^\\s+|\\s+$", "") for trim both the end.

For left trim:

String leftRemoved = myString.replaceAll("^\\s+", "");

For right trim:

String rightRemoved = myString.replaceAll("\\s+$", "");

What does the regex \S mean in JavaScript?

/\S/.test(string) returns true if and only if there's a non-space character in string. Tab and newline count as spaces.

Why can't I change my input value in React even with the onChange listener

You can do shortcut via inline function if you want to simply change the state variable without declaring a new function at top:

<input type="text" onChange={e => this.setState({ text: })}/>

How do I delete an exported environment variable?

unset is the command you're looking for.


Simulator or Emulator? What is the difference?

Both are models of an object that you have some means of controlling inputs to and observing outputs from.

The key difference is that:

  • With an emulator, you want the output exactly match what the object you are emulating would produce.
  • With a simulator, you want certain properties of your output to be similar to what the object would produce.

Let me give an example -- suppose you want to do some system testing to see how adding a new sensor (like a thermometer) to a system would affect the system. You know that the thermometer sends a message 8 time a second containing its measurement.

Simulation -- if you do not have the thermometer yet, but you want to test that this message rate will not overload you system, you can simulate the sensor by attaching a unit that sends a random number 8 times a second. You can run any test that does not rely on the actual value the sensor sends.

Emulation -- suppose you have a very expensive thermometer that measures to 0.001 C, and you want to see if you can get by with a cheaper thermometer that only measures to the nearest 0.5 C. You can emulate the cheaper thermometer using an expensive thermometer and then rounding the reading to the nearest 0.5 C and running tests that rely on the temperature values.

Note that simulations can also be used for forecasting or predicting behavior. Finite element analysis simulations are used in many applications, including weather prediction and virtual wind tunnels.

The definitions of the terms:

  • emulation -- surpass or exactly match
  • simulate -- imitate in appearance or character

How do I get a Cron like scheduler in Python?

If you're looking for something lightweight checkout schedule:

import schedule
import time

def job():
    print("I'm working...")


while 1:

Disclosure: I'm the author of that library.

How to Implement DOM Data Binding in JavaScript

Late to the party, especially since I've written 2 libs related months/years ago, I'll mention them later, but still looks relevant to me. To make it really short spoiler, the technologies of my choice are:

  • Proxy for observation of model
  • MutationObserver for the tracking changes of DOM (for binding reasons, not value changes)
  • value changes (view to model flow) are handled via regular addEventListener handlers

IMHO, in addition to the OP, it is important that data binding implementation will:

  • handle different app lifecycle cases (HTML first, then JS, JS first then HTML, dynamic attributes change etc)
  • allow deep binding of model, so that one may bind user.address.block
  • arrays as a model should be supported correctly (shift, splice and alike)
  • handle ShadowDOM
  • attempt to be as easy for technology replacement as possible, thus any templating sub-languages are a non-future-changes-friendly approach since it's too heavily coupled with framework

Taking all those into consideration, in my opinion makes it impossible to just throw few dozens of JS lines. I've tried to do it as a pattern rather than lib - didn't work for me.

Next, having Object.observe is removed, and yet given that observation of model is crucial part - this whole part MUST be concern-separated to another lib. Now to the point of principals of how I took this problem - exactly as OP asked:

Model (JS part)

My take for model observation is Proxy, it is the only sane way to make it work, IMHO. Fully featured observer deserves it's own library, so I've developed object-observer library for that sole purpose.

The model/s should be registered via some dedicated API, that's the point where POJOs turn into Observables, can't see any shortcut here. The DOM elements which are considered to be a bound views (see below), are updated with the values of the model/s at first and then upon each data change.

Views (HTML part)

IMHO, the cleanest way to express the binding, is via attributes. Many did this before and many will do after, so no news here, this is just a right way to do that. In my case I've gone with the following syntax: <span data-tie=" => targerProperty"></span>, but this is less important. What is important to me, no complex scripting syntax in the HTML - this is wrong, again, IMHO.

All the elements designated to be a bound views shall be collected at first. It looks inevitable to me from a performance side to manage some internal mapping between the models and the views, seems a right case where memory + some management should be sacrificed to save runtime lookups and updates.

The views are updated at first from the model, if available and upon later model changes, as we said. More yet, the whole DOM should be observed by means of MutationObserver in order to react (bind/unbind) on the dynamically added/remove/changed elements. Furthermore, all this, should be replicated into the ShadowDOM (open one, of course) in order to not leave unbound black holes.

The list of specifics may go further indeed, but those are in my opinion the main principals that would made data binding implemented with a good balance of feature completeness from one and sane simplicity from the other side.

And thus, in addition to the object-observer mentioned above, I've written indeed also data-tier library, that implements data binding along the above mentioned concepts.

Writing an input integer into a cell

When asking a user for a response to put into a cell using the InputBox method, there are usually three things that can happen¹.

  1. The user types something in and clicks OK. This is what you expect to happen and you will receive input back that can be returned directly to a cell or a declared variable.
  2. The user clicks Cancel, presses Esc or clicks × (Close). The return value is a boolean False. This should be accounted for.
  3. The user does not type anything in but clicks OK regardless. The return value is a zero-length string.

If you are putting the return value into a cell, your own logic stream will dictate what you want to do about the latter two scenarios. You may want to clear the cell or you may want to leave the cell contents alone. Here is how to handle the various outcomes with a variant type variable and a Select Case statement.

    Dim returnVal As Variant

    returnVal = InputBox(Prompt:="Type a value:", Title:="Test Data")

    'if the user clicked Cancel, Close or Esc the False
    'is translated to the variant as a vbNullString
    Select Case True
        Case Len(returnVal) = 0
            'no value but user clicked OK - clear the target cell
        Case Else
            'returned a value with OK, save it
            Range("A2") = returnVal
    End Select

¹ There is a fourth scenario when a specific type of InputBox method is used. An InputBox can return a formula, cell range error or array. Those are special cases and requires using very specific syntax options. See the supplied link for more.

Set start value for column with autoincrement

You need to set the Identity seed to that value:

 id int IDENTITY(9586,1)

To alter an existing table:


More info on CREATE TABLE (Transact-SQL) IDENTITY (Property)

$(window).height() vs $(document).height

you need know what it is mean about document and window.

  1. The window object represents an open window in a here
  2. The Document object is the root of a document here

jQuery disable a link

My fav in "checkout to edit an item and prevent -wild wild west clicks to anywhere- while in a checkout" functions

$('a').click(function(e) {
    var = $(this).attr('disabled');
    if (var === 'disabled') {

So if i want that all external links in a second action toolbar should be disabled while in the "edit-mode" as described above, i'll add in the edit function

$('#actionToolbar .external').attr('disabled', true);

Link example after fire:

<a href="" target="elsewhere" class="external" disabled="disabled">Google</a>

And now you CAN use disabled property for links


Failed to instantiate module [$injector:unpr] Unknown provider: $routeProvider

adding to scotty's answer:

Option 1: Either include this in your JS file:

<script src=""></script>

Option 2: or just use the URL to download 'angular-route.min.js' to your local.

and then (whatever option you choose) add this 'ngRoute' as dependency.

explained: var app = angular.module('myapp', ['ngRoute']);


Recording video feed from an IP camera over a network

about 3 years ago i needed cctv. I found zoneminder, tried to edit it to my liking, but found i was fixing it more than editing it.

Not to mention mp4 recording feature isn't actually part of the master branch (which is kind of lol, since its a cctv program and its already been about 3 years or more since it was suggested). Its literally just adapting the ffmpeg command lol.

So i found the solution!

If you want something done right, do it yourself.

I present to you Shinobi! Shinobi : The Open Source CCTV Platform

enter image description here

How to detect a route change in Angular?

In the component, you might want to try this:

import {NavigationEnd, NavigationStart, Router} from '@angular/router';

constructor(private router: Router) {
        (event) => {
            if (event instanceof NavigationStart)
                // start loading pages
            if (event instanceof NavigationEnd) {
                // end of loading paegs

onClick not working on mobile (touch)

you can use instead of click :

$('#whatever').on('touchstart click', function(){ /* do something... */ });

Property 'map' does not exist on type 'Observable<Response>'

Just write this command in the VS Code terminal of your project and restart the project.

npm install rxjs-compat

You need to import the map operator by adding this:

import 'rxjs/add/operator/map';

VBA Public Array : how to?

Well, basically what I found is that you can declare the array, but when you set it vba shows you an error.

So I put an special sub to declare global variables and arrays, something like:

Global example(10) As Variant

Sub set_values()

example(1) = 1
example(2) = 1
example(3) = 1
example(4) = 1
example(5) = 1
example(6) = 1
example(7) = 1
example(8) = 1
example(9) = 1
example(10) = 1

End Sub

And whenever I want to use the array, I call the sub first, just in case

call set_values

Msgbox example(5)

Perhaps is not the most correct way, but I hope it works for you

Delete commit on gitlab

We've had similar problem and it was not enough to only remove commit and force push to GitLab.
It was still available in GitLab interface using url:<group>/<project>/commit/<commit hash>

We've had to remove project from GitLab and recreate it to get rid of this commit in GitLab UI.

To add server using sp_addlinkedserver


EXEC sp_addlinkedserver @server='servername' 

No need to specify other parameters. You can go through this article.


You should try the HttpWebRequest class.

Creating a "Hello World" WebSocket example

I couldnt find a simple working example anywhere (as of Jan 19), so here is an updated version. I have chrome version 71.0.3578.98.

C# Websocket server :

using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;

namespace WebSocketServer
    class Program
    static Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
    static private string guid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";

    static void Main(string[] args)
        serverSocket.Bind(new IPEndPoint(IPAddress.Any, 8080));
        serverSocket.Listen(1); //just one socket
        serverSocket.BeginAccept(null, 0, OnAccept, null);

    private static void OnAccept(IAsyncResult result)
        byte[] buffer = new byte[1024];
            Socket client = null;
            string headerResponse = "";
            if (serverSocket != null && serverSocket.IsBound)
                client = serverSocket.EndAccept(result);
                var i = client.Receive(buffer);
                headerResponse = (System.Text.Encoding.UTF8.GetString(buffer)).Substring(0, i);
                // write received data to the console
            if (client != null)
                /* Handshaking and managing ClientSocket */
                var key = headerResponse.Replace("ey:", "`")
                          .Split('`')[1]                     // dGhlIHNhbXBsZSBub25jZQ== \r\n .......
                          .Replace("\r", "").Split('\n')[0]  // dGhlIHNhbXBsZSBub25jZQ==

                // key should now equal dGhlIHNhbXBsZSBub25jZQ==
                var test1 = AcceptKey(ref key);

                var newLine = "\r\n";

                var response = "HTTP/1.1 101 Switching Protocols" + newLine
                     + "Upgrade: websocket" + newLine
                     + "Connection: Upgrade" + newLine
                     + "Sec-WebSocket-Accept: " + test1 + newLine + newLine
                     //+ "Sec-WebSocket-Protocol: chat, superchat" + newLine
                     //+ "Sec-WebSocket-Version: 13" + newLine

                var i = client.Receive(buffer); // wait for client to send a message
                string browserSent = GetDecodedData(buffer, i);
                Console.WriteLine("BrowserSent: " + browserSent);

                //now send message to client
                client.Send(GetFrameFromString("This is message from server to client."));
                System.Threading.Thread.Sleep(10000);//wait for message to be sent
        catch (SocketException exception)
            throw exception;
            if (serverSocket != null && serverSocket.IsBound)
                serverSocket.BeginAccept(null, 0, OnAccept, null);

    public static T[] SubArray<T>(T[] data, int index, int length)
        T[] result = new T[length];
        Array.Copy(data, index, result, 0, length);
        return result;

    private static string AcceptKey(ref string key)
        string longKey = key + guid;
        byte[] hashBytes = ComputeHash(longKey);
        return Convert.ToBase64String(hashBytes);

    static SHA1 sha1 = SHA1CryptoServiceProvider.Create();
    private static byte[] ComputeHash(string str)
        return sha1.ComputeHash(System.Text.Encoding.ASCII.GetBytes(str));

    //Needed to decode frame
    public static string GetDecodedData(byte[] buffer, int length)
        byte b = buffer[1];
        int dataLength = 0;
        int totalLength = 0;
        int keyIndex = 0;

        if (b - 128 <= 125)
            dataLength = b - 128;
            keyIndex = 2;
            totalLength = dataLength + 6;

        if (b - 128 == 126)
            dataLength = BitConverter.ToInt16(new byte[] { buffer[3], buffer[2] }, 0);
            keyIndex = 4;
            totalLength = dataLength + 8;

        if (b - 128 == 127)
            dataLength = (int)BitConverter.ToInt64(new byte[] { buffer[9], buffer[8], buffer[7], buffer[6], buffer[5], buffer[4], buffer[3], buffer[2] }, 0);
            keyIndex = 10;
            totalLength = dataLength + 14;

        if (totalLength > length)
            throw new Exception("The buffer length is small than the data length");

        byte[] key = new byte[] { buffer[keyIndex], buffer[keyIndex + 1], buffer[keyIndex + 2], buffer[keyIndex + 3] };

        int dataIndex = keyIndex + 4;
        int count = 0;
        for (int i = dataIndex; i < totalLength; i++)
            buffer[i] = (byte)(buffer[i] ^ key[count % 4]);

        return Encoding.ASCII.GetString(buffer, dataIndex, dataLength);

    //function to create  frames to send to client 
    /// <summary>
    /// Enum for opcode types
    /// </summary>
    public enum EOpcodeType
        /* Denotes a continuation code */
        Fragment = 0,

        /* Denotes a text code */
        Text = 1,

        /* Denotes a binary code */
        Binary = 2,

        /* Denotes a closed connection */
        ClosedConnection = 8,

        /* Denotes a ping*/
        Ping = 9,

        /* Denotes a pong */
        Pong = 10

    /// <summary>Gets an encoded websocket frame to send to a client from a string</summary>
    /// <param name="Message">The message to encode into the frame</param>
    /// <param name="Opcode">The opcode of the frame</param>
    /// <returns>Byte array in form of a websocket frame</returns>
    public static byte[] GetFrameFromString(string Message, EOpcodeType Opcode = EOpcodeType.Text)
        byte[] response;
        byte[] bytesRaw = Encoding.Default.GetBytes(Message);
        byte[] frame = new byte[10];

        int indexStartRawData = -1;
        int length = bytesRaw.Length;

        frame[0] = (byte)(128 + (int)Opcode);
        if (length <= 125)
            frame[1] = (byte)length;
            indexStartRawData = 2;
        else if (length >= 126 && length <= 65535)
            frame[1] = (byte)126;
            frame[2] = (byte)((length >> 8) & 255);
            frame[3] = (byte)(length & 255);
            indexStartRawData = 4;
            frame[1] = (byte)127;
            frame[2] = (byte)((length >> 56) & 255);
            frame[3] = (byte)((length >> 48) & 255);
            frame[4] = (byte)((length >> 40) & 255);
            frame[5] = (byte)((length >> 32) & 255);
            frame[6] = (byte)((length >> 24) & 255);
            frame[7] = (byte)((length >> 16) & 255);
            frame[8] = (byte)((length >> 8) & 255);
            frame[9] = (byte)(length & 255);

            indexStartRawData = 10;

        response = new byte[indexStartRawData + length];

        int i, reponseIdx = 0;

        //Add the frame bytes to the reponse
        for (i = 0; i < indexStartRawData; i++)
            response[reponseIdx] = frame[i];

        //Add the data bytes to the response
        for (i = 0; i < length; i++)
            response[reponseIdx] = bytesRaw[i];

        return response;

Client html and javascript:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"_x000D_
<html xmlns="">_x000D_
    <script type="text/javascript">_x000D_
        var socket = new WebSocket('ws://localhost:8080/websession');_x000D_
        socket.onopen = function() {_x000D_
           // alert('handshake successfully established. May send data now...');_x000D_
     socket.send("Hi there from browser.");_x000D_
  socket.onmessage = function (evt) {_x000D_
                //alert("About to receive data");_x000D_
                var received_msg =;_x000D_
                alert("Message received = "+received_msg);_x000D_
        socket.onclose = function() {_x000D_
            alert('connection closed');_x000D_

How to convert a unix timestamp (seconds since epoch) to Ruby DateTime?

DateTime.strptime can handle seconds since epoch. The number must be converted to a string:

require 'date'

How to convert a PIL Image into a numpy array?

You're not saying how exactly putdata() is not behaving. I'm assuming you're doing

>>> pic.putdata(a)
Traceback (most recent call last):
  File "...blablabla.../PIL/", line 1185, in putdata, scale, offset)
SystemError: new style getargs format but argument is not a tuple

This is because putdata expects a sequence of tuples and you're giving it a numpy array. This

>>> data = list(tuple(pixel) for pixel in pix)
>>> pic.putdata(data)

will work but it is very slow.

As of PIL 1.1.6, the "proper" way to convert between images and numpy arrays is simply

>>> pix = numpy.array(pic)

although the resulting array is in a different format than yours (3-d array or rows/columns/rgb in this case).

Then, after you make your changes to the array, you should be able to do either pic.putdata(pix) or create a new image with Image.fromarray(pix).

how to delete files from amazon s3 bucket?

Welcome to 2020 here is the answer in Python/Django:

from django.conf import settings 
import boto3   
s3 = boto3.client('s3')
s3.delete_object(Bucket=settings.AWS_STORAGE_BUCKET_NAME, Key=f"media/{}")

Took me far too long to find the answer and it was as simple as this.

YAML mapping values are not allowed in this context

The elements of a sequence need to be indented at the same level. Assuming you want two jobs (A and B) each with an ordered list of key value pairs, you should use:

 - - name: A
   - schedule: "0 0/5 * 1/1 * ? *"
   - - type: mongodb.cluster
     - config:
       - host: mongodb://localhost:27017/admin?replicaSet=rs
       - minSecondaries: 2
       - minOplogHours: 100
       - maxSecondaryDelay: 120
 - - name: B
   - schedule: "0 0/5 * 1/1 * ? *"
   - - type: mongodb.cluster
     - config:
       - host: mongodb://localhost:27017/admin?replicaSet=rs
       - minSecondaries: 2
       - minOplogHours: 100
       - maxSecondaryDelay: 120

Converting the sequences of (single entry) mappings to a mapping as @Tsyvarrev does is also possible, but makes you lose the ordering.

How to merge two arrays in JavaScript and de-duplicate items

Extremely fast

Using this discovery I create extremely fast solution for medium size arrays and compare performance with chosen solutions (I name my solution as K). This solution modify input arrays

function K(arr1,arr2) {
  let r=[], h={};
  while(arr1.length) {
    let e = arr1.shift();
    if(!h[e]) h[e]=1 && r.push(e);
  while(arr2.length) {
    let e = arr2.shift();
    if(!h[e]) h[e]=1 && r.push(e);
  return r;

var array1 = ["Vijendra", "Singh"];
var array2 = ["Singh", "Shakya"];



Today 2020.10.15 I perform tests on MacOs HighSierra 10.13.6 on Chrome v86, Safari v13.1.2 and Firefox v81 for chosen solutions.


For all browsers

  • solution based on where-shift (K) is fastest (except small arrays on Safari where is fast) - for big arrays is >1000x faster than other solutions (!!!)
  • solution F is fast (fastest on Safari) for small arrays
  • solution M is slowest for small arrays
  • solutions E,F,I are slowest for big arrays

We should note here that for very big arrays on Chrome the K solution can slow down - details here

enter image description here


I perform 2 tests cases:

  • for 2 elements arrays - you can run it HERE
  • for 10000 elements arrays - you can run it HERE

on solutions A, B, C, D, E, F, G, H, I, J, K (my), L, M presented in below snippet

function A(arr1,arr2) {
  return _.union(arr1,arr2)

function B(arr1,arr2) {
  return _.unionWith(arr1, arr2, _.isEqual);

function C(arr1,arr2) {
  return [ Set([...arr1,...arr2])]

function D(arr1,arr2) {
  return Array.from(new Set(arr1.concat(arr2)))

function E(arr1,arr2) {
  return arr1.concat(arr2.filter((item) => arr1.indexOf(item) < 0))

function F(array1, array2){
  for (var i = 0; i < array2.length; i++)
    if (array1.indexOf(array2[i]) === -1)
  return array1;

function G(arr1,arr2) {
  var hash = {};
  var i;
  for (i = 0; i < arr1.length; i++) {
    hash[arr1[i]] = true;
  for (i = 0; i < arr2.length; i++) {
    hash[arr2[i]] = true;
  return Object.keys(hash);

function H(a, b){
    var hash = {};
    var ret = [];

    for(var i=0; i < a.length; i++){
        var e = a[i];
        if (!hash[e]){
            hash[e] = true;

    for(var i=0; i < b.length; i++){
        var e = b[i];
        if (!hash[e]){
            hash[e] = true;

    return ret;

function I(a1, a2) {
    var ai = [];
    for (var x = 0; x < a2.length; x++) {

    for (var x = 0; x < a1.length; x++) {
        for (var y = 0; y < ai.length; y++) {
            if (a1[x] === a2[ai[y]]) {
                ai.splice(y, 1);

    for (var x = 0; x < ai.length; x++) {

    return a1;

function J(arr1,arr2) {
  function arrayUnique(array) {
      var a = array.concat();
      for(var i=0; i<a.length; ++i) {
          for(var j=i+1; j<a.length; ++j) {
              if(a[i] === a[j])
                  a.splice(j--, 1);

      return a;

  return arrayUnique(arr1.concat(arr2));

// my
function K(arr1,arr2) {
  let r=[], h={};
  while(arr1.length) {
    let e = arr1.shift();
    if(!h[e]) h[e]=1 && r.push(e);
  while(arr2.length) {
    let e = arr2.shift();
    if(!h[e]) h[e]=1 && r.push(e);
  return r;

function L(array1, array2) {
    const array3 = array1.slice(0);
    let len1 = array1.length;
    let len2 = array2.length;
    const assoc = {};

    while (len1--) {
        assoc[array1[len1]] = null;

    while (len2--) {
        let itm = array2[len2];

        if (assoc[itm] === undefined) { // Eliminate the indexOf call
            assoc[itm] = null;

    return array3;

function M(arr1,arr2) {
  const comp = f => g => x => f(g(x));
  const apply = f => a => f(a);
  const flip = f => b => a => f(a) (b);
  const concat = xs => y => xs.concat(y);
  const afrom = apply(Array.from);
  const createSet = xs => new Set(xs);
  const filter = f => xs => xs.filter(apply(f));

  const dedupe = comp(afrom) (createSet);

  const union = xs => ys => {
    const zs = createSet(xs);  
    return concat(xs) (
      filter(x => zs.has(x)
       ? false
       : zs.add(x)
    ) (ys));

  return union(dedupe(arr1)) (arr2)

// -------------
// -------------

var array1 = ["Vijendra","Singh"];
var array2 = ["Singh", "Shakya"];

[A,B,C,D,E,F,G,H,I,J,K,L,M].forEach(f=> {
  console.log(`${} [${f([...array1],[...array2])}]`);
<script src="" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"></script>
This shippet only presents functions used in performance tests - it not perform tests itself!

And here are example test run for chrome

enter image description here

How do I sort a Set to a List in Java?

TreeSet sortedset = new TreeSet();


where originalset = unsorted set and list = the list to be returned

How to get the previous url using PHP

Use the $_SERVER['HTTP_REFERER'] header, but bear in mind anybody can spoof it at anytime regardless of whether they clicked on a link.

Is it possible to use if...else... statement in React render function?

If you need more than one condition, so you can try this out

import { If, Then, ElseIf, Else } from 'react-if-elseif-else-render';

class Example extends Component {

  render() {
    var i = 3; // it will render '<p>Else</p>'
    return (
      <If condition={i == 1}>
          <p>Then: 1</p>
        <ElseIf condition={i == 2}>
          <p>ElseIf: 2</p>

create table in postgreSQL

-- Table: "user"

-- DROP TABLE "user";

  id bigserial NOT NULL,
  name text NOT NULL,
  email character varying(20) NOT NULL,
  password text NOT NULL,
  OWNER TO postgres;

What are some good SSH Servers for windows?

I've been using Bitvise SSH Server and it's really great. From install to administration it does it all through a GUI so you won't be putting together a sshd_config file. Plus if you use their client, Tunnelier, you get some bonus features (like mapping shares, port forwarding setup up server side, etc.) If you don't use their client it will still work with the Open Source SSH clients.

It's not Open Source and it costs $39.95, but I think it's worth it.

UPDATE 2009-05-21 11:10: The pricing has changed. The current price is $99.95 per install for commercial, but now free for non-commercial/personal use. Here is the current pricing.

Android Device not recognized by adb

Fundamentally, the issue has to do with not being able to get MTP+ADB working while for example PTP+ADB may work. In my case when I plugged Nexus 5, windows 7 will install only MTP driver completely ignoring ADB. I couldn't find a good solution for this problem anywhere else so here I provide steps (some of the steps I copied from other sources):

0) Unplug Nexus 5. Make sure you selected MTP and ADB.

1) Make sure that sdk\extras\google\usb_driverandroid_winusb.inf in Google SDK had the following lines (in two places in that file):

;Google Nexus (generic)

%CompositeAdbInterface% = USB_Install, USB\VID_18D1&PID_4EE2&MI_01

NOTE: VID_18D1 is Google VID, PID_4EE2 is PID for MTP+ADB, MI_01 means that ADB is on interface 1 (MTP is on interface 0).

You can check what is on what interface by plugging Nexus 5 into a Linux system and typing lsusb.

2) first delete all installed Google USB drivers. One good tool is called USBDeview and can be find at the following location: Download the tool and run it (there is no need to install it). Take a look at the colored status indicator on the far-left of the USBDeview window. Green indicates the the device functions properly. Pink means the device can unplug and works properly (although it may not actually work properly). Red indicates a disabled USB device. Gray (circled, below) means the device is installed, but not connected. Second, remove all gray items with the words “Google”, “Linux”, “ADB”, or “Android” in the title.

3) Now delete old cached Google *.inf files. Open a Windows Explorer and navigate to the C:\Windows\INF directory. Somewhere in there there is an "oemN.inf" file (where N is a number that will vary on your system) that is a copy of the android_usb.inf -- the thing to do is to find which file and remove it. Windows keeps a cache of the INF files here and what we found is that sometimes an older cached copy is used instead of a newer version.

One simple way to find which one using the Windows Explorer: - In the explorer's Search box, enter "" without the quotes. - Typically the search will be empty because no filename has this pattern. - Go to Tools/Folder Options, click Search Tab and click Always search file name and contents. Click Apply - Search again. This time it should list a few files such as "oem90.inf" (you'll have one or more, with different numbers).

Now use the Windows Explorer and delete the "oemNN.*" files that matched above (only those with androidwinusb in them.).

4) We now want to disable installation of MTP by windows before windows discovers ADB. Now search for wpdmtp.* files in the same directory. Presence of these files will force install MTP disregarding ADB class in the same (composite) device. Move these files out of \inf folder

5) plug in the device again. This time, both MTP and Android ADB driver installation will fail.

6) Find Other devices in the Device Manager and when expanded it should show Nexus 5 and MTP. Right click and update Nexus 5 by navigating to the sdk\extras\google\usb_driver\android_winusb.inf.

Move wpdmtp.* files back to \inf folder. Right click MTP device and update.

7) If necessary, confirm on your Nexus 5 that this PC has access to the phone.

8) If everything went as expected you should see in Device Manager the following:

  • Expand Android Device. Right click Android Composite ADB Interface, select Properties, choose tab Details, under Property select Hardware Ids. You should see USB\VID_18D1&PID_4EE2&MI_01

  • Expand Portable devices. Right click Nexus 5, select Properties, choose tab Details, under Property select Hardware Ids. You should see USB\VID_18D1&PID_4EE2&MI_00

Counting the number of non-NaN elements in a numpy ndarray in Python

Quick-to-write alterantive

Even though is not the fastest choice, if performance is not an issue you can use:



In [7]: %timeit data.size - np.count_nonzero(np.isnan(data))
10 loops, best of 3: 67.5 ms per loop

In [8]: %timeit sum(~np.isnan(data))
10 loops, best of 3: 154 ms per loop

In [9]: %timeit np.sum(~np.isnan(data))
10 loops, best of 3: 140 ms per loop

Enable IIS7 gzip

If you use YSlow with Firebug and analyse your page performance, YSlow will certainly tell you what artifacts on your page are not gzip'd!

Pass a reference to DOM object with ng-click

While you do the following, technically speaking:

<button ng-click="doSomething($event)"></button>
// In controller:
$scope.doSomething = function($event) {
  //reference to the button that triggered the function:

This is probably something you don't want to do as AngularJS philosophy is to focus on model manipulation and let AngularJS do the rendering (based on hints from the declarative UI). Manipulating DOM elements and attributes from a controller is a big no-no in AngularJS world.

You might check this answer for more info:

What does O(log n) mean exactly?

O(log n) refers to a function (or algorithm, or step in an algorithm) working in an amount of time proportional to the logarithm (usually base 2 in most cases, but not always, and in any event this is insignificant by big-O notation*) of the size of the input.

The logarithmic function is the inverse of the exponential function. Put another way, if your input grows exponentially (rather than linearly, as you would normally consider it), your function grows linearly.

O(log n) running times are very common in any sort of divide-and-conquer application, because you are (ideally) cutting the work in half every time. If in each of the division or conquer steps, you are doing constant time work (or work that is not constant-time, but with time growing more slowly than O(log n)), then your entire function is O(log n). It's fairly common to have each step require linear time on the input instead; this will amount to a total time complexity of O(n log n).

The running time complexity of binary search is an example of O(log n). This is because in binary search, you are always ignoring half of your input in each later step by dividing the array in half and only focusing on one half with each step. Each step is constant-time, because in binary search you only need to compare one element with your key in order to figure out what to do next irregardless of how big the array you are considering is at any point. So you do approximately log(n)/log(2) steps.

The running time complexity of merge sort is an example of O(n log n). This is because you are dividing the array in half with each step, resulting in a total of approximately log(n)/log(2) steps. However, in each step you need to perform merge operations on all elements (whether it's one merge operation on two sublists of n/2 elements, or two merge operations on four sublists of n/4 elements, is irrelevant because it adds to having to do this for n elements in each step). Thus, the total complexity is O(n log n).

*Remember that big-O notation, by definition, constants don't matter. Also by the change of base rule for logarithms, the only difference between logarithms of different bases is a constant factor.

target="_blank" vs. target="_new"

Using target="_blank" will instruct the browser to create a new browser tab or window when the user clicks on the link.

Using target="_new" is technically invalid according to the specifications, but as far as I know every browser will behave the same way:

  • it will search for a tab or window with the context name "_new"
  • if a "_new" tab/window is found, then the URL is loaded into it
  • if it's not found, a new tab/window is created with the context name "_new", and the URL loaded into it

Note target="_new" will behave exactly the same as target="new", and the latter is valid HTML while the former is invalid HTML.

Adding some confusion to this, in HTML4 the target attribute was deprecated. In HTML5 this decision was reversed, and it is an official part of the spec once again. All browsers support target no matter what version of HTML you are using, but some validators will flag the use as deprecated if your doctype is HTML4.

Check box size change with CSS

Try this

<input type="checkbox" style="zoom:1.5;" />
/* The value 1.5 i.e., the size of checkbox will be increased by 0.5% */

How do I see the current encoding of a file in Sublime Text?

ShowEncoding is another simple plugin that shows you the encoding in the status bar. That's all it does, to convert between encodings use the built-in "Save with Encoding" and "Reopen with Encoding" commands.

python error: no module named pylab

With the addition of Python 3, here is an updated code that works:

import numpy as n
import scipy as s
import matplotlib.pylab as p #pylab is part of matplotlib


Y = n.ones(len(C))

for x in range(iter):
    Y = Y**2 - C   #get rid of early transients

for x in range(iter): 
    Y = Y**2 - C
    p.plot(C,Y, '.', color = 'k', markersize = 2)

Converting binary to decimal integer output

The input may be string or integer.

num = 1000  #or num = '1000'  
sum(map(lambda x: x[1]*(2**x[0]), enumerate(map(int, str(num))[::-1])))

# 8

Found a swap file by the name

Looks like you have an open git commit or git merge going on, and an editor is still open editing the commit message.

Two choices:

  1. Find the session and finish it (preferable).
  2. Delete the .swp file (if you're sure the other git session has gone away).

Clarification from comments:

  • The session is the editing session.
  • You can see what .swp is being used by entering the command :sw within the editing session, but generally it's a hidden file in the same directory as the file you are using, with a .swp file suffix (i.e. ~/myfile.txt would be ~/.myfile.txt.swp).

Populate nested array in mongoose

You can populate multiple nested documents like this.

      path: 'pages',
      populate: [{
       path: 'components',
       model: 'Component'
        path: 'AnotherRef',
        model: 'AnotherRef',
        select: 'firstname lastname'
   .exec(function(err, docs) {});

Sites not accepting wget user agent header

You need to set both the user-agent and the referer:

 wget  --header="Accept: text/html" --user-agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:21.0) Gecko/20100101 Firefox/21.0" --referrer

How to convert a command-line argument to int?

Since this answer was somehow accepted and thus will appear at the top, although it's not the best, I've improved it based on the other answers and the comments.

The C way; simplest, but will treat any invalid number as 0:

#include <cstdlib>

int x = atoi(argv[1]);

The C way with input checking:

#include <cstdlib>

errno = 0;
char *endptr;
long int x = strtol(argv[1], &endptr, 10);
if (endptr == argv[1]) {
  std::cerr << "Invalid number: " << argv[1] << '\n';
} else if (*endptr) {
  std::cerr << "Trailing characters after number: " << argv[1] << '\n';
} else if (errno == ERANGE) {
  std::cerr << "Number out of range: " << argv[1] << '\n';

The C++ iostreams way with input checking:

#include <sstream>

std::istringstream ss(argv[1]);
int x;
if (!(ss >> x)) {
  std::cerr << "Invalid number: " << argv[1] << '\n';
} else if (!ss.eof()) {
  std::cerr << "Trailing characters after number: " << argv[1] << '\n';

Alternative C++ way since C++11:

#include <stdexcept>
#include <string>

std::string arg = argv[1];
try {
  std::size_t pos;
  int x = std::stoi(arg, &pos);
  if (pos < arg.size()) {
    std::cerr << "Trailing characters after number: " << arg << '\n';
} catch (std::invalid_argument const &ex) {
  std::cerr << "Invalid number: " << arg << '\n';
} catch (std::out_of_range const &ex) {
  std::cerr << "Number out of range: " << arg << '\n';

All four variants assume that argc >= 2. All accept leading whitespace; check isspace(argv[1][0]) if you don't want that. All except atoi reject trailing whitespace.

Windows ignores JAVA_HOME: how to set JDK as default?

I have this issue too. I am running 1.6 but want to build the code I'm working on with 1.5. I've changed the JAVA_HOME and PATH (both user and system) to no avail.

The answer is that the installer for 1.6 dropped java.exe, javaw.exe, and javaws.exe into my Windows\System32 folder (Windows 7).

I solved it by renaming those files to java_wrong.exe, javaw_wrong.exe, and javaws_wrong.exe. Only after doing that does it pick up the correct version of java as defined in JAVA_HOME and PATH. I renamed the files thusly because that deleted them in an easily reversible manner.

Hope this helps!

Error: Microsoft Visual C++ 10.0 is required (Unable to find vcvarsall.bat) when running Python script

Tried to install lxml, grab and other extensions, which requires VS 10.0+ and get the same issue. I find own way to solve this problem(Windows 10 x64, Python 3.4+):

  1. Install Visual C++ 2010 Express (download). (Do not install Microsoft Visual Studio 2010 Service Pack 1 )

  2. Remove all the Microsoft Visual C++ 2010 Redistributable packages from Control Panel\Programs and Features. If you don't do those then the install is going to fail with an obscure "Fatal error during installation" error.

  3. Install offline version of Windows SDK for Visual Studio 2010 (v7.1) (download). This is required for 64bit extensions. Windows has builtin mounting for ISOs. Just mount the ISO and run Setup\SDKSetup.exe instead of setup.exe.

  4. Create a vcvars64.bat file in C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin\amd64 that contains:

    CALL "C:\Program Files\Microsoft SDKs\Windows\v7.1\Bin\SetEnv.cmd" /x64

  5. Find extension on this site, then put them into the python folder, and install .whl extension with pip:

    python -m pip install extensionname.whl

  6. Enjoy

Inheriting from a template class in c++

For understanding templates, it's of huge advantage to get the terminology straight because the way you speak about them determines the way to think about them.

Specifically, Area is not a template class, but a class template. That is, it is a template from which classes can be generated. Area<int> is such a class (it's not an object, but of course you can create an object from that class in the same ways you can create objects from any other class). Another such class would be Area<char>. Note that those are completely different classes, which have nothing in common except for the fact that they were generated from the same class template.

Since Area is not a class, you cannot derive the class Rectangle from it. You only can derive a class from another class (or several of them). Since Area<int> is a class, you could, for example, derive Rectangle from it:

class Rectangle:
  public Area<int>
  // ...

Since Area<int> and Area<char> are different classes, you can even derive from both at the same time (however when accessing members of them, you'll have to deal with ambiguities):

class Rectangle:
  public Area<int>,
  public Area<char>
  // ...

However you have to specify which classed to derive from when you define Rectangle. This is true no matter whether those classes are generated from a template or not. Two objects of the same class simply cannot have different inheritance hierarchies.

What you can do is to make Rectangle a template as well. If you write

template<typename T> class Rectangle:
  public Area<T>
  // ...

You have a template Rectangle from which you can get a class Rectangle<int> which derives from Area<int>, and a different class Rectangle<char> which derives from Area<char>.

It may be that you want to have a single type Rectangle so that you can pass all sorts of Rectangle to the same function (which itself doesn't need to know the Area type). Since the Rectangle<T> classes generated by instantiating the template Rectangle are formally independent of each other, it doesn't work that way. However you can make use of multiple inheritance here:

class Rectangle // not inheriting from any Area type
  // Area independent interface

template<typename T> class SpecificRectangle:
  public Rectangle,
  public Area<T>
  // Area dependent stuff

void foo(Rectangle&); // A function which works with generic rectangles

int main()
  SpecificRectangle<int> intrect;

  SpecificRectangle<char> charrect;

If it is important that your generic Rectangle is derived from a generic Area you can do the same trick with Area too:

class Area
  // generic Area interface

class Rectangle:
  public virtual Area // virtual because of "diamond inheritance"
  // generic rectangle interface

template<typename T> class SpecificArea:
  public virtual Area
  // specific implementation of Area for type T

template<typename T> class SpecificRectangle:
  public Rectangle, // maybe this should be virtual as well, in case the hierarchy is extended later
  public SpecificArea<T> // no virtual inheritance needed here
  // specific implementation of Rectangle for type T

.war vs .ear file

To make the project transport, deployment made easy. need to compressed into one file. JAR (java archive) group of .class files

WAR (web archive) - each war represents one web application - use only web related technologies like servlet, jsps can be used. - can run on Tomcat server - web app developed by web related technologies only jsp servlet html js - info representation only no transactions.

EAR (enterprise archive) - each ear represents one enterprise application - we can use anything from j2ee like ejb, jms can happily be used. - can run on Glassfish like server not on Tomcat server. - enterprise app devloped by any technology anything from j2ee like all web app plus ejbs jms etc. - does transactions with info representation. eg. Bank app, Telecom app

Why is there extra padding at the top of my UITableView with style UITableViewStyleGrouped in iOS7

I've been banging my head against this one as well. Pretty sure this is an iOS7 bug. What helped me eventually, is the order of views in the xib. I had one view in which table view was displayed correctly, and another in which the table view had that extra 35px space. The only difference between then (UITableView wise), is that in the bad-displaying view UITableView was the first child, whereas in the view which was displaying correctly, it was the second.

That did the trick for me, just changing the order of views. I really prefer not to add extra lines of code for a workaround...

Find object by its property in array of objects with AngularJS way

The solucion that work for me is the following

$filter('filter')(data, {'id':10}) 

How to check sbt version?

Running the command, "sbt sbt-version" will simply output your current directory and the version number.

$ sbt sbt-version
[info] Set current project to spark (in build file:/home/morgan/code/spark/)
[info] 0.13.8

What does the colon (:) operator do?

It's used in for loops to iterate over a list of objects.

for (Object o: list)
    // o is an element of list here

Think of it as a for <item> in <list> in Python.

How do I find and replace all occurrences (in all files) in Visual Studio Code?

Update - as of version 1.3 (june 2016) it is possible to search and replace in Visual Studio Code. Using ctrl + shift + f , you can search and replace text in all files.

It seems this is not possible at the moment (Version 1.1.1 (April 2016))

"Q: Is it possible to globally search and replace?

A: This feature is not yet implemented, but you can expect it to come in the future!"

This seems also requested by community:

Access iframe elements in JavaScript

If your iframe is in the same domain as your parent page you can access the elements using document.frames collection.

// replace myIFrame with your iFrame id
// replace myIFrameElemId with your iFrame's element id
// you can work on document.frames['myIFrame'].document like you are working on
// normal document object in JS

If your iframe is not in the same domain the browser should prevent such access for security reasons.

Get the generated SQL statement from a SqlCommand object?

If your database was Oracle and the sql text contains dynamic variables named like :1,:2 ,... then you can use:

string query = cmd.CommandText;
int i = 1;
foreach (OracleParameter p in cmd.Parameters)
    query = query.Replace(":"+i.ToString(),((p.Value==null)?"":p.Value.ToString()));

Is there a null-coalescing (Elvis) operator or safe navigation operator in javascript?

You can achieve roughly the same effect by saying:

var displayName = || "Anonymous";

php var_dump() vs print_r()

Generally, print_r( ) output is nicer, more concise and easier to read, aka more human-readable but cannot show data types.

With print_r() you can also store the output into a variable:

$output = print_r($array, true);

which var_dump() cannot do. Yet var_dump() can show data types.

Error: Can't set headers after they are sent to the client

I had this same issue and realised it was because I was calling res.redirect without a return statement, so the next function was also being called immediately afterwards:

auth.annonymousOnly = function(req, res, next) {
    if (req.user) res.redirect('/');

Which should have been:

auth.annonymousOnly = function(req, res, next) {
    if (req.user) return res.redirect('/');

Play audio file from the assets directory


Your version would work if you had only one file in the assets directory. The asset directory contents are not actually 'real files' on disk. All of them are put together one after another. So, if you do not specify where to start and how many bytes to read, the player will read up to the end (that is, will keep playing all the files in assets directory)

NullPointerException in eclipse in Eclipse itself at PartServiceImpl.internalFixContext

Better you update your eclipse by clicking it on help >> check for updates, also you can start eclipse by entering command in command prompt eclipse -clean.
Hope this will help you.

makefiles - compile all c files at once

LIBS  = -lkernel32 -luser32 -lgdi32 -lopengl32
CFLAGS = -Wall

# Should be equivalent to your list of C files, if you don't build selectively
SRC=$(wildcard *.c)

test: $(SRC)
    gcc -o $@ $^ $(CFLAGS) $(LIBS)