Programs & Examples On #Qlpreviewcontroller

A QLPreviewController, or Quick Look preview controller, provides a specialized view for previewing a file on the iOS platform.

Python functions call by reference

Python is neither pass-by-value nor pass-by-reference. It's more of "object references are passed by value" as described here:

  1. Here's why it's not pass-by-value. Because

    def append(list):
        list.append(1)
    
    list = [0]
    reassign(list)
    append(list)
    

returns [0,1] showing that some kind of reference was clearly passed as pass-by-value does not allow a function to alter the parent scope at all.

Looks like pass-by-reference then, hu? Nope.

  1. Here's why it's not pass-by-reference. Because

    def reassign(list):
      list = [0, 1]
    
    list = [0]
    reassign(list)
    print list
    

returns [0] showing that the original reference was destroyed when list was reassigned. pass-by-reference would have returned [0,1].

For more information look here:

If you want your function to not manipulate outside scope, you need to make a copy of the input parameters that creates a new object.

from copy import copy

def append(list):
  list2 = copy(list)
  list2.append(1)
  print list2

list = [0]
append(list)
print list

correct PHP headers for pdf file download

Example 2 on w3schools shows what you are trying to achieve.

<?php
header("Content-type:application/pdf");

// It will be called downloaded.pdf
header("Content-Disposition:attachment;filename='downloaded.pdf'");

// The PDF source is in original.pdf
readfile("original.pdf");
?>

Also remember that,

It is important to notice that header() must be called before any actual output is sent (In PHP 4 and later, you can use output buffering to solve this problem)

MongoDB: update every document on one field

You can use updateMany() methods of mongodb to update multiple document

Simple query is like this

db.collection.updateMany(filter, update, options)

For more doc of uppdateMany read here

As per your requirement the update code will be like this:

User.updateMany({"created": false}, {"$set":{"created": true}});

here you need to use $set because you just want to change created from true to false. For ref. If you want to change entire doc then you don't need to use $set

How to loop through all elements of a form jQuery

As taken from the #jquery Freenode IRC channel:

$.each($(form).serializeArray(), function(_, field) { /* use field.name, field.value */ });

Thanks to @Cork on the channel.

How to fire AJAX request Periodically?

As others have pointed out setInterval and setTimeout will do the trick. I wanted to highlight a bit more advanced technique that I learned from this excellent video by Paul Irish: http://paulirish.com/2010/10-things-i-learned-from-the-jquery-source/

For periodic tasks that might end up taking longer than the repeat interval (like an HTTP request on a slow connection) it's best not to use setInterval(). If the first request hasn't completed and you start another one, you could end up in a situation where you have multiple requests that consume shared resources and starve each other. You can avoid this problem by waiting to schedule the next request until the last one has completed:

// Use a named immediately-invoked function expression.
(function worker() {
  $.get('ajax/test.html', function(data) {
    // Now that we've completed the request schedule the next one.
    $('.result').html(data);
    setTimeout(worker, 5000);
  });
})();

For simplicity I used the success callback for scheduling. The down side of this is one failed request will stop updates. To avoid this you could use the complete callback instead:

(function worker() {
  $.ajax({
    url: 'ajax/test.html', 
    success: function(data) {
      $('.result').html(data);
    },
    complete: function() {
      // Schedule the next request when the current one's complete
      setTimeout(worker, 5000);
    }
  });
})();

How to convert a file to utf-8 in Python?

This is a Python3 function for converting any text file into the one with UTF-8 encoding. (without using unnecessary packages)

def correctSubtitleEncoding(filename, newFilename, encoding_from, encoding_to='UTF-8'):
    with open(filename, 'r', encoding=encoding_from) as fr:
        with open(newFilename, 'w', encoding=encoding_to) as fw:
            for line in fr:
                fw.write(line[:-1]+'\r\n')

You can use it easily in a loop to convert a list of files.

SQL Server ON DELETE Trigger

INSERTED and DELETED are virtual tables. They need to be used in a FROM clause.

CREATE TRIGGER sampleTrigger
    ON database1.dbo.table1
    FOR DELETE
AS
    IF EXISTS (SELECT foo
               FROM database2.dbo.table2
               WHERE id IN (SELECT deleted.id FROM deleted)
               AND bar = 4)

How to check if string input is a number?

You can use the isdigit() method for strings. In this case, as you said the input is always a string:

    user_input = input("Enter something:")
    if user_input.isdigit():
        print("Is a number")
    else:
        print("Not a number")

How can I use an array of function pointers?

Can use it in the way like this:

//! Define:
#define F_NUM 3
int (*pFunctions[F_NUM])(void * arg);

//! Initialise:
int someFunction(void * arg) {
    int a= *((int*)arg);
    return a*a;
}

pFunctions[0]= someFunction;

//! Use:
int someMethod(int idx, void * arg, int * result) {
    int done= 0;
    if (idx < F_NUM && pFunctions[idx] != NULL) {
        *result= pFunctions[idx](arg);
        done= 1;
    }
    return done;
}

int x= 2;
int z= 0;
someMethod(0, (void*)&x, &z);
assert(z == 4);

Keep values selected after form submission

Just change this line:

 <input type="submit" value="Submit" class="submit" />

with this line:

 <input type="submit" value="Submit/Reload" class="submit" onclick="history.go(-1);">

Git merge with force overwrite

When I tried using -X theirs and other related command switches I kept getting a merge commit. I probably wasn't understanding it correctly. One easy to understand alternative is just to delete the branch then track it again.

git branch -D <branch-name>
git branch --track <branch-name> origin/<branch-name>

This isn't exactly a "merge", but this is what I was looking for when I came across this question. In my case I wanted to pull changes from a remote branch that were force pushed.

What's the best way to share data between activities?

What you can use:

  1. passing data between activities (like Cristian said)
  2. using a class with a lot of static variables (so you can call them without an instance of the class and without using getter/setter)
  3. Using a database
  4. Shared Preferences

What you choose depends on your needs. Probably you will use more than one way when you have "a lot of"

Make a link open a new window (not tab)

That will open a new window, not tab (with JavaScript, but quite laconically):

<a href="print.html"  
    onclick="window.open('print.html', 
                         'newwindow', 
                         'width=300,height=250'); 
              return false;"
 >Print</a>

Spring JPA @Query with LIKE

You Missed a colon(:) before the username parameter. therefore your code must change from:

@Query("select u from user u where u.username like '%username%'")

to :

@Query("select u from user u where u.username like '%:username%'")

Get Locale Short Date Format using javascript

Short date patterns:

const shortDatePatterns = {
'aa-DJ': "dd/MM/yyyy",
'aa-ER': "dd/MM/yyyy",
'aa-ET': "dd/MM/yyyy",
'af': "yyyy-MM-dd",
'af-NA': "yyyy-MM-dd",
'af-ZA': "yyyy-MM-dd",
'agq-CM': "d/M/yyyy",
'ak-GH': "yyyy/MM/dd",
'am': "dd/MM/yyyy",
'am-ET': "dd/MM/yyyy",
'ar': "dd/MM/yy",
'ar-001': "d/M/yyyy",
'ar-AE': "dd/MM/yyyy",
'ar-BH': "dd/MM/yyyy",
'ar-DJ': "d/M/yyyy",
'ar-DZ': "dd-MM-yyyy",
'ar-EG': "dd/MM/yyyy",
'ar-ER': "d/M/yyyy",
'ar-IL': "d/M/yyyy",
'ar-IQ': "dd/MM/yyyy",
'ar-JO': "dd/MM/yyyy",
'ar-KM': "d/M/yyyy",
'ar-KW': "dd/MM/yyyy",
'ar-LB': "dd/MM/yyyy",
'ar-LY': "dd/MM/yyyy",
'ar-MA': "dd-MM-yyyy",
'ar-MR': "d/M/yyyy",
'ar-OM': "dd/MM/yyyy",
'ar-PS': "d/M/yyyy",
'ar-QA': "dd/MM/yyyy",
'ar-SA': "dd/MM/yy",
'ar-SD': "d/M/yyyy",
'ar-SO': "d/M/yyyy",
'ar-SS': "d/M/yyyy",
'ar-SY': "dd/MM/yyyy",
'ar-TD': "d/M/yyyy",
'ar-TN': "dd-MM-yyyy",
'ar-YE': "dd/MM/yyyy",
'arn-CL': "dd-MM-yyyy",
'as': "dd-MM-yyyy",
'as-IN': "dd-MM-yyyy",
'asa-TZ': "dd/MM/yyyy",
'ast-ES': "d/M/yyyy",
'az': "dd.MM.yyyy",
'az-Cyrl-AZ': "dd.MM.yyyy",
'az-Latn-AZ': "dd.MM.yyyy",
'ba': "dd.MM.yy",
'ba-RU': "dd.MM.yy",
'bas-CM': "d/M/yyyy",
'be': "dd.MM.yy",
'be-BY': "dd.MM.yy",
'bem-ZM': "dd/MM/yyyy",
'bez-TZ': "dd/MM/yyyy",
'bg': "d.M.yyyy '?.'",
'bg-BG': "d.M.yyyy '?.'",
'bin-NG': "d/M/yyyy",
'bm': "d/M/yyyy",
'bm-Latn-ML': "d/M/yyyy",
'bn': "d/M/yyyy",
'bn-BD': "d/M/yyyy",
'bn-IN': "dd-MM-yy",
'bo': "yyyy/M/d",
'bo-CN': "yyyy/M/d",
'bo-IN': "yyyy-MM-dd",
'br': "dd/MM/yyyy",
'br-FR': "dd/MM/yyyy",
'brx-IN': "M/d/yyyy",
'bs': "d.M.yyyy.",
'bs-Cyrl-BA': "d.M.yyyy",
'bs-Latn-BA': "d.M.yyyy.",
'byn-ER': "dd/MM/yyyy",
'ca': "d/M/yyyy",
'ca-AD': "d/M/yyyy",
'ca-ES': "d/M/yyyy",
'ca-ES-valencia': "d/M/yyyy",
'ca-FR': "d/M/yyyy",
'ca-IT': "d/M/yyyy",
'ce-RU': "yyyy-MM-dd",
'cgg-UG': "dd/MM/yyyy",
'chr-Cher-US': "M/d/yyyy",
'co': "dd/MM/yyyy",
'co-FR': "dd/MM/yyyy",
'cs-CZ': "dd.MM.yyyy",
'cu': "yyyy.MM.dd",
'cu-RU': "yyyy.MM.dd",
'cy': "dd/MM/yyyy",
'cy-GB': "dd/MM/yyyy",
'da-DK': "dd-MM-yyyy",
'da-GL': "dd/MM/yyyy",
'dav-KE': "dd/MM/yyyy",
'de': "dd.MM.yyyy",
'de-AT': "dd.MM.yyyy",
'de-BE': "dd.MM.yyyy",
'de-CH': "dd.MM.yyyy",
'de-DE': "dd.MM.yyyy",
'de-IT': "dd.MM.yyyy",
'de-LI': "dd.MM.yyyy",
'de-LU': "dd.MM.yyyy",
'dje-NE': "d/M/yyyy",
'dsb-DE': "d. M. yyyy",
'dua-CM': "d/M/yyyy",
'dv-MV': "dd/MM/yy",
'dyo-SN': "d/M/yyyy",
'dz': "yyyy-MM-dd",
'dz-BT': "yyyy-MM-dd",
'ebu-KE': "dd/MM/yyyy",
'ee': "M/d/yyyy",
'ee-GH': "M/d/yyyy",
'ee-TG': "M/d/yyyy",
'el-CY': "d/M/yyyy",
'el-GR': "d/M/yyyy",
'en-001': "dd/MM/yyyy",
'en-029': "dd/MM/yyyy",
'en-150': "dd/MM/yyyy",
'en-AG': "dd/MM/yyyy",
'en-AI': "dd/MM/yyyy",
'en-AS': "M/d/yyyy",
'en-AT': "dd/MM/yyyy",
'en-AU': "d/MM/yyyy",
'en-BB': "dd/MM/yyyy",
'en-BE': "dd/MM/yyyy",
'en-BI': "M/d/yyyy",
'en-BM': "dd/MM/yyyy",
'en-BS': "dd/MM/yyyy",
'en-BW': "dd/MM/yyyy",
'en-BZ': "dd/MM/yyyy",
'en-CA': "yyyy-MM-dd",
'en-CC': "dd/MM/yyyy",
'en-CH': "dd/MM/yyyy",
'en-CK': "dd/MM/yyyy",
'en-CM': "dd/MM/yyyy",
'en-CX': "dd/MM/yyyy",
'en-CY': "dd/MM/yyyy",
'en-DE': "dd/MM/yyyy",
'en-DK': "dd/MM/yyyy",
'en-DM': "dd/MM/yyyy",
'en-ER': "dd/MM/yyyy",
'en-FI': "dd/MM/yyyy",
'en-FJ': "dd/MM/yyyy",
'en-FK': "dd/MM/yyyy",
'en-FM': "dd/MM/yyyy",
'en-GB': "dd/MM/yyyy",
'en-GD': "dd/MM/yyyy",
'en-GG': "dd/MM/yyyy",
'en-GH': "dd/MM/yyyy",
'en-GI': "dd/MM/yyyy",
'en-GM': "dd/MM/yyyy",
'en-GU': "M/d/yyyy",
'en-GY': "dd/MM/yyyy",
'en-HK': "d/M/yyyy",
'en-ID': "dd/MM/yyyy",
'en-IE': "dd/MM/yyyy",
'en-IL': "dd/MM/yyyy",
'en-IM': "dd/MM/yyyy",
'en-IN': "dd-MM-yyyy",
'en-IO': "dd/MM/yyyy",
'en-JE': "dd/MM/yyyy",
'en-JM': "d/M/yyyy",
'en-KE': "dd/MM/yyyy",
'en-KI': "dd/MM/yyyy",
'en-KN': "dd/MM/yyyy",
'en-KY': "dd/MM/yyyy",
'en-LC': "dd/MM/yyyy",
'en-LR': "dd/MM/yyyy",
'en-LS': "dd/MM/yyyy",
'en-MG': "dd/MM/yyyy",
'en-MH': "M/d/yyyy",
'en-MO': "dd/MM/yyyy",
'en-MP': "M/d/yyyy",
'en-MS': "dd/MM/yyyy",
'en-MT': "dd/MM/yyyy",
'en-MU': "dd/MM/yyyy",
'en-MW': "dd/MM/yyyy",
'en-MY': "d/M/yyyy",
'en-NA': "dd/MM/yyyy",
'en-NF': "dd/MM/yyyy",
'en-NG': "dd/MM/yyyy",
'en-NL': "dd/MM/yyyy",
'en-NR': "dd/MM/yyyy",
'en-NU': "dd/MM/yyyy",
'en-NZ': "d/MM/yyyy",
'en-PG': "dd/MM/yyyy",
'en-PH': "dd/MM/yyyy",
'en-PK': "dd/MM/yyyy",
'en-PN': "dd/MM/yyyy",
'en-PR': "M/d/yyyy",
'en-PW': "dd/MM/yyyy",
'en-RW': "dd/MM/yyyy",
'en-SB': "dd/MM/yyyy",
'en-SC': "dd/MM/yyyy",
'en-SD': "dd/MM/yyyy",
'en-SE': "yyyy-MM-dd",
'en-SG': "d/M/yyyy",
'en-SH': "dd/MM/yyyy",
'en-SI': "dd/MM/yyyy",
'en-SL': "dd/MM/yyyy",
'en-SS': "dd/MM/yyyy",
'en-SX': "dd/MM/yyyy",
'en-SZ': "dd/MM/yyyy",
'en-TC': "dd/MM/yyyy",
'en-TK': "dd/MM/yyyy",
'en-TO': "dd/MM/yyyy",
'en-TT': "dd/MM/yyyy",
'en-TV': "dd/MM/yyyy",
'en-TZ': "dd/MM/yyyy",
'en-UG': "dd/MM/yyyy",
'en-UM': "M/d/yyyy",
'en-US': "M/d/yyyy",
'en-VC': "dd/MM/yyyy",
'en-VG': "dd/MM/yyyy",
'en-VI': "M/d/yyyy",
'en-VU': "dd/MM/yyyy",
'en-WS': "dd/MM/yyyy",
'en-ZA': "yyyy/MM/dd",
'en-ZM': "dd/MM/yyyy",
'en-ZW': "d/M/yyyy",
'eo-001': "yyyy-MM-dd",
'es': "dd/MM/yyyy",
'es-419': "d/M/yyyy",
'es-AR': "d/M/yyyy",
'es-BO': "d/M/yyyy",
'es-BR': "d/M/yyyy",
'es-BZ': "d/M/yyyy",
'es-CL': "dd-MM-yyyy",
'es-CO': "d/MM/yyyy",
'es-CR': "d/M/yyyy",
'es-CU': "d/M/yyyy",
'es-DO': "d/M/yyyy",
'es-EC': "d/M/yyyy",
'es-ES': "dd/MM/yyyy",
'es-GQ': "d/M/yyyy",
'es-GT': "d/MM/yyyy",
'es-HN': "d/M/yyyy",
'es-MX': "dd/MM/yyyy",
'es-NI': "d/M/yyyy",
'es-PA': "MM/dd/yyyy",
'es-PE': "d/MM/yyyy",
'es-PH': "d/M/yyyy",
'es-PR': "MM/dd/yyyy",
'es-PY': "d/M/yyyy",
'es-SV': "d/M/yyyy",
'es-US': "M/d/yyyy",
'es-UY': "d/M/yyyy",
'es-VE': "d/M/yyyy",
'et': "dd.MM.yyyy",
'et-EE': "dd.MM.yyyy",
'eu-ES': "yyyy/M/d",
'ewo-CM': "d/M/yyyy",
'fa-IR': "dd/MM/yyyy",
'ff-CM': "d/M/yyyy",
'ff-GN': "d/M/yyyy",
'ff-Latn-SN': "dd/MM/yyyy",
'ff-MR': "d/M/yyyy",
'ff-NG': "d/M/yyyy",
'fi': "d.M.yyyy",
'fi-FI': "d.M.yyyy",
'fil-PH': "M/d/yyyy",
'fo': "dd.MM.yyyy",
'fo-DK': "dd.MM.yyyy",
'fo-FO': "dd.MM.yyyy",
'fr': "dd/MM/yyyy",
'fr-029': "dd/MM/yyyy",
'fr-BE': "dd-MM-yy",
'fr-BF': "dd/MM/yyyy",
'fr-BI': "dd/MM/yyyy",
'fr-BJ': "dd/MM/yyyy",
'fr-BL': "dd/MM/yyyy",
'fr-CA': "yyyy-MM-dd",
'fr-CD': "dd/MM/yyyy",
'fr-CF': "dd/MM/yyyy",
'fr-CG': "dd/MM/yyyy",
'fr-CH': "dd.MM.yyyy",
'fr-CI': "dd/MM/yyyy",
'fr-CM': "dd/MM/yyyy",
'fr-DJ': "dd/MM/yyyy",
'fr-DZ': "dd/MM/yyyy",
'fr-FR': "dd/MM/yyyy",
'fr-GA': "dd/MM/yyyy",
'fr-GF': "dd/MM/yyyy",
'fr-GN': "dd/MM/yyyy",
'fr-GP': "dd/MM/yyyy",
'fr-GQ': "dd/MM/yyyy",
'fr-HT': "dd/MM/yyyy",
'fr-KM': "dd/MM/yyyy",
'fr-LU': "dd/MM/yyyy",
'fr-MA': "dd/MM/yyyy",
'fr-MC': "dd/MM/yyyy",
'fr-MF': "dd/MM/yyyy",
'fr-MG': "dd/MM/yyyy",
'fr-ML': "dd/MM/yyyy",
'fr-MQ': "dd/MM/yyyy",
'fr-MR': "dd/MM/yyyy",
'fr-MU': "dd/MM/yyyy",
'fr-NC': "dd/MM/yyyy",
'fr-NE': "dd/MM/yyyy",
'fr-PF': "dd/MM/yyyy",
'fr-PM': "dd/MM/yyyy",
'fr-RE': "dd/MM/yyyy",
'fr-RW': "dd/MM/yyyy",
'fr-SC': "dd/MM/yyyy",
'fr-SN': "dd/MM/yyyy",
'fr-SY': "dd/MM/yyyy",
'fr-TD': "dd/MM/yyyy",
'fr-TG': "dd/MM/yyyy",
'fr-TN': "dd/MM/yyyy",
'fr-VU': "dd/MM/yyyy",
'fr-WF': "dd/MM/yyyy",
'fr-YT': "dd/MM/yyyy",
'fur-IT': "dd/MM/yyyy",
'fy-NL': "dd-MM-yyyy",
'ga': "dd/MM/yyyy",
'ga-IE': "dd/MM/yyyy",
'gd': "dd/MM/yyyy",
'gd-GB': "dd/MM/yyyy",
'gl': "dd/MM/yyyy",
'gl-ES': "dd/MM/yyyy",
'gn': "dd/MM/yyyy",
'gn-PY': "dd/MM/yyyy",
'gsw-CH': "dd.MM.yyyy",
'gsw-FR': "dd/MM/yyyy",
'gsw-LI': "dd.MM.yyyy",
'gu': "dd-MM-yy",
'gu-IN': "dd-MM-yy",
'guz-KE': "dd/MM/yyyy",
'gv-IM': "dd/MM/yyyy",
'ha-Latn-GH': "d/M/yyyy",
'ha-Latn-NE': "d/M/yyyy",
'ha-Latn-NG': "d/M/yyyy",
'haw-US': "d/M/yyyy",
'he-IL': "dd/MM/yyyy",
'hi-IN': "dd-MM-yyyy",
'hr': "d.M.yyyy.",
'hr-BA': "d. M. yyyy.",
'hr-HR': "d.M.yyyy.",
'hsb-DE': "d.M.yyyy",
'hu': "yyyy. MM. dd.",
'hu-HU': "yyyy. MM. dd.",
'hy-AM': "dd.MM.yyyy",
'ia-001': "yyyy/MM/dd",
'ia-FR': "yyyy/MM/dd",
'ibb-NG': "d/M/yyyy",
'id': "dd/MM/yyyy",
'id-ID': "dd/MM/yyyy",
'ig-NG': "dd/MM/yyyy",
'ii-CN': "yyyy/M/d",
'is': "d.M.yyyy",
'is-IS': "d.M.yyyy",
'it': "dd/MM/yyyy",
'it-CH': "dd.MM.yyyy",
'it-IT': "dd/MM/yyyy",
'it-SM': "dd/MM/yyyy",
'it-VA': "dd/MM/yyyy",
'iu-Cans-CA': "d/M/yyyy",
'iu-Latn-CA': "d/MM/yyyy",
'ja-JP': "yyyy/MM/dd",
'jgo-CM': "yyyy-MM-dd",
'jmc-TZ': "dd/MM/yyyy",
'jv-Java-ID': "dd/MM/yyyy",
'jv-Latn-ID': "dd/MM/yyyy",
'ka-GE': "dd.MM.yyyy",
'kab-DZ': "d/M/yyyy",
'kam-KE': "dd/MM/yyyy",
'kde-TZ': "dd/MM/yyyy",
'kea-CV': "d/M/yyyy",
'khq-ML': "d/M/yyyy",
'ki': "dd/MM/yyyy",
'ki-KE': "dd/MM/yyyy",
'kk-KZ': "dd.MM.yyyy",
'kkj-CM': "dd/MM yyyy",
'kl-GL': "dd-MM-yyyy",
'kln-KE': "dd/MM/yyyy",
'km': "dd/MM/yy",
'km-KH': "dd/MM/yy",
'kn': "dd-MM-yy",
'kn-IN': "dd-MM-yy",
'ko-KP': "yyyy. M. d.",
'ko-KR': "yyyy-MM-dd",
'kok-IN': "dd-MM-yyyy",
'kr': "d/M/yyyy",
'kr-NG': "d/M/yyyy",
'ks-Arab-IN': "M/d/yyyy",
'ks-Deva-IN': "dd-MM-yyyy",
'ksb-TZ': "dd/MM/yyyy",
'ksf-CM': "d/M/yyyy",
'ksh-DE': "d. M. yyyy",
'ku-Arab-IQ': "yyyy/MM/dd",
'ku-Arab-IR': "dd/MM/yyyy",
'kw': "dd/MM/yyyy",
'kw-GB': "dd/MM/yyyy",
'ky': "d-MMM yy",
'ky-KG': "d-MMM yy",
'la': "dd/MM/yyyy",
'la-001': "dd/MM/yyyy",
'lag-TZ': "dd/MM/yyyy",
'lb': "dd.MM.yy",
'lb-LU': "dd.MM.yy",
'lg-UG': "dd/MM/yyyy",
'lkt-US': "M/d/yyyy",
'ln-AO': "d/M/yyyy",
'ln-CD': "d/M/yyyy",
'ln-CF': "d/M/yyyy",
'ln-CG': "d/M/yyyy",
'lo-LA': "d/M/yyyy",
'lrc-IQ': "yyyy-MM-dd",
'lrc-IR': "dd/MM/yyyy",
'lt': "yyyy-MM-dd",
'lt-LT': "yyyy-MM-dd",
'lu': "d/M/yyyy",
'lu-CD': "d/M/yyyy",
'luo-KE': "dd/MM/yyyy",
'luy-KE': "dd/MM/yyyy",
'lv': "dd.MM.yyyy",
'lv-LV': "dd.MM.yyyy",
'mas-KE': "dd/MM/yyyy",
'mas-TZ': "dd/MM/yyyy",
'mer-KE': "dd/MM/yyyy",
'mfe-MU': "d/M/yyyy",
'mg': "yyyy-MM-dd",
'mg-MG': "yyyy-MM-dd",
'mgh-MZ': "dd/MM/yyyy",
'mgo-CM': "yyyy-MM-dd",
'mi-NZ': "dd/MM/yyyy",
'mk': "dd.M.yyyy",
'mk-MK': "dd.M.yyyy",
'ml': "d/M/yyyy",
'ml-IN': "d/M/yyyy",
'mn': "yyyy.MM.dd",
'mn-MN': "yyyy.MM.dd",
'mn-Mong-CN': "yyyy/M/d",
'mn-Mong-MN': "yyyy/M/d",
'mni-IN': "dd/MM/yyyy",
'moh-CA': "M/d/yyyy",
'mr': "dd-MM-yyyy",
'mr-IN': "dd-MM-yyyy",
'ms': "d/MM/yyyy",
'ms-BN': "d/MM/yyyy",
'ms-MY': "d/MM/yyyy",
'ms-SG': "d/MM/yyyy",
'mt': "dd/MM/yyyy",
'mt-MT': "dd/MM/yyyy",
'mua-CM': "d/M/yyyy",
'my': "dd-MM-yyyy",
'my-MM': "dd-MM-yyyy",
'mzn-IR': "dd/MM/yyyy",
'naq-NA': "dd/MM/yyyy",
'nb-NO': "dd.MM.yyyy",
'nb-SJ': "dd.MM.yyyy",
'nd-ZW': "dd/MM/yyyy",
'nds-DE': "d.MM.yyyy",
'nds-NL': "d.MM.yyyy",
'ne': "M/d/yyyy",
'ne-IN': "yyyy/M/d",
'ne-NP': "M/d/yyyy",
'nl': "d-M-yyyy",
'nl-AW': "dd-MM-yyyy",
'nl-BE': "d/MM/yyyy",
'nl-BQ': "dd-MM-yyyy",
'nl-CW': "dd-MM-yyyy",
'nl-NL': "d-M-yyyy",
'nl-SR': "dd-MM-yyyy",
'nl-SX': "dd-MM-yyyy",
'nmg-CM': "d/M/yyyy",
'nn-NO': "dd.MM.yyyy",
'nnh-CM': "dd/MM/yyyy",
'no': "dd.MM.yyyy",
'nqo-GN': "dd/MM/yyyy",
'nr': "yyyy-MM-dd",
'nr-ZA': "yyyy-MM-dd",
'nso-ZA': "yyyy-MM-dd",
'nus-SS': "d/MM/yyyy",
'nyn-UG': "dd/MM/yyyy",
'oc-FR': "dd/MM/yyyy",
'om': "dd/MM/yyyy",
'om-ET': "dd/MM/yyyy",
'om-KE': "dd/MM/yyyy",
'or-IN': "dd-MM-yy",
'os-GE': "dd.MM.yyyy",
'os-RU': "dd.MM.yyyy",
'pa': "dd-MM-yy",
'pa-Arab-PK': "dd-MM-yy",
'pa-IN': "dd-MM-yy",
'pap-029': "d-M-yyyy",
'pl': "dd.MM.yyyy",
'pl-PL': "dd.MM.yyyy",
'prg-001': "dd.MM.yyyy",
'prs-AF': "yyyy/M/d",
'ps': "yyyy/M/d",
'ps-AF': "yyyy/M/d",
'pt': "dd/MM/yyyy",
'pt-AO': "dd/MM/yyyy",
'pt-BR': "dd/MM/yyyy",
'pt-CH': "dd/MM/yyyy",
'pt-CV': "dd/MM/yyyy",
'pt-GQ': "dd/MM/yyyy",
'pt-GW': "dd/MM/yyyy",
'pt-LU': "dd/MM/yyyy",
'pt-MO': "dd/MM/yyyy",
'pt-MZ': "dd/MM/yyyy",
'pt-PT': "dd/MM/yyyy",
'pt-ST': "dd/MM/yyyy",
'pt-TL': "dd/MM/yyyy",
'quc-Latn-GT': "dd/MM/yyyy",
'quz-BO': "dd/MM/yyyy",
'quz-EC': "dd/MM/yyyy",
'quz-PE': "dd/MM/yyyy",
'rm-CH': "dd-MM-yyyy",
'rn-BI': "d/M/yyyy",
'ro': "dd.MM.yyyy",
'ro-MD': "dd.MM.yyyy",
'ro-RO': "dd.MM.yyyy",
'rof-TZ': "dd/MM/yyyy",
'ru': "dd.MM.yyyy",
'ru-BY': "dd.MM.yyyy",
'ru-KG': "dd.MM.yyyy",
'ru-KZ': "dd.MM.yyyy",
'ru-MD': "dd.MM.yyyy",
'ru-RU': "dd.MM.yyyy",
'ru-UA': "dd.MM.yyyy",
'rw': "yyyy-MM-dd",
'rw-RW': "yyyy-MM-dd",
'rwk-TZ': "dd/MM/yyyy",
'sa': "dd-MM-yyyy",
'sa-IN': "dd-MM-yyyy",
'sah-RU': "dd.MM.yyyy",
'saq-KE': "dd/MM/yyyy",
'sbp-TZ': "dd/MM/yyyy",
'sd': "dd/MM/yyyy",
'sd-Arab-PK': "dd/MM/yyyy",
'sd-Deva-IN': "dd/MM/yyyy",
'se': "yyyy-MM-dd",
'se-FI': "d.M.yyyy",
'se-NO': "yyyy-MM-dd",
'se-SE': "yyyy-MM-dd",
'seh-MZ': "d/M/yyyy",
'ses-ML': "d/M/yyyy",
'sg': "d/M/yyyy",
'sg-CF': "d/M/yyyy",
'shi-Latn-MA': "d/M/yyyy",
'shi-Tfng-MA': "d/M/yyyy",
'si': "yyyy-MM-dd",
'si-LK': "yyyy-MM-dd",
'sk': "d. M. yyyy",
'sk-SK': "d. M. yyyy",
'sl': "d. MM. yyyy",
'sl-SI': "d. MM. yyyy",
'sma-NO': "dd.MM.yyyy",
'sma-SE': "yyyy-MM-dd",
'smj-NO': "dd.MM.yyyy",
'smj-SE': "yyyy-MM-dd",
'smn-FI': "d.M.yyyy",
'sms-FI': "d.M.yyyy",
'sn': "yyyy-MM-dd",
'sn-Latn-ZW': "yyyy-MM-dd",
'so': "dd/MM/yyyy",
'so-DJ': "dd/MM/yyyy",
'so-ET': "dd/MM/yyyy",
'so-KE': "dd/MM/yyyy",
'so-SO': "dd/MM/yyyy",
'sq-AL': "d.M.yyyy",
'sq-MK': "d.M.yyyy",
'sq-XK': "d.M.yyyy",
'sr': "d.M.yyyy.",
'sr-Cyrl-BA': "d.M.yyyy.",
'sr-Cyrl-ME': "d.M.yyyy.",
'sr-Cyrl-RS': "dd.MM.yyyy.",
'sr-Cyrl-XK': "d.M.yyyy.",
'sr-Latn-BA': "d.M.yyyy.",
'sr-Latn-ME': "d.M.yyyy.",
'sr-Latn-RS': "d.M.yyyy.",
'sr-Latn-XK': "d.M.yyyy.",
'ss': "yyyy-MM-dd",
'ss-SZ': "yyyy-MM-dd",
'ss-ZA': "yyyy-MM-dd",
'ssy-ER': "dd/MM/yyyy",
'st': "yyyy-MM-dd",
'st-LS': "yyyy-MM-dd",
'st-ZA': "yyyy-MM-dd",
'sv': "yyyy-MM-dd",
'sv-AX': "yyyy-MM-dd",
'sv-FI': "dd-MM-yyyy",
'sv-SE': "yyyy-MM-dd",
'sw-CD': "dd/MM/yyyy",
'sw-KE': "dd/MM/yyyy",
'sw-TZ': "dd/MM/yyyy",
'sw-UG': "dd/MM/yyyy",
'syr-SY': "dd/MM/yyyy",
'ta-IN': "dd-MM-yyyy",
'ta-LK': "d/M/yyyy",
'ta-MY': "d/M/yyyy",
'ta-SG': "d/M/yyyy",
'te-IN': "dd-MM-yy",
'teo-KE': "dd/MM/yyyy",
'teo-UG': "dd/MM/yyyy",
'tg': "dd.MM.yyyy",
'tg-Cyrl-TJ': "dd.MM.yyyy",
'th': "d/M/yyyy",
'th-TH': "d/M/yyyy",
'ti-ER': "dd/MM/yyyy",
'ti-ET': "dd/MM/yyyy",
'tig-ER': "dd/MM/yyyy",
'tk': "dd.MM.yy 'ý.'",
'tk-TM': "dd.MM.yy 'ý.'",
'tn': "yyyy-MM-dd",
'tn-BW': "yyyy-MM-dd",
'tn-ZA': "yyyy-MM-dd",
'to': "d/M/yyyy",
'to-TO': "d/M/yyyy",
'tr': "d.MM.yyyy",
'tr-CY': "d.MM.yyyy",
'tr-TR': "d.MM.yyyy",
'ts-ZA': "yyyy-MM-dd",
'tt': "dd.MM.yyyy",
'tt-RU': "dd.MM.yyyy",
'twq-NE': "d/M/yyyy",
'tzm-Arab-MA': "d/M/yyyy",
'tzm-Latn-DZ': "dd-MM-yyyy",
'tzm-Latn-MA': "dd/MM/yyyy",
'tzm-Tfng-MA': "dd-MM-yyyy",
'ug': "yyyy-M-d",
'ug-CN': "yyyy-M-d",
'uk-UA': "dd.MM.yyyy",
'ur-IN': "d/M/yy",
'ur-PK': "dd/MM/yyyy",
'uz': "dd/MM/yyyy",
'uz-Arab-AF': "dd/MM yyyy",
'uz-Cyrl-UZ': "dd/MM/yyyy",
'uz-Latn-UZ': "dd/MM/yyyy",
'vai-Latn-LR': "dd/MM/yyyy",
'vai-Vaii-LR': "dd/MM/yyyy",
've': "yyyy-MM-dd",
've-ZA': "yyyy-MM-dd",
'vi': "dd/MM/yyyy",
'vi-VN': "dd/MM/yyyy",
'vo-001': "yyyy-MM-dd",
'vun-TZ': "dd/MM/yyyy",
'wae-CH': "yyyy-MM-dd",
'wal-ET': "dd/MM/yyyy",
'wo-SN': "dd/MM/yyyy",
'xh-ZA': "yyyy-MM-dd",
'xog-UG': "dd/MM/yyyy",
'yav-CM': "d/M/yyyy",
'yi-001': "dd/MM/yyyy",
'yo-BJ': "dd/MM/yyyy",
'yo-NG': "dd/MM/yyyy",
'zgh-Tfng-MA': "d/M/yyyy",
'zh-CN': "yyyy/M/d",
'zh-Hans-HK': "d/M/yyyy",
'zh-Hans-MO': "d/M/yyyy",
'zh-HK': "d/M/yyyy",
'zh-MO': "d/M/yyyy",
'zh-SG': "d/M/yyyy",
'zh-TW': "yyyy/M/d",
'zu-ZA': "M/d/yyyy",
};

How do I deserialize a complex JSON object in C# .NET?

I am using like this in my code and it's working fine

below is a piece of code which you need to write

using System.Web.Script.Serialization;

JavaScriptSerializer oJS = new JavaScriptSerializer();
RootObject oRootObject = new RootObject();
oRootObject = oJS.Deserialize<RootObject>(Your JSon String);

Git: How to remove file from index without deleting files from any repository

The above solutions work fine for most cases. However, if you also need to remove all traces of that file (ie sensitive data such as passwords), you will also want to remove it from your entire commit history, as the file could still be retrieved from there.

Here is a solution that removes all traces of the file from your entire commit history, as though it never existed, yet keeps the file in place on your system.

https://help.github.com/articles/remove-sensitive-data/

You can actually skip to step 3 if you are in your local git repository, and don't need to perform a dry run. In my case, I only needed steps 3 and 6, as I had already created my .gitignore file, and was in the repository I wanted to work on.

To see your changes, you may need to go to the GitHub root of your repository and refresh the page. Then navigate through the links to get to an old commit that once had the file, to see that it has now been removed. For me, simply refreshing the old commit page did not show the change.

It looked intimidating at first, but really, was easy and worked like a charm ! :-)

Multiple Image Upload PHP form with one input

$total = count($_FILES['txt_gallery']['name']);
            $filename_arr = [];
            $filename_arr1 = [];
            for( $i=0 ; $i < $total ; $i++ ) {
              $tmpFilePath = $_FILES['txt_gallery']['tmp_name'][$i];
              if ($tmpFilePath != ""){
                $newFilePath = "../uploaded/" .date('Ymdhis').$i.$_FILES['txt_gallery']['name'][$i];
                $newFilePath1 = date('Ymdhis').$i.$_FILES['txt_gallery']['name'][$i];
                if(move_uploaded_file($tmpFilePath, $newFilePath)) {
                  $filename_arr[] = $newFilePath;
                  $filename_arr1[] = $newFilePath1;

                }
              }
            }
            $file_names = implode(',', $filename_arr1);
            var_dump($file_names); exit;

How can I exclude one word with grep?

grep provides '-v' or '--invert-match' option to select non-matching lines.

e.g.

grep -v 'unwanted_pattern' file_name

This will output all the lines from file file_name, which does not have 'unwanted_pattern'.

If you are searching the pattern in multiple files inside a folder, you can use the recursive search option as follows

grep -r 'wanted_pattern' * | grep -v 'unwanted_pattern'

Here grep will try to list all the occurrences of 'wanted_pattern' in all the files from within currently directory and pass it to second grep to filter out the 'unwanted_pattern'. '|' - pipe will tell shell to connect the standard output of left program (grep -r 'wanted_pattern' *) to standard input of right program (grep -v 'unwanted_pattern').

How do I stretch an image to fit the whole background (100% height x 100% width) in Flutter?

This worked for me

class _SplashScreenState extends State<SplashScreen> {
  @override
  Widget build(BuildContext context) {
    return Container(
      child: FittedBox(
        child: Image.asset("images/my_image.png"),
        fit: BoxFit.fill,
      ),);
  }
}

How to convert JSON object to an Typescript array?

You have a JSON object that contains an Array. You need to access the array results. Change your code to:

this.data = res.json().results

How do you post to an iframe?

If you want to change inputs in an iframe then submit the form from that iframe, do this

...
var el = document.getElementById('targetFrame');

var doc, frame_win = getIframeWindow(el); // getIframeWindow is defined below

if (frame_win) {
  doc = (window.contentDocument || window.document);
}

if (doc) {
  doc.forms[0].someInputName.value = someValue;
  ...
  doc.forms[0].submit();
}
...

Normally, you can only do this if the page in the iframe is from the same origin, but you can start Chrome in a debug mode to disregard the same origin policy and test this on any page.

function getIframeWindow(iframe_object) {
  var doc;

  if (iframe_object.contentWindow) {
    return iframe_object.contentWindow;
  }

  if (iframe_object.window) {
    return iframe_object.window;
  } 

  if (!doc && iframe_object.contentDocument) {
    doc = iframe_object.contentDocument;
  } 

  if (!doc && iframe_object.document) {
    doc = iframe_object.document;
  }

  if (doc && doc.defaultView) {
   return doc.defaultView;
  }

  if (doc && doc.parentWindow) {
    return doc.parentWindow;
  }

  return undefined;
}

Finding Variable Type in JavaScript

For builtin JS types you can use:

function getTypeName(val) {
    return {}.toString.call(val).slice(8, -1);
}

Here we use 'toString' method from 'Object' class which works different than the same method of another types.

Examples:

// Primitives
getTypeName(42);        // "Number"
getTypeName("hi");      // "String"
getTypeName(true);      // "Boolean"
getTypeName(Symbol('s'))// "Symbol"
getTypeName(null);      // "Null"
getTypeName(undefined); // "Undefined"

// Non-primitives
getTypeName({});            // "Object"
getTypeName([]);            // "Array"
getTypeName(new Date);      // "Date"
getTypeName(function() {}); // "Function"
getTypeName(/a/);           // "RegExp"
getTypeName(new Error);     // "Error"

If you need a class name you can use:

instance.constructor.name

Examples:

({}).constructor.name       // "Object"
[].constructor.name         // "Array"
(new Date).constructor.name // "Date"

function MyClass() {}
let my = new MyClass();
my.constructor.name         // "MyClass"

But this feature was added in ES2015.

Make 2 functions run at the same time

The thread module does work simultaneously unlike multiprocess, but the timing is a bit off. The code below prints a "1" and a "2". These are called by different functions respectively. I did notice that when printed to the console, they would have slightly different timings.

from threading import Thread

def one():
    while(1 == num):
        print("1")
        time.sleep(2)
    
def two():
    while(1 == num):
        print("2")
        time.sleep(2)


p1 = Thread(target = one)
p2 = Thread(target = two)

p1.start()
p2.start()

Output: (Note the space is for the wait in between printing)

1
2

2
1

12
   
21

12
   
1
2

Not sure if there is a way to correct this, or if it matters at all. Just something I noticed.

Pass arguments into C program from command line

Consider using getopt_long(). It allows both short and long options in any combination.

#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>

/* Flag set by `--verbose'. */
static int verbose_flag;

int
main (int argc, char *argv[])
{
  while (1)
    {
      static struct option long_options[] =
    {
      /* This option set a flag. */
      {"verbose", no_argument,       &verbose_flag, 1},
      /* These options don't set a flag.
         We distinguish them by their indices. */
      {"blip",    no_argument,       0, 'b'},
      {"slip",    no_argument,       0, 's'},
      {0,         0,                 0,  0}
    };
      /* getopt_long stores the option index here. */
      int option_index = 0;

      int c = getopt_long (argc, argv, "bs",
               long_options, &option_index);

      /* Detect the end of the options. */
      if (c == -1)
    break;

      switch (c)
    {
    case 0:
      /* If this option set a flag, do nothing else now. */
      if (long_options[option_index].flag != 0)
        break;
      printf ("option %s", long_options[option_index].name);
      if (optarg)
        printf (" with arg %s", optarg);
      printf ("\n");
      break;
    case 'b':
      puts ("option -b\n");
      break;
    case 's':
      puts ("option -s\n");
      break;
    case '?':
      /* getopt_long already printed an error message. */
      break;

    default:
      abort ();
    }
    }

  if (verbose_flag)
    puts ("verbose flag is set");

  /* Print any remaining command line arguments (not options). */
  if (optind < argc)
    {
      printf ("non-option ARGV-elements: ");
      while (optind < argc)
    printf ("%s ", argv[optind++]);
      putchar ('\n');
    }

  return 0;
}

Related:

How do I check if the Java JDK is installed on Mac?

Make sure you correctly define the project's JDK and restart IntelliJ (full restart).

How to split an integer into an array of digits?

Splitting a single number to it's digits (as answered by all):

>>> [int(i) for i in str(12345)]
[1, 2, 3, 4, 5]

But, to get digits from a list of numbers:

>>> [int(d) for d in ''.join(str(x) for x in [12, 34, 5])]
[1, 2, 3, 4, 5]

So like to know, if we can do the above, more efficiently.

Lollipop : draw behind statusBar with its color set to transparent

Similar to some of the solutions posted, but in my case I did the status bar transparent and fix the position of the action bar with some negative margin

if (Build.VERSION.SDK_INT >= 21) {
    getWindow().setStatusBarColor(Color.TRANSPARENT);
    FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) toolbar.getLayoutParams();
    lp.setMargins(0, -getStatusBarHeight(), 0, 0);
}

And I used in the toolbar and the root view

android:fitsSystemWindows="true"

CSS3 Fade Effect

You can't transition between two background images, as there's no way for the browser to know what you want to interpolate. As you've discovered, you can transition the background position. If you want the image to fade in on mouse over, I think the best way to do it with CSS transitions is to put the image on a containing element and then animate the background colour to transparent on the link itself:

span {
    background: url(button.png) no-repeat 0 0;
}
a {
    width: 32px;
    height: 32px;
    text-align: left;
    background: rgb(255,255,255);

    -webkit-transition: background 300ms ease-in 200ms; /* property duration timing-function delay */
    -moz-transition: background 300ms ease-in 200ms;
    -o-transition: background 300ms ease-in 200ms;
    transition: background 300ms ease-in 200ms;
    }
a:hover {
    background: rgba(255,255,255,0);
}

Put a Delay in Javascript

Actually only setTimeout is fine for that job and normally you cannot set exact delays with non determined methods as busy loops.

Display image as grayscale using matplotlib

Try to use a grayscale colormap?

E.g. something like

imshow(..., cmap=pyplot.cm.binary)

For a list of colormaps, see http://scipy-cookbook.readthedocs.org/items/Matplotlib_Show_colormaps.html

SQL Server check case-sensitivity?

You're interested in the collation. You could build something based on this snippet:

SELECT DATABASEPROPERTYEX('master', 'Collation');

Update
Based on your edit — If @test and @TEST can ever refer to two different variables, it's not SQL Server. If you see problems where the same variable is not equal to itself, check if that variable is NULL, because NULL = NULL returns `false.

Spring MVC - How to return simple String as JSON in Rest Controller

This issue has driven me mad: Spring is such a potent tool and yet, such a simple thing as writing an output String as JSON seems impossible without ugly hacks.

My solution (in Kotlin) that I find the least intrusive and most transparent is to use a controller advice and check whether the request went to a particular set of endpoints (REST API typically since we most often want to return ALL answers from here as JSON and not make specializations in the frontend based on whether the returned data is a plain string ("Don't do JSON deserialization!") or something else ("Do JSON deserialization!")). The positive aspect of this is that the controller remains the same and without hacks.

The supports method makes sure that all requests that were handled by the StringHttpMessageConverter(e.g. the converter that handles the output of all controllers that return plain strings) are processed and in the beforeBodyWrite method, we control in which cases we want to interrupt and convert the output to JSON (and modify headers accordingly).

@ControllerAdvice
class StringToJsonAdvice(val ob: ObjectMapper) : ResponseBodyAdvice<Any?> {
    
    override fun supports(returnType: MethodParameter, converterType: Class<out HttpMessageConverter<*>>): Boolean =
        converterType === StringHttpMessageConverter::class.java

    override fun beforeBodyWrite(
        body: Any?,
        returnType: MethodParameter,
        selectedContentType: MediaType,
        selectedConverterType: Class<out HttpMessageConverter<*>>,
        request: ServerHttpRequest,
        response: ServerHttpResponse
    ): Any? {
        return if (request.uri.path.contains("api")) {
            response.getHeaders().contentType = MediaType.APPLICATION_JSON
            ob.writeValueAsString(body)
        } else body
    }
}

I hope in the future that we will get a simple annotation in which we can override which HttpMessageConverter should be used for the output.

How do I get into a non-password protected Java keystore or change the password?

which means that cacerts keystore isn't password protected

That's a false assumption. If you read more carefully, you'll find that the listing was provided without verifying the integrity of the keystore because you didn't provide the password. The listing doesn't require a password, but your keystore definitely has a password, as indicated by:

In order to verify its integrity, you must provide your keystore password.

Java's default cacerts password is "changeit", unless you're on a Mac, where it's "changeme" up to a certain point. Apparently as of Mountain Lion (based on comments and another answer here), the password for Mac is now also "changeit", probably because Oracle is now handling distribution for the Mac JVM as well.

Cast a Double Variable to Decimal

You can cast a double to a decimal like this, without needing the M literal suffix:

double dbl = 1.2345D;
decimal dec = (decimal) dbl;

You should use the M when declaring a new literal decimal value:

decimal dec = 123.45M;

(Without the M, 123.45 is treated as a double and will not compile.)

Could not locate Gemfile

I solved similar problem just by backing out of the project directory, then cd back into the project directory and bundle install.

Find which commit is currently checked out in Git

If you want to extract just a simple piece of information, you can get that using git show with the --format=<string> option...and ask it not to give you the diff with --no-patch. This means you can get a printf-style output of whatever you want, which might often be a single field.

For instance, to get just the shortened hash (%h) you could say:

$ git show --format="%h" --no-patch
4b703eb

If you're looking to save that into an environment variable in bash (a likely thing for people to want to do) you can use the $() syntax:

$ GIT_COMMIT="$(git show --format="%h" --no-patch)"

$ echo $GIT_COMMIT
4b703eb

The full list of what you can do is in git show --help. But here's an abbreviated list of properties that might be useful:

  • %H commit hash
  • %h abbreviated commit hash
  • %T tree hash
  • %t abbreviated tree hash
  • %P parent hashes
  • %p abbreviated parent hashes
  • %an author name
  • %ae author email
  • %at author date, UNIX timestamp
  • %aI author date, strict ISO 8601 format
  • %cn committer name
  • %ce committer email
  • %ct committer date, UNIX timestamp
  • %cI committer date, strict ISO 8601 format
  • %s subject
  • %f sanitized subject line, suitable for a filename
  • %gD reflog selector, e.g., refs/stash@{1}
  • %gd shortened reflog selector, e.g., stash@{1}

Why is “while ( !feof (file) )” always wrong?

feof() is not very intuitive. In my very humble opinion, the FILE's end-of-file state should be set to true if any read operation results in the end of file being reached. Instead, you have to manually check if the end of file has been reached after each read operation. For example, something like this will work if reading from a text file using fgetc():

#include <stdio.h>

int main(int argc, char *argv[])
{
  FILE *in = fopen("testfile.txt", "r");

  while(1) {
    char c = fgetc(in);
    if (feof(in)) break;
    printf("%c", c);
  }

  fclose(in);
  return 0;
}

It would be great if something like this would work instead:

#include <stdio.h>

int main(int argc, char *argv[])
{
  FILE *in = fopen("testfile.txt", "r");

  while(!feof(in)) {
    printf("%c", fgetc(in));
  }

  fclose(in);
  return 0;
}

Are static methods inherited in Java?

Static methods in Java are inherited, but can not be overridden. If you declare the same method in a subclass, you hide the superclass method instead of overriding it. Static methods are not polymorphic. At the compile time, the static method will be statically linked.

Example:

public class Writer {
    public static void write() {
        System.out.println("Writing");
    }
}

public class Author extends Writer {
    public static void write() {
        System.out.println("Writing book");
    }
}

public class Programmer extends Writer {

    public static void write() {
        System.out.println("Writing code");
    }

    public static void main(String[] args) {
        Writer w = new Programmer();
        w.write();

        Writer secondWriter = new Author();
        secondWriter.write();

        Writer thirdWriter = null;
        thirdWriter.write();

        Author firstAuthor = new Author();
        firstAuthor.write();
    }
}

You'll get the following:

Writing
Writing
Writing
Writing book

PHP Get URL with Parameter

Here's probably what you are looking for: php-get-url-query-string. You can combine it with other suggested $_SERVER parameters.

Return the most recent record from ElasticSearch index

You can use sort on date field and size=1 parameter. Does it help?

How to call window.alert("message"); from C#?

You can try this:

Hope it works for you..

`private void validateUserEntry()
{
    // Checks the value of the text.
    if(serverName.Text.Length == 0)
    {
    // Initializes the variables to pass to the MessageBox.Show method.
    string message = "You did not enter a server name. Cancel this operation?";
    string caption = "Error Detected in Input";
    MessageBoxButtons buttons = MessageBoxButtons.YesNo;
    DialogResult result;

    // Displays the MessageBox.
    result = MessageBox.Show(message, caption, buttons);
    if (result == System.Windows.Forms.DialogResult.Yes)
    {
     // Closes the parent form.
        this.Close();
    }
    }
}` 

How is attr_accessible used in Rails 4?

If you prefer attr_accessible, you could use it in Rails 4 too. You should install it like gem:

gem 'protected_attributes'

after that you could use attr_accessible in you models like in Rails 3

Also, and i think that is the best way- using form objects for dealing with mass assignment, and saving nested objects, and you can also use protected_attributes gem that way

class NestedForm
   include  ActiveModel::MassAssignmentSecurity
   attr_accessible :name,
                   :telephone, as: :create_params
   def create_objects(params)
      SomeModel.new(sanitized_params(params, :create_params))
   end
end

Remove last character from string. Swift language

complimentary to the above code I wanted to remove the beginning of the string and could not find a reference anywhere. Here is how I did it:

var mac = peripheral.identifier.description
let range = mac.startIndex..<mac.endIndex.advancedBy(-50)
mac.removeRange(range)  // trim 17 characters from the beginning
let txPower = peripheral.advertisements.txPower?.description

This trims 17 characters from the beginning of the string (he total string length is 67 we advance -50 from the end and there you have it.

Populate nested array in mongoose

As others have noted, Mongoose 4 supports this. It is very important to note that you can recurse deeper than one level too, if needed—though it is not noted in the docs:

Project.findOne({name: req.query.name})
    .populate({
        path: 'threads',
        populate: {
            path: 'messages', 
            model: 'Message',
            populate: {
                path: 'user',
                model: 'User'
            }
        }
    })

Check if character is number?

I suggest a simple regex.

If you're looking for just the last character in the string:

/^.*?[0-9]$/.test("blabla,120");  // true
/^.*?[0-9]$/.test("blabla,120a"); // false
/^.*?[0-9]$/.test("120");         // true
/^.*?[0-9]$/.test(120);           // true
/^.*?[0-9]$/.test(undefined);     // false
/^.*?[0-9]$/.test(-1);            // true
/^.*?[0-9]$/.test("-1");          // true
/^.*?[0-9]$/.test(false);         // false
/^.*?[0-9]$/.test(true);          // false

And the regex is even simpler if you are just checking a single char as an input:

var char = "0";
/^[0-9]$/.test(char);             // true

How do I Set Background image in Flutter?

I was able to apply a background below the Scaffold (and even it's AppBar) by putting the Scaffold under a Stack and setting a Container in the first "layer" with the background image set and fit: BoxFit.cover property.

Both the Scaffold and AppBar has to have the backgroundColor set as Color.transparent and the elevation of AppBar has to be 0 (zero).

Voilà! Now you have a nice background below the whole Scaffold and AppBar! :)

import 'package:flutter/material.dart';
import 'package:mynamespace/ui/shared/colors.dart';
import 'package:mynamespace/ui/shared/textstyle.dart';
import 'package:mynamespace/ui/shared/ui_helpers.dart';
import 'package:mynamespace/ui/widgets/custom_text_form_field_widget.dart';

class SignUpView extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Stack( // <-- STACK AS THE SCAFFOLD PARENT
      children: [
        Container(
          decoration: BoxDecoration(
            image: DecorationImage(
              image: AssetImage("assets/images/bg.png"), // <-- BACKGROUND IMAGE
              fit: BoxFit.cover,
            ),
          ),
        ),
        Scaffold(
          backgroundColor: Colors.transparent, // <-- SCAFFOLD WITH TRANSPARENT BG
          appBar: AppBar(
            title: Text('NEW USER'),
            backgroundColor: Colors.transparent, // <-- APPBAR WITH TRANSPARENT BG
            elevation: 0, // <-- ELEVATION ZEROED
          ),
          body: Padding(
            padding: EdgeInsets.all(spaceXS),
            child: Column(
              children: [
                CustomTextFormFieldWidget(labelText: 'Email', hintText: 'Type your Email'),
                UIHelper.verticalSpaceSM,
                SizedBox(
                  width: double.maxFinite,
                  child: RaisedButton(
                    color: regularCyan,
                    child: Text('Finish Registration', style: TextStyle(color: white)),
                    onPressed: () => {},
                  ),
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }
}

Disable validation of HTML5 form elements

If you want to disable client side validation for a form in HTML5 add a novalidate attribute to the form element. Ex:

<form method="post" action="/foo" novalidate>...</form>

See https://www.w3.org/TR/html5/sec-forms.html#element-attrdef-form-novalidate

ORA-00932: inconsistent datatypes: expected - got CLOB

I found that selecting a clob column in CTE caused this explosion. ie

with cte as (
    select
        mytable1.myIntCol,
        mytable2.myClobCol
    from mytable1
    join mytable2 on ...
)
select myIntCol, myClobCol
from cte
where ...

presumably because oracle can't handle a clob in a temporary table.

Because my values were longer than 4K, I couldn't use to_char().
My work around was to select it from the final select, ie

with cte as (
    select
        mytable1.myIntCol
    from mytable1
)
select myIntCol, myClobCol
from cte
join mytable2 on ...
where ...

Too bad if this causes a performance problem.

Using 24 hour time in bootstrap timepicker

It looks like you have to set the option for the format with data-date-*. This example works for me with 24h support.

<div class="form-group">
    <div class="input-group date timepicker"
        data-date-format="HH:mm"
        data-date-useseconds="false"
        data-date-pickDate="false">

        <input type="text" name="" />
        <div class="input-group-addon">
            <i class="fa fa-clock-o"></i>
        </div>
    </div>
</div>

jQuery form validation on button click

$(document).ready(function() {
    $("#form1").validate({
        rules: {
            field1: "required"
        },
        messages: {
            field1: "Please specify your name"
        }
    })
});

<form id="form1" name="form1">
     Field 1: <input id="field1" type="text" class="required">
    <input id="btn" type="submit" value="Validate">
</form>

You are also you using type="button". And I'm not sure why you ought to separate the submit button, place it within the form. It's more proper to do it that way. This should work.

What exactly should be set in PYTHONPATH?

Here is what I learned: PYTHONPATH is a directory to add to the Python import search path "sys.path", which is made up of current dir. CWD, PYTHONPATH, standard and shared library, and customer library. For example:

% python3 -c "import sys;print(sys.path)"
['', 
'/home/username/Documents/DjangoTutorial/mySite', 
'/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', 
'/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages']

where the first path '' denotes the current dir., the 2nd path is via

%export PYTHONPATH=/home/username/Documents/DjangoTutorial/mySite 

which can be added to ~/.bashrc to make it permanent, and the rest are Python standard and dynamic shared library plus third-party library such as django.

As said not to mess with PYTHONHOME, even setting it to '' or 'None' will cause python3 shell to stop working:

% export PYTHONHOME=''
% python3
Fatal Python error: Py_Initialize: Unable to get the locale encoding
ModuleNotFoundError: No module named 'encodings'

Current thread 0x00007f18a44ff740 (most recent call first):
Aborted (core dumped)

Note that if you start a Python script, the CWD will be the script's directory. For example:

username@bud:~/Documents/DjangoTutorial% python3 mySite/manage.py runserver
==== Printing sys.path ====
/home/username/Documents/DjangoTutorial/mySite # CWD is where manage.py resides
/usr/lib/python3.6
/usr/lib/python3.6/lib-dynload
/usr/local/lib/python3.6/dist-packages
/usr/lib/python3/dist-packages

You can also append a path to sys.path at run-time: Suppose you have a file Fibonacci.py in ~/Documents/Python directory:

username@bud:~/Documents/DjangoTutorial% python3 
>>> sys.path.append("/home/username/Documents")
>>> print(sys.path)
['', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', 
'/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages', 
'/home/username/Documents']
>>> from Python import Fibonacci as fibo

or via

% PYTHONPATH=/home/username/Documents:$PYTHONPATH
% python3
>>> print(sys.path)
['', 
'/home/username/Documents', '/home/username/Documents/DjangoTutorial/mySite', 
'/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', 
'/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages']
>>> from Python import Fibonacci as fibo

Is string in array?

Arrays are, in general, a poor data structure to use if you want to ask if a particular object is in the collection or not.

If you'll be running this search frequently, it might be worth it to use a Dictionary<string, something> rather than an array. Lookups in a Dictionary are O(1) (constant-time), while searching through the array is O(N) (takes time proportional to the length of the array).

Even if the array is only 200 items at most, if you do a lot of these searches, the Dictionary will likely be faster.

Set the space between Elements in Row Flutter

Just add "Container(width: 5, color: Colors.transparent)," between elements

new Container(
      alignment: FractionalOffset.center,
      child: new Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: <Widget>[
          new FlatButton(
            child: new Text('Don\'t have an account?', style: new TextStyle(color: Color(0xFF2E3233))),
          ),
            Container(width: 5, color: Colors.transparent),
          new FlatButton(
            child: new Text('Register.', style: new TextStyle(color: Color(0xFF84A2AF), fontWeight: FontWeight.bold),),
            onPressed: moveToRegister,
          )
        ],
      ),
    ),  

NotificationCompat.Builder deprecated in Android O

Here is the sample code, which is working in Android Oreo and less than Oreo.

  NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            NotificationCompat.Builder builder = null;
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                int importance = NotificationManager.IMPORTANCE_DEFAULT;
                NotificationChannel notificationChannel = new NotificationChannel("ID", "Name", importance);
                notificationManager.createNotificationChannel(notificationChannel);
                builder = new NotificationCompat.Builder(getApplicationContext(), notificationChannel.getId());
            } else {
                builder = new NotificationCompat.Builder(getApplicationContext());
            }

            builder = builder
                    .setSmallIcon(R.drawable.ic_notification_icon)
                    .setColor(ContextCompat.getColor(context, R.color.color))
                    .setContentTitle(context.getString(R.string.getTitel))
                    .setTicker(context.getString(R.string.text))
                    .setContentText(message)
                    .setDefaults(Notification.DEFAULT_ALL)
                    .setAutoCancel(true);
            notificationManager.notify(requestCode, builder.build());

Setting attribute disabled on a SPAN element does not prevent click events

The best method is to wrap the span inside a button and disable the button

_x000D_
_x000D_
$("#buttonD").click(function(){_x000D_
  alert("button clicked");_x000D_
})_x000D_
_x000D_
$("#buttonS").click(function(){_x000D_
  alert("span clicked");_x000D_
})
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" />
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" />_x000D_
_x000D_
_x000D_
<button class="btn btn-success" disabled="disabled" id="buttonD">_x000D_
    <span>Disabled button</span>_x000D_
</button>_x000D_
_x000D_
<br>_x000D_
<br>_x000D_
_x000D_
 <span class="btn btn-danger" disabled="disabled" id="buttonS">Disabled span</span>
_x000D_
_x000D_
_x000D_

String index out of range: 4

You are using the wrong iteration counter, replace inp.charAt(i) with inp.charAt(j).

Intel HAXM installation error - This computer does not support Intel Virtualization Technology (VT-x)

chances are that you have windows 8 with hyper-v installed? if yes remove hyper-v and your problem goes away!

How to remove tab indent from several lines in IDLE?

By default, IDLE has it on Shift-Left Bracket. However, if you want, you can customise it to be Shift-Tab by clicking Options --> Configure IDLE --> Keys --> Use a Custom Key Set --> dedent-region --> Get New Keys for Selection

Then you can choose whatever combination you want. (Don't forget to click apply otherwise all the settings would not get affected.)

How to access Spring context in jUnit tests annotated with @RunWith and @ContextConfiguration?

It's possible to inject instance of ApplicationContext class by using SpringClassRule and SpringMethodRule rules. It might be very handy if you would like to use another non-Spring runners. Here's an example:

@ContextConfiguration(classes = BeanConfiguration.class)
public static class SpringRuleUsage {

    @ClassRule
    public static final SpringClassRule springClassRule = new SpringClassRule();

    @Rule
    public final SpringMethodRule springMethodRule = new SpringMethodRule();

    @Autowired
    private ApplicationContext context;

    @Test
    public void shouldInjectContext() {
    }
}

How to overwrite the previous print to stdout in python?

Here's my solution! Windows 10, Python 3.7.1

I'm not sure why this code works, but it completely erases the original line. I compiled it from the previous answers. The other answers would just return the line to the beginning, but if you had a shorter line afterwards, it would look messed up like hello turns into byelo.

import sys
#include ctypes if you're on Windows
import ctypes
kernel32 = ctypes.windll.kernel32
kernel32.SetConsoleMode(kernel32.GetStdHandle(-11), 7)
#end ctypes

def clearline(msg):
    CURSOR_UP_ONE = '\033[K'
    ERASE_LINE = '\x1b[2K'
    sys.stdout.write(CURSOR_UP_ONE)
    sys.stdout.write(ERASE_LINE+'\r')
    print(msg, end='\r')

#example
ig_usernames = ['beyonce','selenagomez']
for name in ig_usernames:
    clearline("SCRAPING COMPLETE: "+ name)

Output - Each line will be rewritten without any old text showing:

SCRAPING COMPLETE: selenagomez

Next line (rewritten completely on same line):

SCRAPING COMPLETE: beyonce

SQL Server AS statement aliased column within WHERE statement

Logical Processing Order of the SELECT statement

The following steps show the logical processing order, or binding order, for a SELECT statement. This order determines when the objects defined in one step are made available to the clauses in subsequent steps. For example, if the query processor can bind to (access) the tables or views defined in the FROM clause, these objects and their columns are made available to all subsequent steps. Conversely, because the SELECT clause is step 8, any column aliases or derived columns defined in that clause cannot be referenced by preceding clauses. However, they can be referenced by subsequent clauses such as the ORDER BY clause. Note that the actual physical execution of the statement is determined by the query processor and the order may vary from this list.

  1. FROM
  2. ON
  3. JOIN
  4. WHERE
  5. GROUP BY
  6. WITH CUBE or WITH ROLLUP
  7. HAVING
  8. SELECT
  9. DISTINCT
  10. ORDER BY
  11. TOP

Source: http://msdn.microsoft.com/en-us/library/ms189499%28v=sql.110%29.aspx

Error in Python script "Expected 2D array, got 1D array instead:"?

With one feature my Dataframe list converts to a Series. I had to convert it back to a Dataframe list and it worked.

if type(X) is Series:
    X = X.to_frame()

How to use string.substr() function?

Another interesting variant question can be:

How would you make "12345" as "12 23 34 45" without using another string?

Will following do?

    for(int i=0; i < a.size()-1; ++i)
    {
        //b = a.substr(i, 2);
        c = atoi((a.substr(i, 2)).c_str());
        cout << c << " ";
    }

How do I get the result of a command in a variable in windows?

Just use the result from the FOR command. For example (inside a batch file):

for /F "delims=" %%I in ('dir /b /a-d /od FILESA*') do (echo %%I)

You can use the %%I as the value you want. Just like this: %%I.

And in advance the %%I does not have any spaces or CR characters and can be used for comparisons!!

Browser/HTML Force download of image from src="data:image/jpeg;base64..."

Simply replace image/jpeg with application/octet-stream. The client would not recognise the URL as an inline-able resource, and prompt a download dialog.

A simple JavaScript solution would be:

//var img = reference to image
var url = img.src.replace(/^data:image\/[^;]+/, 'data:application/octet-stream');
window.open(url);
// Or perhaps: location.href = url;
// Or even setting the location of an <iframe> element, 

Another method is to use a blob: URI:

var img = document.images[0];
img.onclick = function() {
    // atob to base64_decode the data-URI
    var image_data = atob(img.src.split(',')[1]);
    // Use typed arrays to convert the binary data to a Blob
    var arraybuffer = new ArrayBuffer(image_data.length);
    var view = new Uint8Array(arraybuffer);
    for (var i=0; i<image_data.length; i++) {
        view[i] = image_data.charCodeAt(i) & 0xff;
    }
    try {
        // This is the recommended method:
        var blob = new Blob([arraybuffer], {type: 'application/octet-stream'});
    } catch (e) {
        // The BlobBuilder API has been deprecated in favour of Blob, but older
        // browsers don't know about the Blob constructor
        // IE10 also supports BlobBuilder, but since the `Blob` constructor
        //  also works, there's no need to add `MSBlobBuilder`.
        var bb = new (window.WebKitBlobBuilder || window.MozBlobBuilder);
        bb.append(arraybuffer);
        var blob = bb.getBlob('application/octet-stream'); // <-- Here's the Blob
    }

    // Use the URL object to create a temporary URL
    var url = (window.webkitURL || window.URL).createObjectURL(blob);
    location.href = url; // <-- Download!
};

Relevant documentation

TypeError: method() takes 1 positional argument but 2 were given

In my case, I forgot to add the ()

I was calling the method like this

obj = className.myMethod

But it should be is like this

obj = className.myMethod()

Cleanest way to write retry logic?

I know this answer is very old but I just wanted to comment on this because I have run into issues using these while, do, whatever statement with counters.

Over the years I have settled on a better approach I think. That is to use some sort of event aggregation like a reactive extensions "Subject" or the like. When a try fails, you simply publish an event saying the try failed, and have the aggregator function re-schedule the event. This allows you much more control over the retry without polluting the call itself with a bunch of retry loops and what not. Nor are you tying up a single thread with a bunch of thread sleeps.

Maximize a window programmatically and prevent the user from changing the windows state

Change the property WindowState to System.Windows.Forms.FormWindowState.Maximized, in some cases if the older answers doesn't works.

So the window will be maximized, and the other parts are in the other answers.

Clone an image in cv2 python

My favorite method uses cv2.copyMakeBorder with no border, like so.

copy = cv2.copyMakeBorder(original,0,0,0,0,cv2.BORDER_REPLICATE)

Incrementing a date in JavaScript

Timezone/daylight savings aware date increment for JavaScript dates:

function nextDay(date) {
    const sign = v => (v < 0 ? -1 : +1);
    const result = new Date(date.getTime());
    result.setDate(result.getDate() + 1);
    const offset = result.getTimezoneOffset();
    return new Date(result.getTime() + sign(offset) * offset * 60 * 1000);
}

What are type hints in Python 3.5?

Type hints are for maintainability and don't get interpreted by Python. In the code below, the line def add(self, ic:int) doesn't result in an error until the next return... line:

class C1:
    def __init__(self):
        self.idn = 1
    def add(self, ic: int):
        return self.idn + ic

c1 = C1()
c1.add(2)

c1.add(c1)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "<input>", line 5, in add
TypeError: unsupported operand type(s) for +: 'int' and 'C1'

Conditional statement in a one line lambda function in python?

By the time you say rate = lambda whatever... you've defeated the point of lambda and should just define a function. But, if you want a lambda, you can use 'and' and 'or'

lambda(T): (T>200) and (200*exp(-T)) or (400*exp(-T))

Remove empty strings from array while keeping record Without Loop?

You can use lodash's method, it works for string, number and boolean type

_.compact([0, 1, false, 2, '', 3]);
// => [1, 2, 3]

https://lodash.com/docs/4.17.15#compact

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

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

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

python -m pip install filename.tar.gz

How to calculate percentage with a SQL statement

This is, I believe, a general solution, though I tested it using IBM Informix Dynamic Server 11.50.FC3. The following query:

SELECT grade,
       ROUND(100.0 * grade_sum / (SELECT COUNT(*) FROM grades), 2) AS pct_of_grades
    FROM (SELECT grade, COUNT(*) AS grade_sum
            FROM grades
            GROUP BY grade
         )
    ORDER BY grade;

gives the following output on the test data shown below the horizontal rule. The ROUND function may be DBMS-specific, but the rest (probably) is not. (Note that I changed 100 to 100.0 to ensure that the calculation occurs using non-integer - DECIMAL, NUMERIC - arithmetic; see the comments, and thanks to Thunder.)

grade  pct_of_grades
CHAR(1) DECIMAL(32,2)
A       32.26
B       16.13
C       12.90
D       12.90
E       9.68
F       16.13

CREATE TABLE grades
(
    id VARCHAR(10) NOT NULL,
    grade CHAR(1) NOT NULL CHECK (grade MATCHES '[ABCDEF]')
);

INSERT INTO grades VALUES('1001', 'A');
INSERT INTO grades VALUES('1002', 'B');
INSERT INTO grades VALUES('1003', 'F');
INSERT INTO grades VALUES('1004', 'C');
INSERT INTO grades VALUES('1005', 'D');
INSERT INTO grades VALUES('1006', 'A');
INSERT INTO grades VALUES('1007', 'F');
INSERT INTO grades VALUES('1008', 'C');
INSERT INTO grades VALUES('1009', 'A');
INSERT INTO grades VALUES('1010', 'E');
INSERT INTO grades VALUES('1001', 'A');
INSERT INTO grades VALUES('1012', 'F');
INSERT INTO grades VALUES('1013', 'D');
INSERT INTO grades VALUES('1014', 'B');
INSERT INTO grades VALUES('1015', 'E');
INSERT INTO grades VALUES('1016', 'A');
INSERT INTO grades VALUES('1017', 'F');
INSERT INTO grades VALUES('1018', 'B');
INSERT INTO grades VALUES('1019', 'C');
INSERT INTO grades VALUES('1020', 'A');
INSERT INTO grades VALUES('1021', 'A');
INSERT INTO grades VALUES('1022', 'E');
INSERT INTO grades VALUES('1023', 'D');
INSERT INTO grades VALUES('1024', 'B');
INSERT INTO grades VALUES('1025', 'A');
INSERT INTO grades VALUES('1026', 'A');
INSERT INTO grades VALUES('1027', 'D');
INSERT INTO grades VALUES('1028', 'B');
INSERT INTO grades VALUES('1029', 'A');
INSERT INTO grades VALUES('1030', 'C');
INSERT INTO grades VALUES('1031', 'F');

/bin/sh: apt-get: not found

The image you're using is Alpine based, so you can't use apt-get because it's Ubuntu's package manager.

To fix this just use:

apk update and apk add

Why use armeabi-v7a code over armeabi code?

Instead of having a fat APK file, I would like to use just the armeabi files and remove the armeabi-v7a folder.

The opposite is a much better strategy. If you have minSdkVersion to 14 and upload your apk to the play store, you'll notice you'll support the same number of devices whether you support armeabi or not. Therefore, there are no devices with Android 4 or higher which would benefit from armeabi at all.

This is probably why the Android NDK doesn't even support armeabi anymore as per revision r17b. [source]

Valid values for android:fontFamily and what they map to?

Where do these values come from? The documentation for android:fontFamily does not list this information in any place

These are indeed not listed in the documentation. But they are mentioned here under the section 'Font families'. The document lists every new public API for Android Jelly Bean 4.1.

In the styles.xml file in the application I'm working on somebody listed this as the font family, and I'm pretty sure it's wrong:

Yes, that's wrong. You don't reference the font file, you have to use the font name mentioned in the linked document above. In this case it should have been this:

<item name="android:fontFamily">sans-serif</item>

Like the linked answer already stated, 12 variants are possible:

Added in Android Jelly Bean (4.1) - API 16 :

Regular (default):

<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">normal</item> 

Italic:

<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">italic</item>

Bold:

<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">bold</item>

Bold-italic:

<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">bold|italic</item>

Light:

<item name="android:fontFamily">sans-serif-light</item>
<item name="android:textStyle">normal</item>

Light-italic:

<item name="android:fontFamily">sans-serif-light</item>
<item name="android:textStyle">italic</item>

Thin :

<item name="android:fontFamily">sans-serif-thin</item>
<item name="android:textStyle">normal</item>

Thin-italic :

<item name="android:fontFamily">sans-serif-thin</item>
<item name="android:textStyle">italic</item>

Condensed regular:

<item name="android:fontFamily">sans-serif-condensed</item>
<item name="android:textStyle">normal</item>

Condensed italic:

<item name="android:fontFamily">sans-serif-condensed</item>
<item name="android:textStyle">italic</item>

Condensed bold:

<item name="android:fontFamily">sans-serif-condensed</item>
<item name="android:textStyle">bold</item>

Condensed bold-italic:

<item name="android:fontFamily">sans-serif-condensed</item>
<item name="android:textStyle">bold|italic</item>

Added in Android Lollipop (v5.0) - API 21 :

Medium:

<item name="android:fontFamily">sans-serif-medium</item>
<item name="android:textStyle">normal</item>

Medium-italic:

<item name="android:fontFamily">sans-serif-medium</item>
<item name="android:textStyle">italic</item>

Black:

<item name="android:fontFamily">sans-serif-black</item>
<item name="android:textStyle">italic</item>

For quick reference, this is how they all look like:

How do I use the new computeIfAbsent function?

Suppose you have the following code:

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class Test {
    public static void main(String[] s) {
        Map<String, Boolean> whoLetDogsOut = new ConcurrentHashMap<>();
        whoLetDogsOut.computeIfAbsent("snoop", k -> f(k));
        whoLetDogsOut.computeIfAbsent("snoop", k -> f(k));
    }
    static boolean f(String s) {
        System.out.println("creating a value for \""+s+'"');
        return s.isEmpty();
    }
}

Then you will see the message creating a value for "snoop" exactly once as on the second invocation of computeIfAbsent there is already a value for that key. The k in the lambda expression k -> f(k) is just a placeolder (parameter) for the key which the map will pass to your lambda for computing the value. So in the example the key is passed to the function invocation.

Alternatively you could write: whoLetDogsOut.computeIfAbsent("snoop", k -> k.isEmpty()); to achieve the same result without a helper method (but you won’t see the debugging output then). And even simpler, as it is a simple delegation to an existing method you could write: whoLetDogsOut.computeIfAbsent("snoop", String::isEmpty); This delegation does not need any parameters to be written.

To be closer to the example in your question, you could write it as whoLetDogsOut.computeIfAbsent("snoop", key -> tryToLetOut(key)); (it doesn’t matter whether you name the parameter k or key). Or write it as whoLetDogsOut.computeIfAbsent("snoop", MyClass::tryToLetOut); if tryToLetOut is static or whoLetDogsOut.computeIfAbsent("snoop", this::tryToLetOut); if tryToLetOut is an instance method.

How to check if the URL contains a given string?

window.location isn't a String, but it has a toString() method. So you can do it like this:

(''+window.location).includes("franky")

or

window.location.toString().includes("franky")

From the old Mozilla docs:

Location objects have a toString method returning the current URL. You can also assign a string to window.location. This means that you can work with window.location as if it were a string in most cases. Sometimes, for example when you need to call a String method on it, you have to explicitly call toString.

Javascript onHover event

How about something like this?

<html>
<head>
<script type="text/javascript">

var HoverListener = {
  addElem: function( elem, callback, delay )
  {
    if ( delay === undefined )
    {
      delay = 1000;
    }

    var hoverTimer;

    addEvent( elem, 'mouseover', function()
    {
      hoverTimer = setTimeout( callback, delay );
    } );

    addEvent( elem, 'mouseout', function()
    {
      clearTimeout( hoverTimer );
    } );
  }
}

function tester()
{
  alert( 'hi' );
}

//  Generic event abstractor
function addEvent( obj, evt, fn )
{
  if ( 'undefined' != typeof obj.addEventListener )
  {
    obj.addEventListener( evt, fn, false );
  }
  else if ( 'undefined' != typeof obj.attachEvent )
  {
    obj.attachEvent( "on" + evt, fn );
  }
}

addEvent( window, 'load', function()
{
  HoverListener.addElem(
      document.getElementById( 'test' )
    , tester 
  );
  HoverListener.addElem(
      document.getElementById( 'test2' )
    , function()
      {
        alert( 'Hello World!' );
      }
    , 2300
  );
} );

</script>
</head>
<body>
<div id="test">Will alert "hi" on hover after one second</div>
<div id="test2">Will alert "Hello World!" on hover 2.3 seconds</div>
</body>
</html>

How to include multiple js files using jQuery $.getScript() method

What you are looking for is an AMD compliant loader (like require.js).

http://requirejs.org/

http://requirejs.org/docs/whyamd.html

There are many good open source ones if you look it up. Basically this allows you to define a module of code, and if it is dependent on other modules of code, it will wait until those modules have finished downloading before proceeding to run. This way you can load 10 modules asynchronously and there should be no problems even if one depends on a few of the others to run.

Convert a Python list with strings all to lowercase or uppercase

List comprehension is how I'd do it, it's the "Pythonic" way. The following transcript shows how to convert a list to all upper case then back to lower:

pax@paxbox7:~$ python3
Python 3.5.2 (default, Nov 17 2016, 17:05:23) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.

>>> x = ["one", "two", "three"] ; x
['one', 'two', 'three']

>>> x = [element.upper() for element in x] ; x
['ONE', 'TWO', 'THREE']

>>> x = [element.lower() for element in x] ; x
['one', 'two', 'three']

How to get the absolute coordinates of a view

Following Romain Guy's comment, here's how I fixed it. Hopefully it'll help anyone else who also had this problem.

I was indeed trying to get the positions of the views before they had been laid out on the screen but it wasn't at all obvious that was happening. Those lines had been placed after the initilisation code ran, so I assumed everything was ready. However, this code was still in onCreate(); by experimenting with Thread.sleep() I discovered that the layout is not actually finalised until after onCreate() all the way to onResume() had finished executing. So indeed, the code was trying to run before the layout had finished being positioned on the screen. By adding the code to an OnClickListener (or some other Listener) the correct values were obtained because it could only be fired after the layout had finished.


The line below was suggested as a community edit:

please use onWindowfocuschanged(boolean hasFocus)

What is the difference between "JPG" / "JPEG" / "PNG" / "BMP" / "GIF" / "TIFF" Image?

You should be aware of a few key factors...

First, there are two types of compression: Lossless and Lossy.

Lossless means that the image is made smaller, but at no detriment to the quality. Lossy means the image is made (even) smaller, but at a detriment to the quality. If you saved an image in a Lossy format over and over, the image quality would get progressively worse and worse.

There are also different colour depths (palettes): Indexed color and Direct color.

With Indexed it means that the image can only store a limited number of colours (usually 256) that are chosen by the image author, with Direct it means that you can store many thousands of colours that have not been chosen by the author.


BMP - Lossless / Indexed and Direct

This is an old format. It is Lossless (no image data is lost on save) but there's also little to no compression at all, meaning saving as BMP results in VERY large file sizes. It can have palettes of both Indexed and Direct, but that's a small consolation. The file sizes are so unnecessarily large that nobody ever really uses this format.

Good for: Nothing really. There isn't anything BMP excels at, or isn't done better by other formats.

BMP vs GIF


GIF - Lossless / Indexed only

GIF uses lossless compression, meaning that you can save the image over and over and never lose any data. The file sizes are much smaller than BMP, because good compression is actually used, but it can only store an Indexed palette. This means that there can only be a maximum of 256 different colours in the file. That sounds like quite a small amount, and it is.

GIF images can also be animated and have transparency.

Good for: Logos, line drawings, and other simple images that need to be small. Only really used for websites.

GIF vs JPEG


JPEG - Lossy / Direct

JPEGs images were designed to make detailed photographic images as small as possible by removing information that the human eye won't notice. As a result it's a Lossy format, and saving the same file over and over will result in more data being lost over time. It has a palette of thousands of colours and so is great for photographs, but the lossy compression means it's bad for logos and line drawings: Not only will they look fuzzy, but such images will also have a larger file-size compared to GIFs!

Good for: Photographs. Also, gradients.

JPEG vs GIF


PNG-8 - Lossless / Indexed

PNG is a newer format, and PNG-8 (the indexed version of PNG) is really a good replacement for GIFs. Sadly, however, it has a few drawbacks: Firstly it cannot support animation like GIF can (well it can, but only Firefox seems to support it, unlike GIF animation which is supported by every browser). Secondly it has some support issues with older browsers like IE6. Thirdly, important software like Photoshop have very poor implementation of the format. (Damn you, Adobe!) PNG-8 can only store 256 colours, like GIFs.

Good for: The main thing that PNG-8 does better than GIFs is having support for Alpha Transparency.

PNG-8 vs GIF

Important Note: Photoshop does not support Alpha Transparency for PNG-8 files. (Damn you, Photoshop!) There are ways to convert Photoshop PNG-24 to PNG-8 files while retaining their transparency, though. One method is PNGQuant, another is to save your files with Fireworks.


PNG-24 - Lossless / Direct

PNG-24 is a great format that combines Lossless encoding with Direct color (thousands of colours, just like JPEG). It's very much like BMP in that regard, except that PNG actually compresses images, so it results in much smaller files. Unfortunately PNG-24 files will still be much bigger than JPEGs, GIFs and PNG-8s, so you still need to consider if you really want to use one.

Even though PNG-24s allow thousands of colours while having compression, they are not intended to replace JPEG images. A photograph saved as a PNG-24 will likely be at least 5 times larger than a equivalent JPEG image, which very little improvement in visible quality. (Of course, this may be a desirable outcome if you're not concerned about filesize, and want to get the best quality image you can.)

Just like PNG-8, PNG-24 supports alpha-transparency, too.

I hope that helps!

How to wrap text around an image using HTML/CSS

With CSS Shapes you can go one step further than just float text around a rectangular image.

You can actually wrap text such that it takes the shape of the edge of the image or polygon that you are wrapping it around.

DEMO FIDDLE (Currently working on webkit - caniuse)

_x000D_
_x000D_
.oval {_x000D_
  width: 400px;_x000D_
  height: 250px;_x000D_
  color: #111;_x000D_
  border-radius: 50%;_x000D_
  text-align: center;_x000D_
  font-size: 90px;_x000D_
  float: left;_x000D_
  shape-outside: ellipse();_x000D_
  padding: 10px;_x000D_
  background-color: MediumPurple;_x000D_
  background-clip: content-box;_x000D_
}_x000D_
span {_x000D_
  padding-top: 70px;_x000D_
  display: inline-block;_x000D_
}
_x000D_
<div class="oval"><span>PHP</span>_x000D_
</div>_x000D_
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has_x000D_
  survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing_x000D_
  software like Aldus PageMaker including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley_x000D_
  of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing_x000D_
  Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy_x000D_
  text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised_x000D_
  in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
_x000D_
_x000D_
_x000D_

Also, here is a good list apart article on CSS Shapes

Making an image act like a button

You could implement a JavaScript block which contains a function with your needs.

<div style="position: absolute; left: 10px; top: 40px;"> 
    <img src="logg.png" width="114" height="38" onclick="DoSomething();" />
</div>

Converting milliseconds to minutes and seconds with Javascript

Just works:

const minute = Math.floor(( milliseconds % (1000 * 60 * 60)) / (1000 * 60));

const second = Math.floor((ms % (1000 * 60)) / 1000);

Deserializing JSON data to C# using JSON.NET

You can use:

JsonConvert.PopulateObject(json, obj);

here: json is the json string,obj is the target object. See: example

Note: PopulateObject() will not erase obj's list data, after Populate(), obj's list member will contains its original data and data from json string

Rebasing remote branches in Git

It comes down to whether the feature is used by one person or if others are working off of it.

You can force the push after the rebase if it's just you:

git push origin feature -f

However, if others are working on it, you should merge and not rebase off of master.

git merge master
git push origin feature

This will ensure that you have a common history with the people you are collaborating with.

On a different level, you should not be doing back-merges. What you are doing is polluting your feature branch's history with other commits that don't belong to the feature, making subsequent work with that branch more difficult - rebasing or not.

This is my article on the subject called branch per feature.

Hope this helps.

How to add multiple values to a dictionary key in python?

Make the value a list, e.g.

a["abc"] = [1, 2, "bob"]

UPDATE:

There are a couple of ways to add values to key, and to create a list if one isn't already there. I'll show one such method in little steps.

key = "somekey"
a.setdefault(key, [])
a[key].append(1)

Results:

>>> a
{'somekey': [1]}

Next, try:

key = "somekey"
a.setdefault(key, [])
a[key].append(2)

Results:

>>> a
{'somekey': [1, 2]}

The magic of setdefault is that it initializes the value for that key if that key is not defined, otherwise it does nothing. Now, noting that setdefault returns the key you can combine these into a single line:

a.setdefault("somekey",[]).append("bob")

Results:

>>> a
{'somekey': [1, 2, 'bob']}

You should look at the dict methods, in particular the get() method, and do some experiments to get comfortable with this.

Python Loop: List Index Out of Range

When you call for i in a:, you are getting the actual elements, not the indexes. When we reach the last element, that is 3, b.append(a[i+1]-a[i]) looks for a[4], doesn't find one and then fails. Instead, try iterating over the indexes while stopping just short of the last one, like

for i in range(0, len(a)-1): Do something

Your current code won't work yet for the do something part though ;)

How to change the default charset of a MySQL table?

If you want to change the table default character set and all character columns to a new character set, use a statement like this:

ALTER TABLE tbl_name CONVERT TO CHARACTER SET charset_name;

So query will be:

ALTER TABLE etape_prospection CONVERT TO CHARACTER SET utf8;

PHP filesize MB/KB conversion

This is based on @adnan's great answer.

Changes:

  • added internal filesize() call
  • return early style
  • saving one concatentation on 1 byte

And you can still pull the filesize() call out of the function, in order to get a pure bytes formatting function. But this works on a file.


/**
 * Formats filesize in human readable way.
 *
 * @param file $file
 * @return string Formatted Filesize, e.g. "113.24 MB".
 */
function filesize_formatted($file)
{
    $bytes = filesize($file);

    if ($bytes >= 1073741824) {
        return number_format($bytes / 1073741824, 2) . ' GB';
    } elseif ($bytes >= 1048576) {
        return number_format($bytes / 1048576, 2) . ' MB';
    } elseif ($bytes >= 1024) {
        return number_format($bytes / 1024, 2) . ' KB';
    } elseif ($bytes > 1) {
        return $bytes . ' bytes';
    } elseif ($bytes == 1) {
        return '1 byte';
    } else {
        return '0 bytes';
    }
}

Communication between tabs or windows

Checkout AcrossTabs - Easy communication between cross-origin browser tabs. It uses a combination of postMessage and sessionStorage API to make communication much easier and reliable.


There are different approaches and each one has its own advantages and disadvantages. Lets discuss each:

  1. LocalStorage

    Pros:

    1. Web storage can be viewed simplistically as an improvement on cookies, providing much greater storage capacity. If you look at the Mozilla source code we can see that 5120KB (5MB which equals 2.5 Million chars on Chrome) is the default storage size for an entire domain. This gives you considerably more space to work with than a typical 4KB cookie.
    2. The data is not sent back to the server for every HTTP request (HTML, images, JavaScript, CSS, etc) - reducing the amount of traffic between client and server.
    3. The data stored in localStorage persists until explicitly deleted. Changes made are saved and available for all current and future visits to the site.

    Cons:

    1. It works on same-origin policy. So, data stored will only be able available on the same origin.
  2. Cookies

    Pros:

    1. Compared to others, there's nothing AFAIK.

    Cons:

    1. The 4K limit is for the entire cookie, including name, value, expiry date etc. To support most browsers, keep the name under 4000 bytes, and the overall cookie size under 4093 bytes.
    2. The data is sent back to the server for every HTTP request (HTML, images, JavaScript, CSS, etc) - increasing the amount of traffic between client and server.

      Typically, the following are allowed:

      • 300 cookies in total
      • 4096 bytes per cookie
      • 20 cookies per domain
      • 81920 bytes per domain(Given 20 cookies of max size 4096 = 81920 bytes.)
  3. sessionStorage

    Pros:

    1. It is similar to localStorage.
    2. Changes are only available per window (or tab in browsers like Chrome and Firefox). Changes made are saved and available for the current page, as well as future visits to the site on the same window. Once the window is closed, the storage is deleted

    Cons:

    1. The data is available only inside the window/tab in which it was set.
    2. The data is not persistent i.e. it will be lost once the window/tab is closed.
    3. Like localStorage, tt works on same-origin policy. So, data stored will only be able available on the same origin.
  4. PostMessage

    Pros:

    1. Safely enables cross-origin communication.
    2. As a data point, the WebKit implementation (used by Safari and Chrome) doesn't currently enforce any limits (other than those imposed by running out of memory).

    Cons:

    1. Need to open a window from the current window and then can communicate only as long as you keep the windows open.
    2. Security concerns - Sending strings via postMessage is that you will pick up other postMessage events published by other JavaScript plugins, so be sure to implement a targetOrigin and a sanity check for the data being passed on to the messages listener.
  5. A combination of PostMessage + SessionStorage

    Using postMessage to communicate between multiple tabs and at the same time using sessionStorage in all the newly opened tabs/windows to persist data being passed. Data will be persisted as long as the tabs/windows remain opened. So, even if the opener tab/window gets closed, the opened tabs/windows will have the entire data even after getting refreshed.

I have written a JavaScript library for this, named AcrossTabs which uses postMessage API to communicate between cross-origin tabs/windows and sessionStorage to persist the opened tabs/windows identity as long as they live.

How can I adjust DIV width to contents

EDIT2- Yea auto fills the DOM SOZ!

#img_box{        
    width:90%;
    height:90%;
    min-width: 400px;
    min-height: 400px;
}

check out this fiddle

http://jsfiddle.net/ppumkin/4qjXv/2/

http://jsfiddle.net/ppumkin/4qjXv/3/

and this page

http://www.webmasterworld.com/css/3828593.htm

Removed original answer because it was wrong.

The width is ok- but the height resets to 0

so

 min-height: 400px;

Use CSS to remove the space between images

The best solution I've found for this is to contain them in a parent div, and give that div a font-size of 0.

Remove a file from a Git repository without deleting it from the local filesystem

Above answers didn't work for me. I used filter-branch to remove all committed files.

Remove a file from a git repository with:

git filter-branch --tree-filter 'rm  file'

Remove a folder from a git repository with:

git filter-branch --tree-filter 'rm -rf directory'

This removes the directory or file from all the commits.

You can specify a commit by using:

git filter-branch --tree-filter 'rm -rf directory' HEAD

Or an range:

git filter-branch --tree-filter 'rm -rf vendor/gems' t49dse..HEAD

To push everything to remote, you can do:

git push origin master --force

Java - get pixel array from image

Here is another FastRGB implementation found here:

public class FastRGB {
    public int width;
    public int height;
    private boolean hasAlphaChannel;
    private int pixelLength;
    private byte[] pixels;

    FastRGB(BufferedImage image) {
        pixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
        width = image.getWidth();
        height = image.getHeight();
        hasAlphaChannel = image.getAlphaRaster() != null;
        pixelLength = 3;
        if (hasAlphaChannel)
            pixelLength = 4;
    }

    short[] getRGB(int x, int y) {
        int pos = (y * pixelLength * width) + (x * pixelLength);
        short rgb[] = new short[4];
        if (hasAlphaChannel)
            rgb[3] = (short) (pixels[pos++] & 0xFF); // Alpha
        rgb[2] = (short) (pixels[pos++] & 0xFF); // Blue
        rgb[1] = (short) (pixels[pos++] & 0xFF); // Green
        rgb[0] = (short) (pixels[pos++] & 0xFF); // Red
        return rgb;
    }
}

What is this?

Reading an image pixel by pixel through BufferedImage's getRGB method is quite slow, this class is the solution for this.

The idea is that you construct the object by feeding it a BufferedImage instance, and it reads all the data at once and stores them in an array. Once you want to get pixels, you call getRGB

Dependencies

import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;

Considerations

Although FastRGB makes reading pixels much faster, it could lead to high memory usage, as it simply stores a copy of the image. So if you have a 4MB BufferedImage in the memory, once you create the FastRGB instance, the memory usage would become 8MB. You can however, recycle the BufferedImage instance after you create the FastRGB.

Be careful to not fall into OutOfMemoryException when using it on devices such as Android phones, where RAM is a bottleneck

Manually Set Value for FormBuilder Control

You could try this:

deptSelected(selected: { id: string; text: string }) {
  console.log(selected) // Shows proper selection!

  // This is how I am trying to set the value
  this.form.controls['dept'].updateValue(selected.id);
}

For more details, you could have a look at the corresponding JS Doc regarding the second parameter of the updateValue method: https://github.com/angular/angular/blob/master/modules/angular2/src/common/forms/model.ts#L269.

Visual Studio: ContextSwitchDeadlock

In Visual Studio 2017, unchecked the ContextSwitchDeadlock option by:

Debug > Windows > Exception Settings

enter image description here

In Exception Setting Windows: Uncheck the ContextSwitchDeadlock option

enter image description here

How do I limit the number of decimals printed for a double?

Use the DecimalFormat class to format the double

Environment variables in Mac OS X

There are several places where you can set environment variables.

  • ~/.profile: use this for variables you want to set in all programs launched from the terminal (note that, unlike on Linux, all shells opened in Terminal.app are login shells).
  • ~/.bashrc: this is invoked for shells which are not login shells. Use this for aliases and other things which need to be redefined in subshells, not for environment variables that are inherited.
  • /etc/profile: this is loaded before ~/.profile, but is otherwise equivalent. Use it when you want the variable to apply to terminal programs launched by all users on the machine (assuming they use bash).
  • ~/.MacOSX/environment.plist: this is read by loginwindow on login. It applies to all applications, including GUI ones, except those launched by Spotlight in 10.5 (not 10.6). It requires you to logout and login again for changes to take effect. This file is no longer supported as of OS X 10.8.
  • your user's launchd instance: this applies to all programs launched by the user, GUI and CLI. You can apply changes at any time by using the setenv command in launchctl. In theory, you should be able to put setenv commands in ~/.launchd.conf, and launchd would read them automatically when the user logs in, but in practice support for this file was never implemented. Instead, you can use another mechanism to execute a script at login, and have that script call launchctl to set up the launchd environment.
  • /etc/launchd.conf: this is read by launchd when the system starts up and when a user logs in. They affect every single process on the system, because launchd is the root process. To apply changes to the running root launchd you can pipe the commands into sudo launchctl.

The fundamental things to understand are:

  • environment variables are inherited by a process's children at the time they are forked.
  • the root process is a launchd instance, and there is also a separate launchd instance per user session.
  • launchd allows you to change its current environment variables using launchctl; the updated variables are then inherited by all new processes it forks from then on.

Example of setting an environment variable with launchd:

echo setenv REPLACE_WITH_VAR REPLACE_WITH_VALUE | launchctl

Now, launch your GUI app that uses the variable, and voila!

To work around the fact that ~/.launchd.conf does not work, you can put the following script in ~/Library/LaunchAgents/local.launchd.conf.plist:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key>
  <string>local.launchd.conf</string>
  <key>ProgramArguments</key>
  <array>
    <string>sh</string>
    <string>-c</string>
    <string>launchctl &lt; ~/.launchd.conf</string>    
  </array>
  <key>RunAtLoad</key>
  <true/>
</dict>
</plist>

Then you can put setenv REPLACE_WITH_VAR REPLACE_WITH_VALUE inside ~/.launchd.conf, and it will be executed at each login.

Note that, when piping a command list into launchctl in this fashion, you will not be able to set environment variables with values containing spaces. If you need to do so, you can call launchctl as follows: launchctl setenv MYVARIABLE "QUOTE THE STRING".

Also, note that other programs that run at login may execute before the launchagent, and thus may not see the environment variables it sets.

Python For loop get index

Use the enumerate() function to generate the index along with the elements of the sequence you are looping over:

for index, w in enumerate(loopme):
    print "CURRENT WORD IS", w, "AT CHARACTER", index 

Batch / Find And Edit Lines in TXT file

This is the kind of stuff sed was made for (of course, you need sed on your system for that).

sed 's/ex3/ex5/g' input.txt > output.txt

You will either need a Unix system or a Windows Cygwin kind of platform for this.
There is also GnuWin32 for sed. (GnuWin32 installation and usage).

Adding a new SQL column with a default value

Simply add default 0 at the end of your ALTER TABLE <table> ADD COLUMN <column> <type> statement

Append file contents to the bottom of existing file in Bash

This should work:

 cat "$API" >> "$CONFIG"

You need to use the >> operator to append to a file. Redirecting with > causes the file to be overwritten. (truncated).

ArrayList insertion and retrieval order

Yes, it will always be the same. From the documentation

Appends the specified element to the end of this list. Parameters: e element to be appended to this list Returns: true (as specified by Collection.add(java.lang.Object))

ArrayList add() implementation

public boolean More ...add(E e) {
    ensureCapacity(size + 1);  // Increments modCount!!
    elementData[size++] = e;
    return true;
}

How to implement LIMIT with SQL Server?

Syntactically MySQL LIMIT query is something like this:

SELECT * FROM table LIMIT OFFSET, ROW_COUNT

This can be translated into Microsoft SQL Server like

SELECT * FROM 
(
    SELECT TOP #{OFFSET+ROW_COUNT} *, ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS rnum 
    FROM table
) a
WHERE rnum > OFFSET

Now your query select * from table1 LIMIT 10,20 will be like this:

SELECT * FROM 
(
    SELECT TOP 30 *, ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS rnum 
    FROM table1
) a
WHERE rnum > 10 

enum Values to NSString (iOS)

This is an old question, but if you have a non contiguous enum use a dictionary literal instead of an array:

typedef enum {
    value1 = 0,
    value2 = 1,
    value3 = 2,

    // beyond value3
    value1000 = 1000,
    value1001
} MyType;

#define NSStringFromMyType( value ) \
( \
    @{ \
        @( value1 )    : @"value1", \
        @( value2 )    : @"value2", \
        @( value3 )    : @"value3", \
        @( value1000 ) : @"value1000", \
        @( value1001 ) : @"value1001", \
    } \
    [ @( value ) ] \
)

how to add json library

AFAIK the json module was added in version 2.6, see here. I'm guessing you can update your python installation to the latest stable 2.6 from this page.

How to open a new window on form submit

In a web-based database application that uses a pop-up window to display print-outs of database data, this worked well enough for our needs (tested in Chrome 48):

<form method="post" 
      target="print_popup" 
      action="/myFormProcessorInNewWindow.aspx"
      onsubmit="window.open('about:blank','print_popup','width=1000,height=800');">

The trick is to match the target attribute on the <form> tag with the second argument in the window.open call in the onsubmit handler.

What does the clearfix class do in css?

clearfix is the same as overflow:hidden. Both clear floated children of the parent, but clearfix will not cut off the element which overflow to it's parent. It also works in IE8 & above.

There is no need to define "." in content & .clearfix. Just write like this:

.clr:after {
    clear: both;
    content: "";
    display: block;
}

HTML

<div class="parent clr"></div>

Read these links for more

http://css-tricks.com/snippets/css/clear-fix/,

What methods of ‘clearfix’ can I use?

How to generate different random numbers in a loop in C++?

Don't know men. I found the best way for me after testing different ways like 10 minutes. ( Change the numbers in code to get big or small random number.)

    int x;
srand ( time(NULL) );
x = rand() % 1000 * rand() % 10000 ;
cout<<x;

Convert Text to Date?

Solved the issue for me :

    Range(Cells(1, 1), Cells(100, 1)).Select

    For Each xCell In Selection

    xCell.Value = CDate(xCell.Value)

    Next xCell

String, StringBuffer, and StringBuilder

Note that if you are using Java 5 or newer, you should use StringBuilder instead of StringBuffer. From the API documentation:

As of release JDK 5, this class has been supplemented with an equivalent class designed for use by a single thread, StringBuilder. The StringBuilder class should generally be used in preference to this one, as it supports all of the same operations but it is faster, as it performs no synchronization.

In practice, you will almost never use this from multiple threads at the same time, so the synchronization that StringBuffer does is almost always unnecessary overhead.

returning a Void object

Just for the sake of it, there is of course the possibility to create Void instance using reflection:

interface B<E>{ E method(); }

class A implements B<Void>{

    public Void method(){
        // do something

        try {
            Constructor<Void> voidConstructor = Void.class.getDeclaredConstructor();
            voidConstructor.setAccessible(true);
            return voidConstructor.newInstance();
        } catch (Exception ex) {
            // Rethrow, or return null, or whatever.
        }
    }
}

You probably won't do that in production.

Changing fonts in ggplot2

You just missed an initialization step I think.

You can see what fonts you have available with the command windowsFonts(). For example mine looks like this when I started looking at this:

> windowsFonts()
$serif
[1] "TT Times New Roman"

$sans
[1] "TT Arial"

$mono
[1] "TT Courier New"

After intalling the package extraFont and running font_import like this (it took like 5 minutes):

library(extrafont)
font_import()
loadfonts(device = "win")

I had many more available - arguable too many, certainly too many to list here.

Then I tried your code:

library(ggplot2)
library(extrafont)
loadfonts(device = "win")

a <- ggplot(mtcars, aes(x=wt, y=mpg)) + geom_point() +
  ggtitle("Fuel Efficiency of 32 Cars") +
  xlab("Weight (x1000 lb)") + ylab("Miles per Gallon") +
  theme(text=element_text(size=16,  family="Comic Sans MS"))
print(a)

yielding this:

enter image description here

Update:

You can find the name of a font you need for the family parameter of element_text with the following code snippet:

> names(wf[wf=="TT Times New Roman"])
[1] "serif"

And then:

library(ggplot2)
library(extrafont)
loadfonts(device = "win")

a <- ggplot(mtcars, aes(x=wt, y=mpg)) + geom_point() +
  ggtitle("Fuel Efficiency of 32 Cars") +
  xlab("Weight (x1000 lb)") + ylab("Miles per Gallon") +
  theme(text=element_text(size=16,  family="serif"))
print(a)

yields: enter image description here

How can I plot a histogram such that the heights of the bars sum to 1 in matplotlib?

It would be more helpful if you posed a more complete working (or in this case non-working) example.

I tried the following:

import numpy as np
import matplotlib.pyplot as plt

x = np.random.randn(1000)

fig = plt.figure()
ax = fig.add_subplot(111)
n, bins, rectangles = ax.hist(x, 50, density=True)
fig.canvas.draw()
plt.show()

This will indeed produce a bar-chart histogram with a y-axis that goes from [0,1].

Further, as per the hist documentation (i.e. ax.hist? from ipython), I think the sum is fine too:

*normed*:
If *True*, the first element of the return tuple will
be the counts normalized to form a probability density, i.e.,
``n/(len(x)*dbin)``.  In a probability density, the integral of
the histogram should be 1; you can verify that with a
trapezoidal integration of the probability density function::

    pdf, bins, patches = ax.hist(...)
    print np.sum(pdf * np.diff(bins))

Giving this a try after the commands above:

np.sum(n * np.diff(bins))

I get a return value of 1.0 as expected. Remember that normed=True doesn't mean that the sum of the value at each bar will be unity, but rather than the integral over the bars is unity. In my case np.sum(n) returned approx 7.2767.

case-insensitive matching in xpath?

This does not work in Chrome Developer tools to locate a element, i am looking to locate the 'Submit' button in the screen

//input[matches(@value,'submit','i')]

However, using 'translate' to replace all caps to small works as below

//input[translate(@value,'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz') = 'submit']

Update: I just found the reason why 'matches' doesnt work. I am using Chrome with xpath 1.0 which wont understand the syntax 'matches'. It should be xpath 2.0

ArrayAdapter in android to create simple listview

You don't need to use id for textview. You can learn more from android arrayadapter. The below code initializes the arrayadapter.

ArrayAdapter arrayAdapter = new ArrayAdapter(this, R.layout.single_item, eatables);

Iterating through a List Object in JSP

 <c:forEach items="${sessionScope.empL}" var="emp">
            <tr>
                <td>Employee ID: <c:out value="${emp.eid}"/></td>
                <td>Employee Pass: <c:out value="${emp.ename}"/></td>  
            </tr>
        </c:forEach>

is there a require for json in node.js

No. Either use readFile or readFileSync (The latter only at startup time).

Or use an existing library like

Alternatively write your config in a js file rather then a json file like

module.exports = {
  // json
}

How to install PHP intl extension in Ubuntu 14.04

install it from terminal

sudo apt-get install php-intl

Effect of NOLOCK hint in SELECT statements

NOLOCK makes most SELECT statements faster, because of the lack of shared locks. Also, the lack of issuance of the locks means that writers will not be impeded by your SELECT.

NOLOCK is functionally equivalent to an isolation level of READ UNCOMMITTED. The main difference is that you can use NOLOCK on some tables but not others, if you choose. If you plan to use NOLOCK on all tables in a complex query, then using SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED is easier, because you don't have to apply the hint to every table.

Here is information about all of the isolation levels at your disposal, as well as table hints.

SET TRANSACTION ISOLATION LEVEL

Table Hint (Transact-SQL)

C# Version Of SQL LIKE

public static class StringsEx
{
    public static IEnumerable<String> Like(this IEnumerable<String> input, String pattern)
    {
        var dt = new DataTable();
        dt.Columns.Add("Search");
        foreach (String str in input)
        {
            dt.Rows.Add(str);
        }
        dt.DefaultView.RowFilter = String.Format("Search LIKE '{0}'", pattern);
        return dt.DefaultView.ToTable()
            .AsEnumerable()
            .Select(r => r.Field<String>("Search"));
    }
}

The only disadvantage is following: "Wildcard characters are not allowed in the middle of a string. For example, 'te*xt' is not allowed."©

Coarse-grained vs fine-grained

Coarse-grained: A few ojects hold a lot of related data that's why services have broader scope in functionality. Example: A single "Account" object holds the customer name, address, account balance, opening date, last change date, etc. Thus: Increased design complexity, smaller number of cells to various operations

Fine-grained: More objects each holding less data that's why services have more narrow scope in functionality. Example: An Account object holds balance, a Customer object holds name and address, a AccountOpenings object holds opening date, etc. Thus: Decreased design complexity , higher number of cells to various service operations. These are relationships defined between these objects.

How to identify which columns are not "NA" per row in a matrix?

Try:

which( !is.na(p), arr.ind=TRUE)

Which I think is just as informative and probably more useful than the output you specified, But if you really wanted the list version, then this could be used:

> apply(p, 1, function(x) which(!is.na(x)) )
[[1]]
[1] 2 3

[[2]]
[1] 4 7

[[3]]
integer(0)

[[4]]
[1] 5

[[5]]
integer(0)

Or even with smushing together with paste:

lapply(apply(p, 1, function(x) which(!is.na(x)) ) , paste, collapse=", ")

The output from which function the suggested method delivers the row and column of non-zero (TRUE) locations of logical tests:

> which( !is.na(p), arr.ind=TRUE)
     row col
[1,]   1   2
[2,]   1   3
[3,]   2   4
[4,]   4   5
[5,]   2   7

Without the arr.ind parameter set to non-default TRUE, you only get the "vector location" determined using the column major ordering the R has as its convention. R-matrices are just "folded vectors".

> which( !is.na(p) )
[1]  6 11 17 24 32

Difference between a Structure and a Union

The uses of union Unions are used frequently when specialized type conversations are needed. To get an idea of the usefulness of union. The c/c standard library defines no function specifically designed to write short integers to a file. Using fwrite() incurs encurs excessive overhead for simple operation. However using a union you can easily create a function which writes binary of a short integer to a file one byte at a time. I assume that short integers are 2 byte long

THE EXAMPLE:

#include<stdio.h>
union pw {
short int i;
char ch[2];
};
int putw(short int num, FILE *fp);
int main (void)
{
FILE *fp;
fp fopen("test.tmp", "wb ");
putw(1000, fp); /* write the value 1000 as an integer*/
fclose(fp);
return 0;
}
int putw(short int num, FILE *fp)
{
pw word;
word.i = num;
putc(word.c[0] , fp);
return putc(word.c[1] , fp);
}    

although putw() i called with short integer, it was possble to use putc() and fwrite(). But i wanted to show an example to dominstrate how a union can be used

Break promise chain and call a function based on the step in the chain where it is broken (rejected)

Try ro use this like libs:

https://www.npmjs.com/package/promise-chain-break

    db.getData()
.then(pb((data) => {
    if (!data.someCheck()) {
        tellSomeone();

        // All other '.then' calls will be skiped
        return pb.BREAK;
    }
}))
.then(pb(() => {
}))
.then(pb(() => {
}))
.catch((error) => {
    console.error(error);
});

Bootstrap 4: Multilevel Dropdown Inside Navigation

I use the following piece of CSS and JavaScript. It uses an extra class dropdown-submenu. I tested it with Bootstrap 4 beta.

It supports multi level sub menus.

_x000D_
_x000D_
$('.dropdown-menu a.dropdown-toggle').on('click', function(e) {_x000D_
  if (!$(this).next().hasClass('show')) {_x000D_
    $(this).parents('.dropdown-menu').first().find('.show').removeClass('show');_x000D_
  }_x000D_
  var $subMenu = $(this).next('.dropdown-menu');_x000D_
  $subMenu.toggleClass('show');_x000D_
_x000D_
_x000D_
  $(this).parents('li.nav-item.dropdown.show').on('hidden.bs.dropdown', function(e) {_x000D_
    $('.dropdown-submenu .show').removeClass('show');_x000D_
  });_x000D_
_x000D_
_x000D_
  return false;_x000D_
});
_x000D_
.dropdown-submenu {_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
.dropdown-submenu a::after {_x000D_
  transform: rotate(-90deg);_x000D_
  position: absolute;_x000D_
  right: 6px;_x000D_
  top: .8em;_x000D_
}_x000D_
_x000D_
.dropdown-submenu .dropdown-menu {_x000D_
  top: 0;_x000D_
  left: 100%;_x000D_
  margin-left: .1rem;_x000D_
  margin-right: .1rem;_x000D_
}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">_x000D_
_x000D_
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>_x000D_
_x000D_
<nav class="navbar navbar-expand-lg navbar-light bg-light">_x000D_
  <a class="navbar-brand" href="#">Navbar</a>_x000D_
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">_x000D_
    <span class="navbar-toggler-icon"></span>_x000D_
  </button>_x000D_
  <div class="collapse navbar-collapse" id="navbarNavDropdown">_x000D_
    <ul class="navbar-nav">_x000D_
      <li class="nav-item active">_x000D_
        <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>_x000D_
      </li>_x000D_
      <li class="nav-item dropdown">_x000D_
        <a class="nav-link dropdown-toggle" href="http://example.com" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">_x000D_
          Dropdown link_x000D_
        </a>_x000D_
        <ul class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">_x000D_
          <li><a class="dropdown-item" href="#">Action</a></li>_x000D_
          <li><a class="dropdown-item" href="#">Another action</a></li>_x000D_
          <li class="dropdown-submenu">_x000D_
            <a class="dropdown-item dropdown-toggle" href="#">Submenu</a>_x000D_
            <ul class="dropdown-menu">_x000D_
              <li><a class="dropdown-item" href="#">Submenu action</a></li>_x000D_
              <li><a class="dropdown-item" href="#">Another submenu action</a></li>_x000D_
_x000D_
_x000D_
              <li class="dropdown-submenu">_x000D_
                <a class="dropdown-item dropdown-toggle" href="#">Subsubmenu</a>_x000D_
                <ul class="dropdown-menu">_x000D_
                  <li><a class="dropdown-item" href="#">Subsubmenu action</a></li>_x000D_
                  <li><a class="dropdown-item" href="#">Another subsubmenu action</a></li>_x000D_
                </ul>_x000D_
              </li>_x000D_
              <li class="dropdown-submenu">_x000D_
                <a class="dropdown-item dropdown-toggle" href="#">Second subsubmenu</a>_x000D_
                <ul class="dropdown-menu">_x000D_
                  <li><a class="dropdown-item" href="#">Subsubmenu action</a></li>_x000D_
                  <li><a class="dropdown-item" href="#">Another subsubmenu action</a></li>_x000D_
                </ul>_x000D_
              </li>_x000D_
_x000D_
_x000D_
_x000D_
            </ul>_x000D_
          </li>_x000D_
        </ul>_x000D_
      </li>_x000D_
    </ul>_x000D_
  </div>_x000D_
</nav>
_x000D_
_x000D_
_x000D_

XPath: Get parent node from child node

Just as an alternative, you can use ancestor.

//*[title="50"]/ancestor::store

It's more powerful than parent since it can get even the grandparent or great great grandparent

Long press on UITableView

I put together a little category on UITableView based on Anna Karenina's excellent answer.

Like this you'll have a convenient delegate method like you're used to when dealing with regular table views. Check it out:

//  UITableView+LongPress.h

#import <UIKit/UIKit.h>

@protocol UITableViewDelegateLongPress;

@interface UITableView (LongPress) <UIGestureRecognizerDelegate>
@property(nonatomic,assign)   id <UITableViewDelegateLongPress>   delegate;
- (void)addLongPressRecognizer;
@end


@protocol UITableViewDelegateLongPress <UITableViewDelegate>
- (void)tableView:(UITableView *)tableView didRecognizeLongPressOnRowAtIndexPath:(NSIndexPath *)indexPath;
@end



//  UITableView+LongPress.m

#import "UITableView+LongPress.h"

@implementation UITableView (LongPress)
@dynamic delegate;

- (void)addLongPressRecognizer {
    UILongPressGestureRecognizer *lpgr = [[UILongPressGestureRecognizer alloc]
                                          initWithTarget:self action:@selector(handleLongPress:)];
    lpgr.minimumPressDuration = 1.2; //seconds
    lpgr.delegate = self;
    [self addGestureRecognizer:lpgr];
}


- (void)handleLongPress:(UILongPressGestureRecognizer *)gestureRecognizer
{
    CGPoint p = [gestureRecognizer locationInView:self];

    NSIndexPath *indexPath = [self indexPathForRowAtPoint:p];
    if (indexPath == nil) {
        NSLog(@"long press on table view but not on a row");
    }
    else {
        if (gestureRecognizer.state == UIGestureRecognizerStateBegan) {
            // I am not sure why I need to cast here. But it seems to be alright.
            [(id<UITableViewDelegateLongPress>)self.delegate tableView:self didRecognizeLongPressOnRowAtIndexPath:indexPath];
        }
    }
}

If you want to use this in a UITableViewController, you probably need to subclass and conform to the new protocol.

It works great for me, hope it helps others!

How to make a parent div auto size to the width of its children divs

The parent div (I assume the outermost div) is display: block and will fill up all available area of its container (in this case, the body) that it can. Use a different display type -- inline-block is probably what you are going for:

http://jsfiddle.net/a78xy/

How to upgrade PostgreSQL from version 9.6 to version 10.1 without losing data?

On Windows I kept facing different errors messages when trying to use pg_upgrade.

Saved a lot of time for me to just:

  1. Backup DB
  2. Uninstall all copies of PostgreSQL
  3. Install 9.5
  4. Restore DB

How to remove application from app listings on Android Developer Console

you can remove an App from the store or "Unpublish" by clicking a tiny label bellow your app's title, right side of the "PUBLISHED" green status label.

enter image description here

Works even if your app was live (published) for long time, mine was.

Regards.

How do I verify that a string only contains letters, numbers, underscores and dashes?

Regular expression can be very flexible.

import re;
re.fullmatch("^[\w-]+$", target_string) # fullmatch looks also workable for python 3.4

\w: Only [a-zA-Z0-9_]

So you need to add - char for justify hyphen char.

+: Match one or more repetitions of the preceding char. I guess you don't accept blank input. But if you do, change to * .

^: Matches the start of the string.

$: Matches the end of the string.

You need these two special characters since you need to avoid the following case. The unwanted chars like & here might appear between the matched pattern.

&&&PATTERN&&PATTERN

Android SQLite SELECT Query

Try trimming the string to make sure there is no extra white space:

Cursor c = db.rawQuery("SELECT * FROM tbl1 WHERE TRIM(name) = '"+name.trim()+"'", null);

Also use c.moveToFirst() like @thinksteep mentioned.


This is a complete code for select statements.

SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery("SELECT column1,column2,column3 FROM table ", null);
if (c.moveToFirst()){
    do {
        // Passing values 
        String column1 = c.getString(0);
        String column2 = c.getString(1);
        String column3 = c.getString(2); 
        // Do something Here with values
    } while(c.moveToNext());
}
c.close();
db.close();

calculate the mean for each column of a matrix in R

try it ! also can calculate NA's data!

df <- data.frame(a1=1:10, a2=11:20)

df %>% summarise_each(funs( mean( .,na.rm = TRUE)))


# a1   a2
# 5.5 15.5

How to read a file without newlines?

You can read the whole file and split lines using str.splitlines:

temp = file.read().splitlines()

Or you can strip the newline by hand:

temp = [line[:-1] for line in file]

Note: this last solution only works if the file ends with a newline, otherwise the last line will lose a character.

This assumption is true in most cases (especially for files created by text editors, which often do add an ending newline anyway).

If you want to avoid this you can add a newline at the end of file:

with open(the_file, 'r+') as f:
    f.seek(-1, 2)  # go at the end of the file
    if f.read(1) != '\n':
        # add missing newline if not already present
        f.write('\n')
        f.flush()
        f.seek(0)
    lines = [line[:-1] for line in f]

Or a simpler alternative is to strip the newline instead:

[line.rstrip('\n') for line in file]

Or even, although pretty unreadable:

[line[:-(line[-1] == '\n') or len(line)+1] for line in file]

Which exploits the fact that the return value of or isn't a boolean, but the object that was evaluated true or false.


The readlines method is actually equivalent to:

def readlines(self):
    lines = []
    for line in iter(self.readline, ''):
        lines.append(line)
    return lines

# or equivalently

def readlines(self):
    lines = []
    while True:
        line = self.readline()
        if not line:
            break
        lines.append(line)
    return lines

Since readline() keeps the newline also readlines() keeps it.

Note: for symmetry to readlines() the writelines() method does not add ending newlines, so f2.writelines(f.readlines()) produces an exact copy of f in f2.

Get first element in PHP stdObject

Update PHP 7.4

Curly brace access syntax is deprecated since PHP 7.4

Update 2019

Moving on to the best practices of OOPS, @MrTrick's answer must be marked as correct, although my answer provides a hacked solution its not the best method.

Simply iterate its using {}

Example:

$videos{0}->id

This way your object is not destroyed and you can easily iterate through object.

For PHP 5.6 and below use this

$videos{0}['id']

Both array() and the stdClass objects can be accessed using the current() key() next() prev() reset() end() functions.

So, if your object looks like

object(stdClass)#19 (3) {
  [0]=>
  object(stdClass)#20 (22) {
    ["id"]=>
    string(1) "123"
  etc...

Then you can just do;

$id = reset($obj)->id; //Gets the 'id' attr of the first entry in the object

If you need the key for some reason, you can do;

reset($obj); //Ensure that we're at the first element
$key = key($obj);

Hope that works for you. :-) No errors, even in super-strict mode, on PHP 5.4


2022 Update:
After PHP 7.4, using current(), end(), etc functions on objects is deprecated.

In newer versions of PHP, use the ArrayIterator class:

$objIterator = new ArrayIterator($obj);

$id = $objIterator->current()->id; // Gets the 'id' attr of the first entry in the object

$key = $objIterator->key(); // and gets the key

Creating and returning Observable from Angular 2 Service

I'm a little late to the party, but I think my approach has the advantage that it lacks the use of EventEmitters and Subjects.

So, here's my approach. We can't get away from subscribe(), and we don't want to. In that vein, our service will return an Observable<T> with an observer that has our precious cargo. From the caller, we'll initialize a variable, Observable<T>, and it will get the service's Observable<T>. Next, we'll subscribe to this object. Finally, you get your "T"! from your service.

First, our people service, but yours doesnt pass parameters, that's more realistic:

people(hairColor: string): Observable<People> {
   this.url = "api/" + hairColor + "/people.json";

   return Observable.create(observer => {
      http.get(this.url)
          .map(res => res.json())
          .subscribe((data) => {
             this._people = data

             observer.next(this._people);
             observer.complete();


          });
   });
}

Ok, as you can see, we're returning an Observable of type "people". The signature of the method, even says so! We tuck-in the _people object into our observer. We'll access this type from our caller in the Component, next!

In the Component:

private _peopleObservable: Observable<people>;

constructor(private peopleService: PeopleService){}

getPeople(hairColor:string) {
   this._peopleObservable = this.peopleService.people(hairColor);

   this._peopleObservable.subscribe((data) => {
      this.people = data;
   });
}

We initialize our _peopleObservable by returning that Observable<people> from our PeopleService. Then, we subscribe to this property. Finally, we set this.people to our data(people) response.

Architecting the service in this fashion has one, major advantage over the typical service: map(...) and component: "subscribe(...)" pattern. In the real world, we need to map the json to our properties in our class and, sometimes, we do some custom stuff there. So this mapping can occur in our service. And, typically, because our service call will be used not once, but, probably, in other places in our code, we don't have to perform that mapping in some component, again. Moreover, what if we add a new field to people?....

Regular Expression to get all characters before "-"

This is something like the regular expression you need:

([^-]*)-

Quick tests in JavaScript:

/([^-]*)-/.exec('text-1')[1] // 'text'

/([^-]*)-/.exec('foo-bar-1')[1] // 'foo'

/([^-]*)-/.exec('-1')[1] // ''

/([^-]*)-/.exec('quux')[1] // explodes

How can I convert a long to int in Java?

Long x = 100L;
int y = x.intValue();

What is the correct way to do a CSS Wrapper?

Centering content has so many avenues that it can't really be explored in a single answer. If you would like to explore them, CSS Zen Garden is an enjoyable-if-old resource exploring the many, many ways to layout content in a way even old browsers will tolerate.

The correct way, if you don't have any mitigating requirements, is to just apply margin: auto to the sides, and a width. If your page has no content that needs to go outside those margins, just apply it to the body:

body {
  padding: 0;
  margin: 15px auto;
  width: 500px;
}

https://jsfiddle.net/b9chris/62wgq8nk/

So here we've got a 500px wide set of content centered at all* sizes. The padding 0 is to deal with some browsers that like to apply some default padding and throw us off a bit. In the example I do wrap the content in an article tag to be nice to Screen Readers, Pocket, etc so for example the blind can jump past the nav you likely have (which should be in nav) and straight to the content.

I say all* because below 500px this will mess up - we're not being Responsive. To get Responsive, you could just use Bootstrap etc, but building it yourself you use a Media Query like:

body {
  padding: 0;

  margin: 15px;
  @media (min-width: 500px) {
    margin: 15px auto;
    width: 500px;
  }
}

Note that this is SCSS/SASS syntax - if you're using plain CSS, it's inverted:

body {
  padding: 0;  
  margin: 15px;
}

@media (min-width: 500px) {
  body {
    margin: 15px auto;
    width: 500px;
  }
}

https://jsfiddle.net/b9chris/62wgq8nk/6/

It's common however to want to center just one chunk of a page, so let's apply this to only the article tag in a final example.

body {
  padding: 0;
  margin: 0;
}

nav {
  width: 100%;
  box-sizing: border-box;
  padding: 15px;
}

article {
  margin: 15px;
  @media (min-width: 500px) {
    margin: 15px auto;
    width: 500px;
  }
}

https://jsfiddle.net/b9chris/62wgq8nk/17/

Note that this final example also uses CSS Flexbox in the nav, which is also one of the newer ways you could center things. So, that's fun.

But, there are special circumstances where you need to use other approaches to center content, and each of those is probably worth its own question (many of them already asked and answered here on this site).

How do I copy a hash in Ruby?

Since Ruby has a million ways to do it, here's another way using Enumerable:

h0 = {  "John"=>"Adams","Thomas"=>"Jefferson","Johny"=>"Appleseed"}
h1 = h0.inject({}) do |new, (name, value)| 
    new[name] = value;
    new 
end

Initializing multiple variables to the same value in Java

String one, two, three;
one = two = three = "";

This should work with immutable objects. It doesn't make any sense for mutable objects for example:

Person firstPerson, secondPerson, thirdPerson;
firstPerson = secondPerson = thirdPerson = new Person();

All the variables would be pointing to the same instance. Probably what you would need in that case is:

Person firstPerson = new Person();
Person secondPerson = new Person();
Person thirdPerson = new Person();

Or better yet use an array or a Collection.

Can you delete data from influxdb?

With influx, you can only delete by time

For example, the following are invalid:

#Wrong
DELETE FROM foo WHERE time < '2014-06-30' and duration > 1000 #Can't delete if where clause has non time entity

This is how I was able to delete the data

DELETE FROM foo WHERE time > '2014-06-30' and time < '2014-06-30 15:16:01'

Update: this worked on influx 8. Supposedly it doesn't work on influx 9

Preferred way to create a Scala list

Uhmm.. these seem too complex to me. May I propose

def listTestD = (0 to 3).toList

or

def listTestE = for (i <- (0 to 3).toList) yield i

C# equivalent to Java's charAt()?

Console.WriteLine allows the user to specify a position in a string.

See sample:

string str = "Tigger"; Console.WriteLine( str[0] ); //returns "T"; Console.WriteLine( str[2] ); //returns "g";

There you go!

Getting value from appsettings.json in .net core

    public static void GetSection()
    {
        Configuration = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json")
            .Build();

        string BConfig = Configuration.GetSection("ConnectionStrings")["BConnection"];

    }

Replace NA with 0 in a data frame column

First, here's some sample data:

set.seed(1)
dat <- data.frame(one = rnorm(15),
                 two = sample(LETTERS, 15),
                 three = rnorm(15),
                 four = runif(15))
dat <- data.frame(lapply(dat, function(x) { x[sample(15, 5)] <- NA; x }))
head(dat)
#          one  two       three      four
# 1         NA    M  0.80418951 0.8921983
# 2  0.1836433    O -0.05710677        NA
# 3 -0.8356286    L  0.50360797 0.3899895
# 4         NA    E          NA        NA
# 5  0.3295078    S          NA 0.9606180
# 6 -0.8204684 <NA> -1.28459935 0.4346595

Here's our replacement:

dat[["four"]][is.na(dat[["four"]])] <- 0
head(dat)
#          one  two       three      four
# 1         NA    M  0.80418951 0.8921983
# 2  0.1836433    O -0.05710677 0.0000000
# 3 -0.8356286    L  0.50360797 0.3899895
# 4         NA    E          NA 0.0000000
# 5  0.3295078    S          NA 0.9606180
# 6 -0.8204684 <NA> -1.28459935 0.4346595

Alternatively, you can, of course, write dat$four[is.na(dat$four)] <- 0

How to set fake GPS location on IOS real device

it seems with XCode 9.2 the way to import .gpx has changed, I tried the ways described here and did not do. The only way worked for me was to drag and drop the file .gpx to the project navigator window on the left. Then I can choose the country in the simulator item.

Hope this helps to someone.

How can I revert a single file to a previous version?

Git doesn't think in terms of file versions. A version in git is a snapshot of the entire tree.

Given this, what you really want is a tree that has the latest content of most files, but with the contents of one file the same as it was 5 commits ago. This will take the form of a new commit on top of the old ones, and the latest version of the tree will have what you want.

I don't know if there's a one-liner that will revert a single file to the contents of 5 commits ago, but the lo-fi solution should work: checkout master~5, copy the file somewhere else, checkout master, copy the file back, then commit.

How do I REALLY reset the Visual Studio window layout?

I close them, but they always come back

When you say "they always come back" do you mean "next time you restart Visual Studio" or "immediately"?

One quirk of Visual Studio (at least VS2005) is that settings aren't saved until you exit. That means that if VS crashes at all while you are using it, any layout changes you made will be lost. The way around this is to always gracefully exit when you have set up everything like you want it to be.

Not sure if this will help your particular situation though.

check if a number already exist in a list in python

If you want your numbers in ascending order you can add them into a set and then sort the set into an ascending list.

s = set()
if number1 not in s:
  s.add(number1)
if number2 not in s:
  s.add(number2)
...
s = sorted(s)  #Now a list in ascending order

Is there any way to wait for AJAX response and halt execution?

New, using jquery's promise implementation:

function functABC(){

  // returns a promise that can be used later. 

  return $.ajax({
    url: 'myPage.php',
    data: {id: id}
  });
}


functABC().then( response => 
  console.log(response);
);

Nice read e.g. here.

This is not "synchronous" really, but I think it achieves what the OP intends.

Old, (jquery's async option has since been deprecated):

All Ajax calls can be done either asynchronously (with a callback function, this would be the function specified after the 'success' key) or synchronously - effectively blocking and waiting for the servers answer. To get a synchronous execution you have to specify

async: false 

like described here

Note, however, that in most cases asynchronous execution (via callback on success) is just fine.

Unsupported major.minor version 52.0 when rendering in Android Studio

I had to update Java version to JDK 8 at Jenkins->Manage Jenkins->Global Tool Configuration->JDK.

How to wait for all threads to finish, using ExecutorService?

Java 8 - We can use stream API to process stream. Please see snippet below

final List<Runnable> tasks = ...; //or any other functional interface
tasks.stream().parallel().forEach(Runnable::run) // Uses default pool

//alternatively to specify parallelism 
new ForkJoinPool(15).submit(
          () -> tasks.stream().parallel().forEach(Runnable::run) 
    ).get();

Why number 9 in kill -9 command in unix?

It's a reference to "Revoulution 9" by the Beatles. A collection of strung together sound clips and found noises, this recording features John Lennon repeating over and over "Number 9, Number 9..." Further, this song drew further attention in 1969 when it was discovered that when played backwards, John seemed to be saying "Turn me on, dead man..."

Therefore the ninth signal was destined to be the deadliest of the kill signals.

How to check if directory exist using C++ and winAPI

Here is a simple function which does exactly this :

#include <windows.h>
#include <string>

bool dirExists(const std::string& dirName_in)
{
  DWORD ftyp = GetFileAttributesA(dirName_in.c_str());
  if (ftyp == INVALID_FILE_ATTRIBUTES)
    return false;  //something is wrong with your path!

  if (ftyp & FILE_ATTRIBUTE_DIRECTORY)
    return true;   // this is a directory!

  return false;    // this is not a directory!
}

Android Studio marks R in red with error message "cannot resolve symbol R", but build succeeds

I had same problem while using exercise files from a training website and tried resolving the problem by uninstalling android studio and deleting all associated directories and reinstalling it but this yielded no result. However, I noticed that The tutorial i was viewing stored its exercise files on the DESKTOP while mine was in a folder in my DOWNLOADS directory so I Simply copied all exercise files to my Desktop; this made my exercise folder structure identical to that of the tutorial creator and this did the trick.

What is the best way to conditionally apply attributes in AngularJS?

For input field validation you can do:

<input ng-model="discount" type="number" ng-attr-max="{{discountType == '%' ? 100 : undefined}}">

This will apply the attribute max to 100 only if discountType is defined as %

need to test if sql query was successful

Check this:

<?php
if (mysqli_num_rows(mysqli_query($con, sqlselectquery)) > 0)
{
    echo "found";
}
else
{
    echo "not found";
}
?>

<!----comment ---for select query to know row matching the condition are fetched or not--->

axios post request to send form data

Check out querystring.

You can use it as follows:

var querystring = require('querystring');
axios.post('http://something.com/', querystring.stringify({ foo: 'bar' }));

How do I add options to a DropDownList using jQuery?

I needed to add as many options to dropdowns as there were dropdowns on my page. So I used it in this way:

function myAppender(obj, value, text){
    obj.append($('<option></option>').val(value).html(text));
}

$(document).ready(function() {
    var counter = 0;
    var builder = 0;
    // Get the number of dropdowns
    $('[id*="ddlPosition_"]').each(function() {
        counter++;
    });

    // Add the options for each dropdown
    $('[id*="ddlPosition_"]').each(function() {
        var myId = this.id.split('_')[1];

        // Add each option in a loop for the specific dropdown we are on
        for (var i=0; i<counter; i++) {
            myAppender($('[id*="ddlPosition_'+myId+'"]'), i, i+1);
        }
        $('[id*="ddlPosition_'+myId+'"]').val(builder);
        builder++;
    });
});

This dynamically set up dropdowns with values like 1 to n, and automatically selected the value for the order that dropdown was in (i.e. 2nd dropdown got "2" in the box, etc.).

It was ridiculous that I could not use this or this.Object or $.obj or anything like that in my 2nd .each(), though --- I actually had to get the specific ID of that object and then grab and pass that whole object to my function before it would append. Fortunately the ID of my dropdown was separated by a "_" and I could grab it. I don't feel I should have had to, but it kept giving me jQuery exceptions otherwise. Something others struggling with what I was might enjoy knowing.

How to get the size of the current screen in WPF?

It works with

this.Width = System.Windows.SystemParameters.VirtualScreenWidth;
this.Height = System.Windows.SystemParameters.VirtualScreenHeight;

Tested on 2 monitors.

Scrolling to an Anchor using Transition/CSS3

Here is a pure css solution using viewport units and variables that automatically scales to the device (and works on window resize). I added the following to Alex's solution:

        html,body {
            width: 100%;
            height: 100%;
            position: fixed;/* prevents scrolling */
            --innerheight: 100vh;/* variable 100% of viewport height */
        }

        body {
            overflow: hidden; /* prevents scrolling */
        }

        .panel {
            width: 100%;
            height: var(--innerheight); /* viewport height */

        a[ id= "galeria" ]:target ~ #main article.panel {
            -webkit-transform: translateY( calc(-1*var(--innerheight)) );
            transform: translateY( calc(-1*var(--innerheight)) );
        }

        a[ id= "contacto" ]:target ~ #main article.panel {
            -webkit-transform: translateY( calc(-2*var(--innerheight)) );
            transform: translateY( calc(-2*var(--innerheight)) );

Google Maps how to Show city or an Area outline

so I have a solution that isn't perfect but it worked for me. Use the polygon example from Google, and use the pinpoint on Google Maps to get lat & long locations.

Calgary pinpoint

I used what I call "ocular copy & paste" where you look at the screen and then write in the numbers you want ;-)

<style>
  #map {
    height: 500px;
  }
</style>
<script>

// This example creates a simple polygon representing the host city of the 
// Greatest Outdoor Show On Earth.

 function initMap() {
   var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 9,
      center: {lat: 51.039, lng: -114.204},
      mapTypeId: 'terrain'
    });

    // Define the LatLng coordinates for the polygon's path.
    var triangleCoords = [
      {lat: 51.183, lng: -114.234},
      {lat: 51.154, lng: -114.235},
      {lat: 51.156, lng: -114.261},
      {lat: 51.104, lng: -114.259},
      {lat: 51.106, lng: -114.261},
      {lat: 51.102, lng: -114.272},
      {lat: 51.081, lng: -114.271},
      {lat: 51.081, lng: -114.234},
      {lat: 51.009, lng: -114.236},
      {lat: 51.008, lng: -114.141},
      {lat: 50.995, lng: -114.142},
      {lat: 50.998, lng: -114.160},
      {lat: 50.984, lng: -114.163},
      {lat: 50.987, lng: -114.141},
      {lat: 50.979, lng: -114.141},
      {lat: 50.921, lng: -114.141},
      {lat: 50.921, lng: -114.210},
      {lat: 50.893, lng: -114.210},
      {lat: 50.892, lng: -114.140},
      {lat: 50.888, lng: -114.139},
      {lat: 50.878, lng: -114.094},
      {lat: 50.878, lng: -113.994},
      {lat: 50.840, lng: -113.954},
      {lat: 50.854, lng: -113.905},
      {lat: 50.922, lng: -113.906},
      {lat: 50.935, lng: -113.877},
      {lat: 50.943, lng: -113.877},
      {lat: 50.955, lng: -113.912},
      {lat: 51.183, lng: -113.910}
    ];

    // Construct the polygon.
    var bermudaTriangle = new google.maps.Polygon({
      paths: triangleCoords,
      strokeColor: '#FF0000',
      strokeOpacity: 0.8,
      strokeWeight: 2,
      fillColor: '#FF0000',
      fillOpacity: 0.35
    });
    bermudaTriangle.setMap(map);
  }
</script>


<div id="map"></div>
<script async defer src="https://maps.googleapis.com/maps/api/jskey=YOUR_API_KEY&callback=initMap">
</script>

This gets you the outline for Calgary. I've attached an image here.

Which version of C# am I using

To get version of framework - look at version of one of main Assemblies i.e.

 Console.Write(typeof(string).Assembly.ImageRuntimeVersion);

Getting version of C# compiler is somewhat harder, but you should be able to guess version by checking what framework version is used.

If you are using command line compiler (csc.exe) you can check help to see version (also you'd need to know Framework version anyway:

C:\Windows\Microsoft.NET\Framework\v4.0.30319>csc /?
Microsoft (R) Visual C# 2010 Compiler version 4.0.30319.1

Using different Web.config in development and production environment

I'd like to know, too. This helps isolate the problem for me

<connectionStrings configSource="connectionStrings.config"/>

I then keep a connectionStrings.config as well as a "{host} connectionStrings.config". It's still a problem, but if you do this for sections that differ in the two environments, you can deploy and version the same web.config.

(And I don't use VS, btw.)

How to copy Outlook mail message into excel using VBA or Macros

Since you have not mentioned what needs to be copied, I have left that section empty in the code below.

Also you don't need to move the email to the folder first and then run the macro in that folder. You can run the macro on the incoming mail and then move it to the folder at the same time.

This will get you started. I have commented the code so that you will not face any problem understanding it.

First paste the below mentioned code in the outlook module.

Then

  1. Click on Tools~~>Rules and Alerts
  2. Click on "New Rule"
  3. Click on "start from a blank rule"
  4. Select "Check messages When they arrive"
  5. Under conditions, click on "with specific words in the subject"
  6. Click on "specific words" under rules description.
  7. Type the word that you want to check in the dialog box that pops up and click on "add".
  8. Click "Ok" and click next
  9. Select "move it to specified folder" and also select "run a script" in the same box
  10. In the box below, specify the specific folder and also the script (the macro that you have in module) to run.
  11. Click on finish and you are done.

When the new email arrives not only will the email move to the folder that you specify but data from it will be exported to Excel as well.

UNTESTED

Const xlUp As Long = -4162

Sub ExportToExcel(MyMail As MailItem)
    Dim strID As String, olNS As Outlook.Namespace
    Dim olMail As Outlook.MailItem
    Dim strFileName As String

    '~~> Excel Variables
    Dim oXLApp As Object, oXLwb As Object, oXLws As Object
    Dim lRow As Long

    strID = MyMail.EntryID
    Set olNS = Application.GetNamespace("MAPI")
    Set olMail = olNS.GetItemFromID(strID)

    '~~> Establish an EXCEL application object
    On Error Resume Next
    Set oXLApp = GetObject(, "Excel.Application")

    '~~> If not found then create new instance
    If Err.Number <> 0 Then
        Set oXLApp = CreateObject("Excel.Application")
    End If
    Err.Clear
    On Error GoTo 0

    '~~> Show Excel
    oXLApp.Visible = True

    '~~> Open the relevant file
    Set oXLwb = oXLApp.Workbooks.Open("C:\Sample.xls")

    '~~> Set the relevant output sheet. Change as applicable
    Set oXLws = oXLwb.Sheets("Sheet1")

    lRow = oXLws.Range("A" & oXLApp.Rows.Count).End(xlUp).Row + 1

    '~~> Write to outlook
    With oXLws
        '
        '~~> Code here to output data from email to Excel File
        '~~> For example
        '
        .Range("A" & lRow).Value = olMail.Subject
        .Range("B" & lRow).Value = olMail.SenderName
        '
    End With

    '~~> Close and Clean up Excel
    oXLwb.Close (True)
    oXLApp.Quit
    Set oXLws = Nothing
    Set oXLwb = Nothing
    Set oXLApp = Nothing

    Set olMail = Nothing
    Set olNS = Nothing
End Sub

FOLLOWUP

To extract the contents from your email body, you can split it using SPLIT() and then parsing out the relevant information from it. See this example

Dim MyAr() As String

MyAr = Split(olMail.body, vbCrLf)

For i = LBound(MyAr) To UBound(MyAr)
    '~~> This will give you the contents of your email
    '~~> on separate lines
    Debug.Print MyAr(i)
Next i

What is stability in sorting algorithms and why is it important?

Some more examples of the reason for wanting stable sorts. Databases are a common example. Take the case of a transaction data base than includes last|first name, date|time of purchase, item number, price. Say the data base is normally sorted by date|time. Then a query is made to make a sorted copy of the data base by last|first name, since a stable sort preserves the original order, even though the inquiry compare only involves last|first name, the transactions for each last|first name will be in data|time order.

A similar example is classic Excel, which limited sorts to 3 columns at a time. To sort 6 columns, a sort is done with the least significant 3 columns, followed by a sort with the most significant 3 columns.

A classic example of a stable radix sort is a card sorter, used to sort by a field of base 10 numeric columns. The cards are sorted from least significant digit to most significant digit. On each pass, a deck of cards is read and separated into 10 different bins according to the digit in that column. Then the 10 bins of cards are put back into the input hopper in order ("0" cards first, "9" cards last). Then another pass is done by the next column, until all columns are sorted. Actual card sorters have more than 10 bins since there are 12 zones on a card, a column can be blank, and there is a mis-read bin. To sort letters, 2 passes per column are needed, 1st pass for digit, 2nd pass for the 12 11 zone.

Later (1937) there were card collating (merging) machines that could merge two decks of cards by comparing fields. The input was two already sorted decks of cards, a master deck and an update deck. The collator merged the two decks into a a new mater bin and an archive bin, which was optionally used for master duplicates so that the new master bin would only have update cards in case of duplicates. This was probably the basis for the idea behind the original (bottom up) merge sort.

How can I make a link from a <td> table cell

I'd like to make the entire td a hyperlink. I'd prefer without javascript. Is this possible?

That's not possible without javascript. Also, that won't be semantic markup. You should use link instead otherwise it is a matter of attaching onclick handler to <td> to redirect to some other page.

CSS: image link, change on hover

You could do the following, without needing CSS...

<a href="ENTER_DESTINATION_URL"><img src="URL_OF_FIRST_IMAGE_SOURCE" onmouseover="this.src='URL_OF_SECOND_IMAGE_SOURCE'" onmouseout="this.src='URL_OF_FIRST_IMAGE_SOURCE_AGAIN'" /></a>

Example: https://jsfiddle.net/jord8on/k1zsfqyk/

This solution was PERFECT for my needs! I found this solution here.

Disclaimer: Having a solution that is possible without CSS is important to me because I design content on the Jive-x cloud community platform which does not give us access to global CSS.

Find and replace - Add carriage return OR Newline

Just a minor word of warning... a lot of environments use, or need, "\r\n" and not just "\n". I ran into an issue with Visual Studio not matching my regex string at the end of the line because I left off the "\r" of "\r\n", so my string couldn't match with a missing invisible character.

So, if you are doing a find, or a replace, consider the "\r".

For a little more detail on "\r" and "\n", see: https://stackoverflow.com/a/3451192/4427457

How to restart remote MySQL server running on Ubuntu linux?

I SSH'ed into my AWS Lightsail wordpress instance, the following worked: sudo /opt/bitnami/ctlscript.sh restart mysql I learnt this here: https://docs.bitnami.com/aws/infrastructure/mysql/administration/control-services/

How to enumerate a range of numbers starting at 1

>>> list(enumerate(range(1999, 2005)))[1:]
[(1, 2000), (2, 2001), (3, 2002), (4, 2003), (5, 2004)]

How to set cursor to input box in Javascript?

This way sets the focus and cursor to the end of your input:

div.getElementsByTagName("input")[0].focus();
div.getElementsByTagName("input")[0].setSelectionRange(div.getElementsByTagName("input")[0].value.length,div.getElementsByTagName("input")[0].value.length,"forward");

How to show a running progress bar while page is loading

Simple Steps, follow them and i guess it will solve your problem

Include these Css in your page,

.progress {
      position: relative;
      height: 2px;
      display: block;
      width: 100%;
      background-color: white;
      border-radius: 2px;
      background-clip: padding-box;
      /*margin: 0.5rem 0 1rem 0;*/
      overflow: hidden;

    }
    .progress .indeterminate {
background-color:black; }
    .progress .indeterminate:before {
      content: '';
      position: absolute;
      background-color: #2C67B1;
      top: 0;
      left: 0;
      bottom: 0;
      will-change: left, right;
      -webkit-animation: indeterminate 2.1s cubic-bezier(0.65, 0.815, 0.735, 0.395) infinite;
              animation: indeterminate 2.1s cubic-bezier(0.65, 0.815, 0.735, 0.395) infinite; }
    .progress .indeterminate:after {
      content: '';
      position: absolute;
      background-color: #2C67B1;
      top: 0;
      left: 0;
      bottom: 0;
      will-change: left, right;
      -webkit-animation: indeterminate-short 2.1s cubic-bezier(0.165, 0.84, 0.44, 1) infinite;
              animation: indeterminate-short 2.1s cubic-bezier(0.165, 0.84, 0.44, 1) infinite;
      -webkit-animation-delay: 1.15s;
              animation-delay: 1.15s; }

    @-webkit-keyframes indeterminate {
      0% {
        left: -35%;
        right: 100%; }
      60% {
        left: 100%;
        right: -90%; }
      100% {
        left: 100%;
        right: -90%; } }
    @keyframes indeterminate {
      0% {
        left: -35%;
        right: 100%; }
      60% {
        left: 100%;
        right: -90%; }
      100% {
        left: 100%;
        right: -90%; } }
    @-webkit-keyframes indeterminate-short {
      0% {
        left: -200%;
        right: 100%; }
      60% {
        left: 107%;
        right: -8%; }
      100% {
        left: 107%;
        right: -8%; } }
    @keyframes indeterminate-short {
      0% {
        left: -200%;
        right: 100%; }
      60% {
        left: 107%;
        right: -8%; }
      100% {
        left: 107%;
        right: -8%; } }

Then include the progress bar your body tag,

<div class="progress" id="PreLoaderBar">
        <div class="indeterminate"></div>
    </div>

then it will start as your page loads, and now what you have to do is just hide this when the page loads,or set the visibility to none, or hidden, using javascript,

document.onreadystatechange = function () {
            if (document.readyState === "complete") {
                console.log(document.readyState);
                document.getElementById("PreLoaderBar").style.display = "none";
            }
        }

Let me Know if you face any problems and also, you can add any type of progress bar you can easily find them, for this example i have used a indeterminate progress bar.

Java: notify() vs. notifyAll() all over again

I am very surprised that no one mentioned the infamous "lost wakeup" problem (google it).

Basically:

  1. if you have multiple threads waiting on a same condition and,
  2. multiple threads that can make you transition from state A to state B and,
  3. multiple threads that can make you transition from state B to state A (usually the same threads as in 1.) and,
  4. transitioning from state A to B should notify threads in 1.

THEN you should use notifyAll unless you have provable guarantees that lost wakeups are impossible.

A common example is a concurrent FIFO queue where: multiple enqueuers (1. and 3. above) can transition your queue from empty to non-empty multiple dequeuers (2. above) can wait for the condition "the queue is not empty" empty -> non-empty should notify dequeuers

You can easily write an interleaving of operations in which, starting from an empty queue, 2 enqueuers and 2 dequeuers interact and 1 enqueuer will remain sleeping.

This is a problem arguably comparable with the deadlock problem.

check if variable is dataframe

Use isinstance, nothing else:

if isinstance(x, pd.DataFrame):
    ... # do something

PEP8 says explicitly that isinstance is the preferred way to check types

No:  type(x) is pd.DataFrame
No:  type(x) == pd.DataFrame
Yes: isinstance(x, pd.DataFrame)

And don't even think about

if obj.__class__.__name__ = 'DataFrame':
    expect_problems_some_day()

isinstance handles inheritance (see What are the differences between type() and isinstance()?). For example, it will tell you if a variable is a string (either str or unicode), because they derive from basestring)

if isinstance(obj, basestring):
    i_am_string(obj)

Specifically for pandas DataFrame objects:

import pandas as pd
isinstance(var, pd.DataFrame)

Add CSS box shadow around the whole DIV

Yes, don't offset vertically or horizontally, and use a relatively large blur radius: fiddle

Also, you can use multiple box-shadows if you separate them with a comma. This will allow you to fine-tune where they blur and how much they extend. The example I provide is indistinguishable from a large outline, but it can be fine-tuned significantly more: fiddle

You missed the last and most relevant property of box-shadow, which is spread-distance. You can specify a value for how much the shadow expands or contracts (makes my second example obsolete): fiddle

The full property list is:

box-shadow: [horizontal-offset] [vertical-offset] [blur-radius] [spread-distance] [color] inset?

But even better, read through the spec.

How to make PopUp window in java

The same answer : JOptionpane with an example :)

package experiments;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class CreateDialogFromOptionPane {

    public static void main(final String[] args) {
        final JFrame parent = new JFrame();
        JButton button = new JButton();

        button.setText("Click me to show dialog!");
        parent.add(button);
        parent.pack();
        parent.setVisible(true);

        button.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                String name = JOptionPane.showInputDialog(parent,
                        "What is your name?", null);
            }
        });
    }
}

enter image description here

Wait until page is loaded with Selenium WebDriver for Python

Trying to pass find_element_by_id to the constructor for presence_of_element_located (as shown in the accepted answer) caused NoSuchElementException to be raised. I had to use the syntax in fragles' comment:

from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

driver = webdriver.Firefox()
driver.get('url')
timeout = 5
try:
    element_present = EC.presence_of_element_located((By.ID, 'element_id'))
    WebDriverWait(driver, timeout).until(element_present)
except TimeoutException:
    print "Timed out waiting for page to load"

This matches the example in the documentation. Here is a link to the documentation for By.

Check number of arguments passed to a Bash script

It might be a good idea to use arithmetic expressions if you're dealing with numbers.

if (( $# != 1 )); then
    >&2 echo "Illegal number of parameters"
fi

>&2 is used to write the error message to stderr.

How to stop/terminate a python script from running?

Ctrl-Break it is more powerful than Ctrl-C

How to set css style to asp.net button?

You could just style the input element in your css file. That is then independent of ASP.NET.

<form action="">
    Name: <input type="text" class="input" />
    Password: <input type="password" class="input" />
    <input type="submit" value="Submit" class="button" />
</form>
CSS
.input {
    border: 1px solid #006;
    background: #ffc;
}
.button {
    border: 1px solid #006;
    background: #9cf;
}

With the CssClass you can assign the "input" class to it.

How can I represent 'Authorization: Bearer <token>' in a Swagger Spec (swagger.json)

Maybe this can help:

swagger: '2.0'
info:
  version: 1.0.0
  title: Based on "Basic Auth Example"
  description: >
    An example for how to use Auth with Swagger.

host: basic-auth-server.herokuapp.com
schemes:
  - http
  - https
securityDefinitions:
  Bearer:
    type: apiKey
    name: Authorization
    in: header
paths:
  /:
    get:
      security:
        - Bearer: []
      responses:
        '200':
          description: 'Will send `Authenticated`'
        '403': 
          description: 'You do not have necessary permissions for the resource'

You can copy&paste it out here: http://editor.swagger.io/#/ to check out the results.

There are also several examples in the swagger editor web with more complex security configurations which could help you.

good postgresql client for windows?

SQLExplorer is a great Eclipse plugin or standalone interface that works with many different database systems, either with dedicated drivers or with ODBC.

What's the difference of $host and $http_host in Nginx

$host is a variable of the Core module.

$host

This variable is equal to line Host in the header of request or name of the server processing the request if the Host header is not available.

This variable may have a different value from $http_host in such cases: 1) when the Host input header is absent or has an empty value, $host equals to the value of server_name directive; 2)when the value of Host contains port number, $host doesn't include that port number. $host's value is always lowercase since 0.8.17.

$http_host is also a variable of the same module but you won't find it with that name because it is defined generically as $http_HEADER (ref).

$http_HEADER

The value of the HTTP request header HEADER when converted to lowercase and with 'dashes' converted to 'underscores', e.g. $http_user_agent, $http_referer...;


Summarizing:

  • $http_host equals always the HTTP_HOST request header.
  • $host equals $http_host, lowercase and without the port number (if present), except when HTTP_HOST is absent or is an empty value. In that case, $host equals the value of the server_name directive of the server which processed the request.

Docker CE on RHEL - Requires: container-selinux >= 2.9

Docker CE is not supported on RHEL. Any way you are trying to get around that is not a supported way. You can see the supported platforms in the Docker Documentation. I suggest you either use a supported OS, or switch to Enterprise Edition.

How to handle :java.util.concurrent.TimeoutException: android.os.BinderProxy.finalize() timed out after 10 seconds errors?

We see this constantly, all over our app, using Crashlytics. The crash usually happens way down in platform code. A small sampling:

android.database.CursorWindow.finalize() timed out after 10 seconds

java.util.regex.Matcher.finalize() timed out after 10 seconds

android.graphics.Bitmap$BitmapFinalizer.finalize() timed out after 10 seconds

org.apache.http.impl.conn.SingleClientConnManager.finalize() timed out after 10 seconds

java.util.concurrent.ThreadPoolExecutor.finalize() timed out after 10 seconds

android.os.BinderProxy.finalize() timed out after 10 seconds

android.graphics.Path.finalize() timed out after 10 seconds

The devices on which this happens are overwhelmingly (but not exclusively) devices manufactured by Samsung. That could just mean that most of our users are using Samsung devices; alternately it could indicate a problem with Samsung devices. I'm not really sure.

I suppose this doesn't really answer your questions, but I just wanted to reinforce that this seems quite common, and is not specific to your application.

How are VST Plugins made?

I wrote up a HOWTO for VST development on C++ with Visual Studio awhile back which details the steps necessary to create a basic plugin for the Windows platform (the Mac version of this article is forthcoming). On Windows, a VST plugin is just a normal DLL, but there are a number of "gotchas", and you need to build the plugin using some specific compiler/linker switches or else it won't be recognized by some hosts.

As for the Mac, a VST plugin is just a bundle with the .vst extension, though there are also a few settings which must be configured correctly in order to generate a valid plugin. You can also download a set of Xcode VST plugin project templates I made awhile back which can help you to write a working plugin on that platform.

As for AudioUnits, Apple has provided their own project templates which are included with Xcode. Apple also has very good tutorials and documentation online:

I would also highly recommend checking out the Juce Framework, which has excellent support for creating cross-platform VST/AU plugins. If you're going open-source, then Juce is a no-brainer, but you will need to pay licensing fees for it if you plan on releasing your work without source code.

Simple two column html layout without using tables

You can create text columns with CSS Multiple Columns property. You don't need any table or multiple divs.

HTML

<div class="column">
       <!-- paragraph text comes here -->
</div> 

CSS

.column {
    column-count: 2;
    column-gap: 40px;
}

Read more about CSS Multiple Columns at https://www.w3schools.com/css/css3_multiple_columns.asp

How to access html form input from asp.net code behind

It should normally be done with Request.Form["elementName"].

For example, if you have <input type="text" name="email" /> then you can use Request.Form["email"] to access its value.