Programs & Examples On #Backing field

How to sort with lambda in Python

Use

a = sorted(a, key=lambda x: x.modified, reverse=True)
#             ^^^^

On Python 2.x, the sorted function takes its arguments in this order:

sorted(iterable, cmp=None, key=None, reverse=False)

so without the key=, the function you pass in will be considered a cmp function which takes 2 arguments.

How to access the correct `this` inside a callback?

Currently there is another approach possible if classes are used in code.

With support of class fields it's possible to make it next way:

class someView {
    onSomeInputKeyUp = (event) => {
        console.log(this); // this refers to correct value
    // ....
    someInitMethod() {
        //...
        someInput.addEventListener('input', this.onSomeInputKeyUp)

For sure under the hood it's all old good arrow function that bind context but in this form it looks much more clear that explicit binding.

Since it's Stage 3 Proposal you will need babel and appropriate babel plugin to process it as for now(08/2018).

Composer require runs out of memory. PHP Fatal error: Allowed memory size of 1610612736 bytes exhausted

go and find php.ini inside you PHP directory incase of xampp it will be inside xampp/PHP and inside php.ini file update memory_limit:512M to 2048M

How can I get the source code of a Python function?

Since this post is marked as the duplicate of this other post, I answer here for the "lambda" case, although the OP is not about lambdas.

So, for lambda functions that are not defined in their own lines: in addition to marko.ristin's answer, you may wish to use mini-lambda or use SymPy as suggested in this answer.

  • mini-lambda is lighter and supports any kind of operation, but works only for a single variable
  • SymPy is heavier but much more equipped with mathematical/calculus operations. In particular it can simplify your expressions. It also supports several variables in the same expression.

Here is how you can do it using mini-lambda:

from mini_lambda import x, is_mini_lambda_expr
import inspect

def get_source_code_str(f):
    if is_mini_lambda_expr(f):
        return f.to_string()
    else:
        return inspect.getsource(f)

# test it

def foo(arg1, arg2):
    # do something with args
    a = arg1 + arg2
    return a

print(get_source_code_str(foo))
print(get_source_code_str(x ** 2))

It correctly yields

def foo(arg1, arg2):
    # do something with args
    a = arg1 + arg2
    return a

x ** 2

See mini-lambda documentation for details. I'm the author by the way ;)

jQuery Validation plugin: disable validation for specified submit buttons

Here is the simplest version, hope it helps someone,

$('#cancel-button').click(function() {
    var $form = $(this).closest('form');
    $form.find('*[data-validation]').attr('data-validation', null);
    $form.get(0).submit();
});

How to specify an element after which to wrap in css flexbox?

There is part of the spec that sure sounds like this... right in the "flex layout algorithm" and "main sizing" sections:

Otherwise, starting from the first uncollected item, collect consecutive items one by one until the first time that the next collected item would not fit into the flex container’s inner main size, or until a forced break is encountered. If the very first uncollected item wouldn’t fit, collect just it into the line. A break is forced wherever the CSS2.1 page-break-before/page-break-after [CSS21] or the CSS3 break-before/break-after [CSS3-BREAK] properties specify a fragmentation break.

From http://www.w3.org/TR/css-flexbox-1/#main-sizing

It sure sounds like (aside from the fact that page-breaks ought to be for printing), when laying out a potentially multi-line flex layout (which I take from another portion of the spec is one without flex-wrap: nowrap) a page-break-after: always or break-after: always should cause a break, or wrap to the next line.

.flex-container {
  display: flex;
  flex-flow: row wrap;
}

.child {
  flex-grow: 1;
}

.child.break-here {
  page-break-after: always;
  break-after: always;
}

However, I have tried this and it hasn't been implemented that way in...

  • Safari (up to 7)
  • Chrome (up to 43 dev)
  • Opera (up to 28 dev & 12.16)
  • IE (up to 11)

It does work the way it sounds (to me, at least) like in:

  • Firefox (28+)

Sample at http://codepen.io/morewry/pen/JoVmVj.

I didn't find any other requests in the bug tracker, so I reported it at https://code.google.com/p/chromium/issues/detail?id=473481.

But the topic took to the mailing list and, regardless of how it sounds, that's not what apparently they meant to imply, except I guess for pagination. So there's no way to wrap before or after a particular box in flex layout without nesting successive flex layouts inside flex children or fiddling with specific widths (e.g. flex-basis: 100%).

This is deeply annoying, of course, since working with the Firefox implementation confirms my suspicion that the functionality is incredibly useful. Aside from the improved vertical alignment, the lack obviates a good deal of the utility of flex layout in numerous scenarios. Having to add additional wrapping tags with nested flex layouts to control the point at which a row wraps increases the complexity of both the HTML and CSS and, sadly, frequently renders order useless. Similarly, forcing the width of an item to 100% reduces the "responsive" potential of the flex layout or requires a lot of highly specific queries or count selectors (e.g. the techniques that may accomplish the general result you need that are mentioned in the other answers).

At least floats had clear. Something may get added at some point or another for this, one hopes.

Get the second largest number in a list in linear time

This can be done in [N + log(N) - 2] time, which is slightly better than the loose upper bound of 2N (which can be thought of O(N) too).

The trick is to use binary recursive calls and "tennis tournament" algorithm. The winner (the largest number) will emerge after all the 'matches' (takes N-1 time), but if we record the 'players' of all the matches, and among them, group all the players that the winner has beaten, the second largest number will be the largest number in this group, i.e. the 'losers' group.

The size of this 'losers' group is log(N), and again, we can revoke the binary recursive calls to find the largest among the losers, which will take [log(N) - 1] time. Actually, we can just linearly scan the losers group to get the answer too, the time budget is the same.

Below is a sample python code:

def largest(L):
    global paris
    if len(L) == 1:
        return L[0]
    else:
        left = largest(L[:len(L)//2])
        right = largest(L[len(L)//2:])
        pairs.append((left, right))
        return max(left, right)

def second_largest(L):
    global pairs
    biggest = largest(L)
    second_L = [min(item) for item in pairs if biggest in item]

    return biggest, largest(second_L)  



if __name__ == "__main__":
    pairs = []
    # test array
    L = [2,-2,10,5,4,3,1,2,90,-98,53,45,23,56,432]    

    if len(L) == 0:
        first, second = None, None
    elif len(L) == 1:
        first, second = L[0], None
    else:
        first, second = second_largest(L)

    print('The largest number is: ' + str(first))
    print('The 2nd largest number is: ' + str(second))

Python using enumerate inside list comprehension

Here's a way to do it:

>>> mylist = ['a', 'b', 'c', 'd']
>>> [item for item in enumerate(mylist)]
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]

Alternatively, you can do:

>>> [(i, j) for i, j in enumerate(mylist)]
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]

The reason you got an error was that you were missing the () around i and j to make it a tuple.

Difference between require, include, require_once and include_once?

one thing I noticed, when using include I can only access the included files functions from the file that included it. With require_once, I can run that function in a second required_once file.

also: I recommend adding

if(file_exists($RequiredFile)){
    require_once($RequiredFile);
}else{
  die('Error: File Does Not Exist');
}

Because when require_once kills the page, it can sometimes echo the directory of your website files

Here's a custom function I made to require files:

function addFile($file, $type = 'php', $important=false){
    //site-content is a directory where I store all the files that I plan to require_once
    //the site-content directory has "deny from all" in its .htaccess file to block direct connections
    if($type && file_exists('site-content/'.$file.'.'.$type) && !is_dir('site-content/'.$file.'.'.$type)){
        //!is_dir checks that the file is not a folder
        require_once('site-content/'.$file.'.'.$type);
        return 'site-content/'.$file.'.'.$type;
    }else if(!$type && file_exists('site-content/'.$file) && !is_dir('site-content/'.$file)){
        //if you set "$type=false" you can add the file type (.php, .ect) to the end of the "$file" (useful for requiring files named after changing vars)
        require_once('site-content/'.$file);
        return 'site-content/'.$file;
    }else if($important){
        //if you set $important to true, the function will kill the page (which also prevents accidentally echoing the main directory path of the server)
        die('Server Error: Files Missing');
        return false;
    }else{
        //the function returns false if the file does not exist, so you can check if your functions were successfully added
        return false;
    }
}

usage example:

$success = addFile('functions/common');

if($success){
    commonFunction();
}else{
    fallbackFunction();
}

Could not load type 'System.Runtime.CompilerServices.ExtensionAttribute' from assembly 'mscorlib

I had this problem, except the type it couldn't load was System.Reflection.AssemblyMetadataAttribute. The web application was built on a machine with .NET 4.5 installed (runs fine there), with 4.0 as the target framework, but the error presented itself when it was run on a web server with only 4.0 installed. I then tried it on a web server with 4.5 installed and there was no error. So, as others have said, this is all due to the screwy way Microsoft released 4.5, which basically is an upgrade to (and overwrite of) version 4.0. The System.Reflection assembly references a type that doesn't exist in 4.0 (AssemblyMetadataAttribute) so it will fail if you don't have the new System.Reflection.dll.

You can either install .NET 4.5 on the target web server, or build the application on a machine that does not have 4.5 installed. Far from an ideal resolution.

REST API Login Pattern

TL;DR Login for each request is not a required component to implement API security, authentication is.

It is hard to answer your question about login without talking about security in general. With some authentication schemes, there's no traditional login.

REST does not dictate any security rules, but the most common implementation in practice is OAuth with 3-way authentication (as you've mentioned in your question). There is no log-in per se, at least not with each API request. With 3-way auth, you just use tokens.

  1. User approves API client and grants permission to make requests in the form of a long-lived token
  2. Api client obtains a short-lived token by using the long-lived one.
  3. Api client sends the short-lived token with each request.

This scheme gives the user the option to revoke access at any time. Practially all publicly available RESTful APIs I've seen use OAuth to implement this.

I just don't think you should frame your problem (and question) in terms of login, but rather think about securing the API in general.

For further info on authentication of REST APIs in general, you can look at the following resources:

Binding a generic list to a repeater - ASP.NET

You may want to create a subRepeater.

<asp:Repeater ID="SubRepeater" runat="server" DataSource='<%# Eval("Fields") %>'>
  <ItemTemplate>
    <span><%# Eval("Name") %></span>
  </ItemTemplate>
</asp:Repeater>

You can also cast your fields

<%# ((ArrayFields)Container.DataItem).Fields[0].Name %>

Finally you could do a little CSV Function and write out your fields with a function

<%# GetAsCsv(((ArrayFields)Container.DataItem).Fields) %>

public string GetAsCsv(IEnumerable<Fields> fields)
{
  var builder = new StringBuilder();
  foreach(var f in fields)
  {
    builder.Append(f);
    builder.Append(",");
  }
  builder.Remove(builder.Length - 1);
  return builder.ToString();
}

Python PDF library

The two that come to mind are:

How to dump a table to console?

I have humbly modified a bit Alundaio code:

-- by Alundaio
-- KK modified 11/28/2019

function dump_table_to_string(node, tree, indentation)
    local cache, stack, output = {},{},{}
    local depth = 1


    if type(node) ~= "table" then
        return "only table type is supported, got " .. type(node)
    end

    if nil == indentation then indentation = 1 end

    local NEW_LINE = "\n"
    local TAB_CHAR = " "

    if nil == tree then
        NEW_LINE = "\n"
    elseif not tree then
        NEW_LINE = ""
        TAB_CHAR = ""
    end

    local output_str = "{" .. NEW_LINE

    while true do
        local size = 0
        for k,v in pairs(node) do
            size = size + 1
        end

        local cur_index = 1
        for k,v in pairs(node) do
            if (cache[node] == nil) or (cur_index >= cache[node]) then

                if (string.find(output_str,"}",output_str:len())) then
                    output_str = output_str .. "," .. NEW_LINE
                elseif not (string.find(output_str,NEW_LINE,output_str:len())) then
                    output_str = output_str .. NEW_LINE
                end

                -- This is necessary for working with HUGE tables otherwise we run out of memory using concat on huge strings
                table.insert(output,output_str)
                output_str = ""

                local key
                if (type(k) == "number" or type(k) == "boolean") then
                    key = "["..tostring(k).."]"
                else
                    key = "['"..tostring(k).."']"
                end

                if (type(v) == "number" or type(v) == "boolean") then
                    output_str = output_str .. string.rep(TAB_CHAR,depth*indentation) .. key .. " = "..tostring(v)
                elseif (type(v) == "table") then
                    output_str = output_str .. string.rep(TAB_CHAR,depth*indentation) .. key .. " = {" .. NEW_LINE
                    table.insert(stack,node)
                    table.insert(stack,v)
                    cache[node] = cur_index+1
                    break
                else
                    output_str = output_str .. string.rep(TAB_CHAR,depth*indentation) .. key .. " = '"..tostring(v).."'"
                end

                if (cur_index == size) then
                    output_str = output_str .. NEW_LINE .. string.rep(TAB_CHAR,(depth-1)*indentation) .. "}"
                else
                    output_str = output_str .. ","
                end
            else
                -- close the table
                if (cur_index == size) then
                    output_str = output_str .. NEW_LINE .. string.rep(TAB_CHAR,(depth-1)*indentation) .. "}"
                end
            end

            cur_index = cur_index + 1
        end

        if (size == 0) then
            output_str = output_str .. NEW_LINE .. string.rep(TAB_CHAR,(depth-1)*indentation) .. "}"
        end

        if (#stack > 0) then
            node = stack[#stack]
            stack[#stack] = nil
            depth = cache[node] == nil and depth + 1 or depth - 1
        else
            break
        end
    end

    -- This is necessary for working with HUGE tables otherwise we run out of memory using concat on huge strings
    table.insert(output,output_str)
    output_str = table.concat(output)

    return output_str

end

then:

print(dump_table_to_string("AA", true,3))

print(dump_table_to_string({"AA","BB"}, true,3))

print(dump_table_to_string({"AA","BB"}))

print(dump_table_to_string({"AA","BB"},false))

print(dump_table_to_string({"AA","BB",{22,33}},true,2))

gives:

only table type is supported, got string

{
   [1] = 'AA',
   [2] = 'BB'
}

{
 [1] = 'AA',
 [2] = 'BB'
}

{[1] = 'AA',[2] = 'BB'}

{
  [1] = 'AA',
  [2] = 'BB',
  [3] = {
    [1] = 22,
    [2] = 33
  }
}

Where does Internet Explorer store saved passwords?

Short answer: in the Vault. Since Windows 7, a Vault was created for storing any sensitive data among it the credentials of Internet Explorer. The Vault is in fact a LocalSystem service - vaultsvc.dll.

Long answer: Internet Explorer allows two methods of credentials storage: web sites credentials (for example: your Facebook user and password) and autocomplete data. Since version 10, instead of using the Registry a new term was introduced: Windows Vault. Windows Vault is the default storage vault for the credential manager information.

You need to check which OS is running. If its Windows 8 or greater, you call VaultGetItemW8. If its isn't, you call VaultGetItemW7.

To use the "Vault", you load a DLL named "vaultcli.dll" and access its functions as needed.

A typical C++ code will be:

hVaultLib = LoadLibrary(L"vaultcli.dll");

if (hVaultLib != NULL) 
{
    pVaultEnumerateItems = (VaultEnumerateItems)GetProcAddress(hVaultLib, "VaultEnumerateItems");
    pVaultEnumerateVaults = (VaultEnumerateVaults)GetProcAddress(hVaultLib, "VaultEnumerateVaults");
    pVaultFree = (VaultFree)GetProcAddress(hVaultLib, "VaultFree");
    pVaultGetItemW7 = (VaultGetItemW7)GetProcAddress(hVaultLib, "VaultGetItem");
    pVaultGetItemW8 = (VaultGetItemW8)GetProcAddress(hVaultLib, "VaultGetItem");
    pVaultOpenVault = (VaultOpenVault)GetProcAddress(hVaultLib, "VaultOpenVault");
    pVaultCloseVault = (VaultCloseVault)GetProcAddress(hVaultLib, "VaultCloseVault");

    bStatus = (pVaultEnumerateVaults != NULL)
        && (pVaultFree != NULL)
        && (pVaultGetItemW7 != NULL)
        && (pVaultGetItemW8 != NULL)
        && (pVaultOpenVault != NULL)
        && (pVaultCloseVault != NULL)
        && (pVaultEnumerateItems != NULL);
}

Then you enumerate all stored credentials by calling

VaultEnumerateVaults

Then you go over the results.

Example of AES using Crypto++

Official document of Crypto++ AES is a good start. And from my archive, a basic implementation of AES is as follows:

Please refer here with more explanation, I recommend you first understand the algorithm and then try to understand each line step by step.

#include <iostream>
#include <iomanip>

#include "modes.h"
#include "aes.h"
#include "filters.h"

int main(int argc, char* argv[]) {

    //Key and IV setup
    //AES encryption uses a secret key of a variable length (128-bit, 196-bit or 256-   
    //bit). This key is secretly exchanged between two parties before communication   
    //begins. DEFAULT_KEYLENGTH= 16 bytes
    CryptoPP::byte key[ CryptoPP::AES::DEFAULT_KEYLENGTH ], iv[ CryptoPP::AES::BLOCKSIZE ];
    memset( key, 0x00, CryptoPP::AES::DEFAULT_KEYLENGTH );
    memset( iv, 0x00, CryptoPP::AES::BLOCKSIZE );

    //
    // String and Sink setup
    //
    std::string plaintext = "Now is the time for all good men to come to the aide...";
    std::string ciphertext;
    std::string decryptedtext;

    //
    // Dump Plain Text
    //
    std::cout << "Plain Text (" << plaintext.size() << " bytes)" << std::endl;
    std::cout << plaintext;
    std::cout << std::endl << std::endl;

    //
    // Create Cipher Text
    //
    CryptoPP::AES::Encryption aesEncryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
    CryptoPP::CBC_Mode_ExternalCipher::Encryption cbcEncryption( aesEncryption, iv );

    CryptoPP::StreamTransformationFilter stfEncryptor(cbcEncryption, new CryptoPP::StringSink( ciphertext ) );
    stfEncryptor.Put( reinterpret_cast<const unsigned char*>( plaintext.c_str() ), plaintext.length() );
    stfEncryptor.MessageEnd();

    //
    // Dump Cipher Text
    //
    std::cout << "Cipher Text (" << ciphertext.size() << " bytes)" << std::endl;

    for( int i = 0; i < ciphertext.size(); i++ ) {

        std::cout << "0x" << std::hex << (0xFF & static_cast<CryptoPP::byte>(ciphertext[i])) << " ";
    }

    std::cout << std::endl << std::endl;

    //
    // Decrypt
    //
    CryptoPP::AES::Decryption aesDecryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
    CryptoPP::CBC_Mode_ExternalCipher::Decryption cbcDecryption( aesDecryption, iv );

    CryptoPP::StreamTransformationFilter stfDecryptor(cbcDecryption, new CryptoPP::StringSink( decryptedtext ) );
    stfDecryptor.Put( reinterpret_cast<const unsigned char*>( ciphertext.c_str() ), ciphertext.size() );
    stfDecryptor.MessageEnd();

    //
    // Dump Decrypted Text
    //
    std::cout << "Decrypted Text: " << std::endl;
    std::cout << decryptedtext;
    std::cout << std::endl << std::endl;

    return 0;
}

For installation details :

sudo apt-get install libcrypto++-dev libcrypto++-doc libcrypto++-utils

jQuery ajax post file field

Try this...

<script type="text/javascript">
      $("#form_oferta").submit(function(event) 
      {
           var myData = $( form ).serialize(); 
           $.ajax({
                type: "POST", 
                contentType:attr( "enctype", "multipart/form-data" ),
                url: " URL Goes Here ",  
                data: myData,  
                success: function( data )  
                {
                     alert( data );
                }
           });
           return false;  
      });
</script>

Here the contentType is specified as multipart/form-data as we do in the form tag, this will work to upload simple file On server side you just need to write simple file upload code to handle this request with echoing message you want to show to user as a response.

Hashing a dictionary?

Answers from this thread with the highest upvotes didn't work for me as their hashing functions give different results on different machines due to PYTHOPYTHONHASHSEED.

I adjusted all the hints from this thread and came up with a solution that works for me.

import collections
import hashlib
import json


def simplify_object(o):
    if isinstance(o, dict):
        ordered_dict = collections.OrderedDict(sorted(o.items()))
        for k, v in ordered_dict.items():
            v = simplify_object(v)
            ordered_dict[str(k)] = v
        o = ordered_dict
    elif isinstance(o, (list, tuple, set)):
        o = [simplify_object(el) for el in o]
    else:
        o = str(o).strip()
    return o


def make_hash(o):
    o = simplify_object(o)
    bytes_val = json.dumps(o, sort_keys=True, ensure_ascii=True, default=str)
    hash_val = hashlib.sha1(bytes_val.encode()).hexdigest()
    return hash_val

How can the default node version be set using NVM?

#Worked for me 100% Follow this for default node version:

nvm install 12.13.1 then, nvm alias default 12.13.1

How to parse a String containing XML in Java and retrieve the value of the root node?

One of the above answer states to convert XML String to bytes which is not needed. Instead you can can use InputSource and supply it with StringReader.

String xmlStr = "<message>HELLO!</message>";
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = db.parse(new InputSource(new StringReader(xmlStr)));
System.out.println(doc.getFirstChild().getNodeValue());

Right way to reverse a pandas DataFrame?

One way to do this if dealing with sorted range index is:

data = data.sort_index(ascending=False)

This approach has the benefits of (1) being a single line, (2) not requiring a utility function, and most importantly (3) not actually changing any of the data in the dataframe.

Caveat: this works by sorting the index in descending order and so may not always be appropriate or generalize for any given Dataframe.

"Expected an indented block" error?

I also experienced that for example:

This code doesnt work and get the intended block error.

class Foo(models.Model):
title = models.CharField(max_length=200)
body = models.TextField()
pub_date = models.DateTimeField('date published')
likes = models.IntegerField()

def __unicode__(self):
return self.title

However, when i press tab before typing return self.title statement, the code works.

class Foo(models.Model):
title = models.CharField(max_length=200)
body = models.TextField()
pub_date = models.DateTimeField('date published')
likes = models.IntegerField()

def __unicode__(self):
    return self.title

Hope, this will help others.

How to get index in Handlebars each helper?

This has changed in the newer versions of Ember.

For arrays:

{{#each array}}
    {{_view.contentIndex}}: {{this}}
{{/each}}

It looks like the #each block no longer works on objects. My suggestion is to roll your own helper function for it.

Thanks for this tip.

C++ Redefinition Header Files (winsock2.h)

This problem is caused when including <windows.h> before <winsock2.h>. Try arrange your include list that <windows.h> is included after <winsock2.h> or define _WINSOCKAPI_ first:

#define _WINSOCKAPI_    // stops windows.h including winsock.h
#include <windows.h>
// ...
#include "MyClass.h"    // Which includes <winsock2.h>

See also this.

How to add an extra column to a NumPy array

In my case, I had to add a column of ones to a NumPy array

X = array([ 6.1101, 5.5277, ... ])
X.shape => (97,)
X = np.concatenate((np.ones((m,1), dtype=np.int), X.reshape(m,1)), axis=1)

After X.shape => (97, 2)

array([[ 1. , 6.1101],
       [ 1. , 5.5277],
...

How to set page content to the middle of screen?

I'm guessing you want to center the box both vertically and horizontally, regardless of browser window size. Since you have a fixed width and height for the box, this should work:

Markup:

<div></div>

CSS:

div {
    height: 200px;
    width: 400px;
    background: black;

    position: fixed;
    top: 50%;
    left: 50%;
    margin-top: -100px;
    margin-left: -200px;
}

The div should remain in the center of the screen even if you resize the browser. Just replace the margin-top and margin-left with half of the height and width of your table.

Edit: Credit goes to CSS-Tricks, where I got the original idea.

Write to Windows Application Event Log

You can using the EventLog class, as explained on How to: Write to the Application Event Log (Visual C#):

var appLog = new EventLog("Application");
appLog.Source = "MySource";
appLog.WriteEntry("Test log message");

However, you'll need to configure this source "MySource" using administrative privileges:

Use WriteEvent and WriteEntry to write events to an event log. You must specify an event source to write events; you must create and configure the event source before writing the first entry with the source.

Run all SQL files in a directory

Create a .BAT file with the following command:

for %%G in (*.sql) do sqlcmd /S servername /d databaseName -E -i"%%G"
pause

If you need to provide username and passsword

for %%G in (*.sql) do sqlcmd /S servername /d databaseName -U username -P 
password -i"%%G"

Note that the "-E" is not needed when user/password is provided

Place this .BAT file in the directory from which you want the .SQL files to be executed, double click the .BAT file and you are done!

How to default to other directory instead of home directory

it must be cd d:/work_space_for_....

without the : it doesn't work for me

Can I set up HTML/Email Templates with ASP.NET?

Sure you can create an html template and I would recommend also a text template. In the template you can just put [BODY] in the place where the body would be placed and then you can just read in the template and replace the body with the new content. You can send the email using .Nets Mail Class. You just have to loop through the sending of the email to all recipients after you create the email initially. Worked like a charm for me.

using System.Net.Mail;

// Email content
string HTMLTemplatePath = @"path";
string TextTemplatePath = @"path";
string HTMLBody = "";
string TextBody = "";

HTMLBody = File.ReadAllText(HTMLTemplatePath);
TextBody = File.ReadAllText(TextTemplatePath);

HTMLBody = HTMLBody.Replace(["[BODY]", content);
TextBody = HTMLBody.Replace(["[BODY]", content);

// Create email code
MailMessage m = new MailMessage();

m.From = new MailAddress("[email protected]", "display name");
m.To.Add("[email protected]");
m.Subject = "subject";

AlternateView plain = AlternateView.CreateAlternateViewFromString(_EmailBody + text, new System.Net.Mime.ContentType("text/plain"));
AlternateView html = AlternateView.CreateAlternateViewFromString(_EmailBody + body, new System.Net.Mime.ContentType("text/html"));
mail.AlternateViews.Add(plain);
mail.AlternateViews.Add(html);

SmtpClient smtp = new SmtpClient("server");
smtp.Send(m);

java.lang.NoClassDefFoundError:failed resolution of :Lorg/apache/http/ProtocolVersion

This link android-9.0-changes-28-->Apache HTTP client deprecation explains reason for adding the following to your AndroidManifest.xml:

<uses-library android:name="org.apache.http.legacy" android:required="false"/>

With Android 6.0, we removed support for the Apache HTTP client. Beginning with Android 9, that library is removed from the bootclasspath and is not available to apps by default.

The endpoint reference (EPR) for the Operation not found is

On Websphere Application Server, in the same situation, it helped deleting the Temp folders while the server was stopped.

I ran into the situation when the package of the service changed.

Real differences between "java -server" and "java -client"?

Last time I had a look at this, (and admittedly it was a while back) the biggest difference I noticed was in the garbage collection.

IIRC:

  • The server heap VM has a differnt number of generations than the Client VM, and a different garbage collection algorithm. This may not be true anymore
  • The server VM will allocate memory and not release it to the OS
  • The server VM will use more sophisticated optimisation algorithms, and hence have bigger time and memory requirements for optimisation

If you can compare two java VMs, one client, one server using the jvisualvm tool, you should see a difference in the frequency and effect of the garbage collection, as well as in the number of generations.

I had a pair of screenshots that showed the difference really well, but I can't reproduce as I have a 64 bit JVM which only implements the server VM. (And I can't be bothered to download and wrangle the 32 bit version on my system as well.)

This doesn't seem to be the case anymore, having tried running some code on windows with both server and client VMs, I seem to get the same generation model for both...

Show popup after page load

    <script type="text/javascript">
        $(window).on('load',function(){
            setTimeout(function(){ alert(" //show popup"); }, 5000); 
        });
    </script>

Get last 30 day records from today date in SQL Server

Below query is appropriate for the last 30 days records

Here, I have used a review table and review_date is a column from the review table

SELECT * FROM reviews WHERE DATE(review_date) >= DATE(NOW()) - INTERVAL 30 DAY

Get the client's IP address in socket.io

In socket.io 2.0: you can use:

socket.conn.transport.socket._socket.remoteAddress

works with transports: ['websocket']

I need to get all the cookies from the browser

You cannot. By design, for security purpose, you can access only the cookies set by your site. StackOverflow can't see the cookies set by UserVoice nor those set by Amazon.

How to overload functions in javascript?

How about using spread operator as a parameter? The same block can be called with Multiple parameters. All the parameters are added into an array and inside the method you can loop in based on the length.

    function mName(...opt){
        console.log(opt); 
    }
    mName(1,2,3,4); //[1,2,3,4]
    mName(1,2,3); //[1,2,3]

Could not open input file: composer.phar

I was trying to install YII 2.0

php composer.phar create-project yiisoft/yii2-app-advanced advanced 2.0.0-alpha

I got the same error:

Could not open input file: composer.phar

Then i gave the full path of .phar like this:

php C:\ProgramData\Composer\bin\composer.phar create-project yiisoft/yii2-app-advanced advanced 2.0.0-alpha

and it worked.

How do I pipe or redirect the output of curl -v?

If you need the output in a file you can use a redirect:

curl https://vi.stackexchange.com/ -vs >curl-output.txt 2>&1

Please be sure not to flip the >curl-output.txt and 2>&1, which will not work due to bash's redirection behavior.

Limit the height of a responsive image with css

The trick is to add both max-height: 100%; and max-width: 100%; to .container img. Example CSS:

.container {
  width: 300px;
  border: dashed blue 1px;
}

.container img {
  max-height: 100%;
  max-width: 100%;
}

In this way, you can vary the specified width of .container in whatever way you want (200px or 10% for example), and the image will be no larger than its natural dimensions. (You could specify pixels instead of 100% if you didn't want to rely on the natural size of the image.)

Here's the whole fiddle: http://jsfiddle.net/KatieK/Su28P/1/

Filter dataframe rows if value in column is in a set list of values

isin() is ideal if you have a list of exact matches, but if you have a list of partial matches or substrings to look for, you can filter using the str.contains method and regular expressions.

For example, if we want to return a DataFrame where all of the stock IDs which begin with '600' and then are followed by any three digits:

>>> rpt[rpt['STK_ID'].str.contains(r'^600[0-9]{3}$')] # ^ means start of string
...   STK_ID   ...                                    # [0-9]{3} means any three digits
...  '600809'  ...                                    # $ means end of string
...  '600141'  ...
...  '600329'  ...
...      ...   ...

Suppose now we have a list of strings which we want the values in 'STK_ID' to end with, e.g.

endstrings = ['01$', '02$', '05$']

We can join these strings with the regex 'or' character | and pass the string to str.contains to filter the DataFrame:

>>> rpt[rpt['STK_ID'].str.contains('|'.join(endstrings)]
...   STK_ID   ...
...  '155905'  ...
...  '633101'  ...
...  '210302'  ...
...      ...   ...

Finally, contains can ignore case (by setting case=False), allowing you to be more general when specifying the strings you want to match.

For example,

str.contains('pandas', case=False)

would match PANDAS, PanDAs, paNdAs123, and so on.

How do I fix certificate errors when running wget on an HTTPS URL in Cygwin?

I had a similar problem with wget to my own live web site returning errors after installing a new SSL certificate. I'd already checked several browsers and they didn't report any errors:

wget --no-cache -O - "https://example.com/..." ERROR: The certificate of ‘example.com’ is not trusted. ERROR: The certificate of ‘example.com’ hasn't got a known issuer.

The problem was I had installed the wrong certificate authority .pem/.crt file from the issuer. Usually they bundle the SSL certificate and CA file as a zip file, but DigiCert email you the certificate and you have to figure out the matching CA on your own. https://www.digicert.com/help/ has an SSL certificate checker which lists the SSL authority and the hopefully matching CA with a nice blue link graphic if they agree:

`SSL Cert: Issuer GeoTrust TLS DV RSA Mixed SHA256 2020 CA-1

CA: Subject GeoTrust TLS DV RSA Mixed SHA256 2020 CA-1 Valid from 16/Jul/2020 to 31/May/2023 Issuer DigiCert Global Root CA`

How to navigate back to the last cursor position in Visual Studio Code?

Mac OS (MacBook Pro):

Back: CTRL(control) + - (Hyphen)

Back Forward: CTRL + Shift + - (Hyphen)

Storing image in database directly or as base64 data?

Just want to give one example why we decided to store image in DB not files or CDN, it is storing images of signatures.

We have tried to do so via CDN, cloud storage, files, and finally decided to store in DB and happy about the decision as it was proven us right in our subsequent events when we moved, upgraded our scripts and migrated the sites serveral times.

For my case, we wanted the signatures to be with the records that belong to the author of documents.

Storing in files format risks missing them or deleted by accident.

We store it as a blob binary format in MySQL, and later as based64 encoded image in a text field. The decision to change to based64 was due to smaller size as result for some reason, and faster loading. Blob was slowing down the page load for some reason.

In our case, this solution to store signature images in DB, (whether as blob or based64), was driven by:

  1. Most signature images are very small.
  2. We don't need to index the signature images stored in DB.
  3. Index is done on the primary key.
  4. We may have to move or switch servers, moving physical images files to different servers, may cause the images not found due to links change.
  5. it is embarrassed to ask the author to re-sign their signatures.
  6. it is more secured saving in the DB as compared to exposing it as files which can be downloaded if security is compromised. Storing in DB allows us better control over its access.
  7. any future migrations, change of web design, hosting, servers, we have zero worries about reconcilating the signature file names against the physical files, it is all in the DB!

AC

Usages of doThrow() doAnswer() doNothing() and doReturn() in mockito

To add a bit to accepted answer ...

If you get an UnfinishedStubbingException, be sure to set the method to be stubbed after the when closure, which is different than when you write Mockito.when

Mockito.doNothing().when(mock).method()    //method is declared after 'when' closes

Mockito.when(mock.method()).thenReturn(something)   //method is declared inside 'when'

Is there a 'box-shadow-color' property?

A quick and copy/paste you can use for Chrome and Firefox would be: (change the stuff after the # to change the color)

-moz-border-radius: 10px;
-webkit-border-radius: 10px;
-khtml-border-radius: 10px;
-border-radius: 10px;
-moz-box-shadow: 0 0 15px 5px #666;
-webkit-box-shadow: 0 0 15px 05px #666;

Matt Roberts' answer is correct for webkit browsers (safari, chrome, etc), but I thought someone out there might want a quick answer rather than be told to learn to program to make some shadows.

Android ADB commands to get the device properties

From Linux Terminal:

adb shell getprop | grep "model\|version.sdk\|manufacturer\|hardware\|platform\|revision\|serialno\|product.name\|brand"

From Windows PowerShell:

adb shell 
getprop | grep -e 'model' -e 'version.sdk' -e 'manufacturer' -e 'hardware' -e 'platform' -e 'revision' -e 'serialno' -e 'product.name' -e 'brand'

Sample output for Samsung:

[gsm.version.baseband]: [G900VVRU2BOE1]
[gsm.version.ril-impl]: [Samsung RIL v3.0]
[net.knoxscep.version]: [2.0.1]
[net.knoxsso.version]: [2.1.1]
[net.knoxvpn.version]: [2.2.0]
[persist.service.bdroid.version]: [4.1]
[ro.board.platform]: [msm8974]
[ro.boot.hardware]: [qcom]
[ro.boot.serialno]: [xxxxxx]
[ro.build.version.all_codenames]: [REL]
[ro.build.version.codename]: [REL]
[ro.build.version.incremental]: [G900VVRU2BOE1]
[ro.build.version.release]: [5.0]
[ro.build.version.sdk]: [21]
[ro.build.version.sdl]: [2101]
[ro.com.google.gmsversion]: [5.0_r2]
[ro.config.timaversion]: [3.0]
[ro.hardware]: [qcom]
[ro.opengles.version]: [196108]
[ro.product.brand]: [Verizon]
[ro.product.manufacturer]: [samsung]
[ro.product.model]: [SM-G900V]
[ro.product.name]: [kltevzw]
[ro.revision]: [14]
[ro.serialno]: [e5ce97c7]

Android 5.0 - Add header/footer to a RecyclerView

You can use viewtype to solve this problem, here is my demo: https://github.com/yefengfreedom/RecyclerViewWithHeaderFooterLoadingEmptyViewErrorView

  1. you can define some recycler view display mode:

    public static final int MODE_DATA = 0, MODE_LOADING = 1, MODE_ERROR = 2, MODE_EMPTY = 3, MODE_HEADER_VIEW = 4, MODE_FOOTER_VIEW = 5;

2.override the getItemViewType mothod

 @Override
public int getItemViewType(int position) {
    if (mMode == RecyclerViewMode.MODE_LOADING) {
        return RecyclerViewMode.MODE_LOADING;
    }
    if (mMode == RecyclerViewMode.MODE_ERROR) {
        return RecyclerViewMode.MODE_ERROR;
    }
    if (mMode == RecyclerViewMode.MODE_EMPTY) {
        return RecyclerViewMode.MODE_EMPTY;
    }
    //check what type our position is, based on the assumption that the order is headers > items > footers
    if (position < mHeaders.size()) {
        return RecyclerViewMode.MODE_HEADER_VIEW;
    } else if (position >= mHeaders.size() + mData.size()) {
        return RecyclerViewMode.MODE_FOOTER_VIEW;
    }
    return RecyclerViewMode.MODE_DATA;
}

3.override the getItemCount method

@Override
public int getItemCount() {
    if (mMode == RecyclerViewMode.MODE_DATA) {
        return mData.size() + mHeaders.size() + mFooters.size();
    } else {
        return 1;
    }
}

4.override the onCreateViewHolder method. create view holder by viewType

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    if (viewType == RecyclerViewMode.MODE_LOADING) {
        RecyclerView.ViewHolder loadingViewHolder = onCreateLoadingViewHolder(parent);
        loadingViewHolder.itemView.setLayoutParams(
                new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, parent.getHeight() - mToolBarHeight)
        );
        return loadingViewHolder;
    }
    if (viewType == RecyclerViewMode.MODE_ERROR) {
        RecyclerView.ViewHolder errorViewHolder = onCreateErrorViewHolder(parent);
        errorViewHolder.itemView.setLayoutParams(
                new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, parent.getHeight() - mToolBarHeight)
        );
        errorViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                if (null != mOnErrorViewClickListener) {
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mOnErrorViewClickListener.onErrorViewClick(v);
                        }
                    }, 200);
                }
            }
        });
        return errorViewHolder;
    }
    if (viewType == RecyclerViewMode.MODE_EMPTY) {
        RecyclerView.ViewHolder emptyViewHolder = onCreateEmptyViewHolder(parent);
        emptyViewHolder.itemView.setLayoutParams(
                new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, parent.getHeight() - mToolBarHeight)
        );
        emptyViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                if (null != mOnEmptyViewClickListener) {
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mOnEmptyViewClickListener.onEmptyViewClick(v);
                        }
                    }, 200);
                }
            }
        });
        return emptyViewHolder;
    }
    if (viewType == RecyclerViewMode.MODE_HEADER_VIEW) {
        RecyclerView.ViewHolder headerViewHolder = onCreateHeaderViewHolder(parent);
        headerViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                if (null != mOnHeaderViewClickListener) {
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mOnHeaderViewClickListener.onHeaderViewClick(v, v.getTag());
                        }
                    }, 200);
                }
            }
        });
        return headerViewHolder;
    }
    if (viewType == RecyclerViewMode.MODE_FOOTER_VIEW) {
        RecyclerView.ViewHolder footerViewHolder = onCreateFooterViewHolder(parent);
        footerViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                if (null != mOnFooterViewClickListener) {
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mOnFooterViewClickListener.onFooterViewClick(v, v.getTag());
                        }
                    }, 200);
                }
            }
        });
        return footerViewHolder;
    }
    RecyclerView.ViewHolder dataViewHolder = onCreateDataViewHolder(parent);
    dataViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(final View v) {
            if (null != mOnItemClickListener) {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mOnItemClickListener.onItemClick(v, v.getTag());
                    }
                }, 200);
            }
        }
    });
    dataViewHolder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(final View v) {
            if (null != mOnItemLongClickListener) {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mOnItemLongClickListener.onItemLongClick(v, v.getTag());
                    }
                }, 200);
                return true;
            }
            return false;
        }
    });
    return dataViewHolder;
}

5.Override the onBindViewHolder method. bind data by viewType

@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
    if (mMode == RecyclerViewMode.MODE_LOADING) {
        onBindLoadingViewHolder(holder, position);
    } else if (mMode == RecyclerViewMode.MODE_ERROR) {
        onBindErrorViewHolder(holder, position);
    } else if (mMode == RecyclerViewMode.MODE_EMPTY) {
        onBindEmptyViewHolder(holder, position);
    } else {
        if (position < mHeaders.size()) {
            if (mHeaders.size() > 0) {
                onBindHeaderViewHolder(holder, position);
            }
        } else if (position >= mHeaders.size() + mData.size()) {
            if (mFooters.size() > 0) {
                onBindFooterViewHolder(holder, position - mHeaders.size() - mData.size());
            }
        } else {
            onBindDataViewHolder(holder, position - mHeaders.size());
        }
    }
}

Passing a callback function to another class

What you need is a delegate and a callback. Here is a nice MSDN article that will show you how to use this technique in C#.

jQuery: Check if button is clicked

jQuery(':button').click(function () {
    if (this.id == 'button1') {
        alert('Button 1 was clicked');
    }
    else if (this.id == 'button2') {
        alert('Button 2 was clicked');
    }
});

EDIT:- This will work for all buttons.

Comparing two files in linux terminal

Also, do not forget about mcdiff - Internal diff viewer of GNU Midnight Commander.

For example:

mcdiff file1 file2

Enjoy!

What does "commercial use" exactly mean?

Fundamentally if you use it as part of a business then its commercial use - so its not a matter of whether the tools are directly generating income or not rather one of if they are being used in support of income generation directly or indirectly.

To take your specific example, if the purpose of the site is to sell or promote your paid services/product then its a commercial enterprise.

Show an image preview before upload

Without FileReader, we can use URL.createObjectURL method to get the DOMString that represents the object ( our image file ).

Don't forget to validate image extension.

<input type="file" id="files" multiple />
<div class="image-preview"></div>
let file_input = document.querySelector('#files');
let image_preview = document.querySelector('.image-preview');

const handle_file_preview = (e) => {
  let files = e.target.files;
  let length = files.length;

  for(let i = 0; i < length; i++) {
      let image = document.createElement('img');
      // use the DOMstring for source
      image.src = window.URL.createObjectURL(files[i]);
      image_preview.appendChild(image);
  }
}

file_input.addEventListener('change', handle_file_preview);

Jenkins - How to access BUILD_NUMBER environment variable

To Answer your first question, Jenkins variables are case sensitive. However, if you are writing a windows batch script, they are case insensitive, because Windows doesn't care about the case.

Since you are not very clear about your setup, let's make the assumption that you are using an ant build step to fire up your ant task. Have a look at the Jenkins documentation (same page that Adarsh gave you, but different chapter) for an example on how to make Jenkins variables available to your ant task.

EDIT:

Hence, I will need to access the environmental variable ${BUILD_NUMBER} to construct the URL.

Why don't you use $BUILD_URL then? Isn't it available in the extended email plugin?

How to do associative array/hashing in JavaScript

All modern browsers support a JavaScript Map object. There are a couple of reasons that make using a Map better than Object:

  • An Object has a prototype, so there are default keys in the map.
  • The keys of an Object are Strings, where they can be any value for a Map.
  • You can get the size of a Map easily while you have to keep track of size for an Object.

Example:

var myMap = new Map();

var keyObj = {},
    keyFunc = function () {},
    keyString = "a string";

myMap.set(keyString, "value associated with 'a string'");
myMap.set(keyObj, "value associated with keyObj");
myMap.set(keyFunc, "value associated with keyFunc");

myMap.size; // 3

myMap.get(keyString);    // "value associated with 'a string'"
myMap.get(keyObj);       // "value associated with keyObj"
myMap.get(keyFunc);      // "value associated with keyFunc"

If you want keys that are not referenced from other objects to be garbage collected, consider using a WeakMap instead of a Map.

How to insert programmatically a new line in an Excel cell in C#?

Using PEAR 'Spreadsheet_Excel_Writer' and 'OLE':

Only way I could get "\n" to work was making the cell $format->setTextWrap(); and then using "\n" would work.

How to debug SSL handshake using cURL?

curl -iv https://your.domain.io

That will give you cert and header output if you do not wish to use openssl command.

How can I enable MySQL's slow query log without restarting MySQL?

For slow queries on version < 5.1, the following configuration worked for me:

log_slow_queries=/var/log/mysql/slow-query.log
long_query_time=20
log_queries_not_using_indexes=YES

Also note to place it under [mysqld] part of the config file and restart mysqld.

convert month from name to number

$nmonth = date("m", strtotime($month));

What is "406-Not Acceptable Response" in HTTP?

406 Not Acceptable The resource identified by the request is only capable of generating response entities which have content characteristics not acceptable according to the accept headers sent in the request.

406 happens when the server cannot respond with the accept-header specified in the request. In your case it seems application/json for the response may not be acceptable to the server.

Performing a query on a result from another query?

I don't know if you even need to wrap it. Won't this work?

SELECT COUNT(*), SUM(DATEDIFF(now(),availables.updated_at))
FROM availables
INNER JOIN rooms    ON availables.room_id=rooms.id
WHERE availables.bookdate BETWEEN '2009-06-25' 
  AND date_add('2009-06-25', INTERVAL 4 DAY)
  AND rooms.hostel_id = 5094
GROUP BY availables.bookdate);

If your goal is to return both result sets then you'll need to store it some place temporarily.

Getting index value on razor foreach

IndexOf seems to be useful here.

@foreach (myItemClass ts in Model.ItemList.Where(x => x.Type == "something"))
    {
       int currentIndex = Model.ItemList.IndexOf(ts);
       @Html.HiddenFor(x=>Model.ItemList[currentIndex].Type)

...

Binary search (bisection) in Python

Using a dict wouldn't like double your memory usage unless the objects you're storing are really tiny, since the values are only pointers to the actual objects:

>>> a = 'foo'
>>> b = [a]
>>> c = [a]
>>> b[0] is c[0]
True

In that example, 'foo' is only stored once. Does that make a difference for you? And exactly how many items are we talking about anyway?

Caused by: org.flywaydb.core.api.FlywayException: Validate failed. Migration Checksum mismatch for migration 2

Actually there is another solution, but it's a workaround, that should not be done in a properly managed project. However I met a situation, where it was not possible to go down the better road :)

You can update the schame_version table, and actually change the checksum to the new one. This will cause the migration to go through, but can have other side effects.

When deploying to different environments (test, uat, prod, etc) then it might happen, that you have to update the same checksum on more environments. And when it comes to gitflow, and release branches, you can easily mix up the whole.

What is the best comment in source code you have ever encountered?

The favorite comment I ever wrote:

//the XML returned from this request is *mind-bogglingly* bad. Terrifyingly bad.
//a completed batch looks like this:
//<Batch>batchid=363777811 status=Done dateandtime=09/18/2007 09:53:10 PDT activateditems=335 numberofwarnings=0 itemsnotacivated=17 </Batch>
//and an incomplete batch like:
//<Batch>batchid=363778361 status=In Progress </Batch>
//so we'll just parse each item as a regex. Thanks Amazon.

And yes, Amazon actually returns XML like this.

How to convert an Stream into a byte[] in C#?

Byte[] Content = new BinaryReader(file.InputStream).ReadBytes(file.ContentLength);

Getting "method not valid without suitable object" error when trying to make a HTTP request in VBA?

For reading REST data, at least OData Consider Microsoft Power Query. You won't be able to write data. However, you can read data very well.

How to get a index value from foreach loop in jstl

I face Similar problem now I understand we have some more option : varStatus="loop", Here will be loop will variable which will hold the index of lop.

It can use for use to read for Zeor base index or 1 one base index.

${loop.count}` it will give 1 starting base index.

${loop.index} it will give 0 base index as normal Index of array start from 0.

For Example :

<c:forEach var="currentImage" items="${cityBannerImages}" varStatus="loop">
<picture>
   <source srcset="${currentImage}" media="(min-width: 1000px)"></source>
   <source srcset="${cityMobileImages[loop.count]}" media="(min-width:600px)"></source>
   <img srcset="${cityMobileImages[loop.count]}" alt=""></img>
</picture>
</c:forEach>

For more Info please refer this link

MySQL create stored procedure syntax with delimiter

I have created a simple MySQL procedure as given below:

DELIMITER //
CREATE PROCEDURE GetAllListings()
 BEGIN
 SELECT nid, type, title  FROM node where type = 'lms_listing' order by nid desc;
END //
DELIMITER;

Kindly follow this. After the procedure created, you can see the same and execute it.

How can one develop iPhone apps in Java?

You can also take a look at RoboVM.

It translates Java byte-code into native ARM or x86 code which can run directly on the processor without any VM or interpreter needed. Most of the Obj-C UI elements are already bridged into Java and follows the usual Java design patterns.

Edit Robo VM recently announced that it would be shutting down the service - Source

Python check if list items are integers?

Try this:

mynewlist = [s for s in mylist if s.isdigit()]

From the docs:

str.isdigit()

Return true if all characters in the string are digits and there is at least one character, false otherwise.

For 8-bit strings, this method is locale-dependent.


As noted in the comments, isdigit() returning True does not necessarily indicate that the string can be parsed as an int via the int() function, and it returning False does not necessarily indicate that it cannot be. Nevertheless, the approach above should work in your case.

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

You can only do this to you own photos. Due to recent upgrades, Facebook has made this more difficult. To do this, go to the album page where the photo is that you want to link to. You should see thumbnail images of the photos in the album. Hold down the "Control" or "Command" key while clicking the photo that you wish to link to. A new browser tab will open with the picture you clicked. Under the picture there is a URL that you can send to others to share the photo. You might have to have the privacy settings for that album set so that anyone can see the photos in that album. If you don't the person who clicks the link may have to be signed in and also be your "friend."

Here is an example of one of my photos: http://www.facebook.com/photo.php?pid=43764341&l=0d8a526a64&id=25502298 -it's my cat.

Update:

The link below the photo no longer appears. Once you open the photo in a new tab you can right click the photo (Control+click for Mac users) and click "Copy Image URL" or similar and then share this link. Based on my tests the person who clicks the link doesn't need to use Facebook. The photo will load without the Facebook interface. Like this - http://a1.sphotos.ak.fbcdn.net/hphotos-ak-ash4/189088_867367406856_25502298_43764341_1304758_n.jpg

How can I find a file/directory that could be anywhere on linux command line?

"Unfortunately this seems to only check the current directory, not the entire folder". Presumably you mean it doesn't look in subdirectories. To fix this, use find -name "filename"

If the file in question is not in the current working directory, you can search your entire machine via

find / -name "filename"

This also works with stuff like find / -name "*.pdf", etc. Sometimes I like to pipe that into a grep statement as well (since, on my machine at least, it highlights the results), so I end up with something like

find / -name "*star*wars*" | grep star

Doing this or a similar method just helps me instantly find the filename and recognize if it is in fact the file I am looking for.

android splash screen sizes for ldpi,mdpi, hdpi, xhdpi displays ? - eg : 1024X768 pixels for ldpi

Just use this website: http://ticons.fokkezb.nl :)

It makes it easier for you, and generates the correct sizes directly

Get current date, given a timezone in PHP?

The other answers set the timezone for all dates in your system. This doesn't always work well if you want to support multiple timezones for your users.

Here's the short version:

<?php
$date = new DateTime("now", new DateTimeZone('America/New_York') );
echo $date->format('Y-m-d H:i:s');

Works in PHP >= 5.2.0

List of supported timezones: php.net/manual/en/timezones.php


Here's a version with an existing time and setting timezone by a user setting

<?php

$usersTimezone = 'America/New_York';
$date = new DateTime( 'Thu, 31 Mar 2011 02:05:59 GMT', new DateTimeZone($usersTimezone) );
echo $date->format('Y-m-d H:i:s');

Here is a more verbose version to show the process a little more clearly

<?php

// Date for a specific date/time:
$date = new DateTime('Thu, 31 Mar 2011 02:05:59 GMT');

// Output date (as-is)
echo $date->format('l, F j Y g:i:s A');     

// Output line break (for testing)
echo "\n<br />\n";

// Example user timezone (to show it can be used dynamically)
$usersTimezone = 'America/New_York';

// Convert timezone
$tz = new DateTimeZone($usersTimezone);
$date->setTimeZone($tz);

// Output date after 
echo $date->format('l, F j Y g:i:s A');

Libraries

  • Carbon — A very popular date library.
  • Chronos — A drop-in replacement for Carbon focused on immutability. See below on why that's important.
  • jenssegers/date — An extension of Carbon that adds multi-language support.

I'm sure there are a number of other libraries available, but these are a few I'm familiar with.


Bonus Lesson: Immutable Date Objects

While you're here, let me save you some future headache. Let's say you want to calculate 1 week from today and 2 weeks from today. You might write some code like:

<?php

// Create a datetime (now, in this case 2017-Feb-11)
$today = new DateTime();

echo $today->format('Y-m-d') . "\n<br>";
echo "---\n<br>";

$oneWeekFromToday = $today->add(DateInterval::createFromDateString('7 days'));
$twoWeeksFromToday = $today->add(DateInterval::createFromDateString('14 days'));

echo $today->format('Y-m-d') . "\n<br>";
echo $oneWeekFromToday->format('Y-m-d') . "\n<br>";
echo $twoWeeksFromToday->format('Y-m-d') . "\n<br>";
echo "\n<br>";

The output:

2017-02-11 
--- 
2017-03-04 
2017-03-04 
2017-03-04

Hmmmm... That's not quite what we wanted. Modifying a traditional DateTime object in PHP not only returns the updated date but modifies the original object as well.

This is where DateTimeImmutable comes in.

$today = new DateTimeImmutable();

echo $today->format('Y-m-d') . "\n<br>";
echo "---\n<br>";

$oneWeekFromToday = $today->add(DateInterval::createFromDateString('7 days'));
$twoWeeksFromToday = $today->add(DateInterval::createFromDateString('14 days'));

echo $today->format('Y-m-d') . "\n<br>";
echo $oneWeekFromToday->format('Y-m-d') . "\n<br>";
echo $twoWeeksFromToday->format('Y-m-d') . "\n<br>";

The output:

2017-02-11 
--- 
2017-02-11 
2017-02-18 
2017-02-25 

In this second example, we get the dates we expected back. By using DateTimeImmutable instead of DateTime, we prevent accidental state mutations and prevent potential bugs.

Using CSS to insert text

Just code it like this:

.OwnerJoe {
  //other things here
  &:before{
    content: "Joe's Task: ";
  }
}

How to write to file in Ruby?

This is preferred approach in most cases:

 File.open(yourfile, 'w') { |file| file.write("your text") }

When a block is passed to File.open, the File object will be automatically closed when the block terminates.

If you don't pass a block to File.open, you have to make sure that file is correctly closed and the content was written to file.

begin
  file = File.open("/tmp/some_file", "w")
  file.write("your text") 
rescue IOError => e
  #some error occur, dir not writable etc.
ensure
  file.close unless file.nil?
end

You can find it in documentation:

static VALUE rb_io_s_open(int argc, VALUE *argv, VALUE klass)
{
    VALUE io = rb_class_new_instance(argc, argv, klass);
    if (rb_block_given_p()) {
        return rb_ensure(rb_yield, io, io_close, io);
    }
    return io;
}

Calculating moving average

In fact RcppRoll is very good.

The code posted by cantdutchthis must be corrected in the fourth line to the window be fixed:

ma <- function(arr, n=15){
  res = arr
  for(i in n:length(arr)){
    res[i] = mean(arr[(i-n+1):i])
  }
  res
}

Another way, which handles missings, is given here.

A third way, improving cantdutchthis code to calculate partial averages or not, follows:

  ma <- function(x, n=2,parcial=TRUE){
  res = x #set the first values

  if (parcial==TRUE){
    for(i in 1:length(x)){
      t<-max(i-n+1,1)
      res[i] = mean(x[t:i])
    }
    res

  }else{
    for(i in 1:length(x)){
      t<-max(i-n+1,1)
      res[i] = mean(x[t:i])
    }
    res[-c(seq(1,n-1,1))] #remove the n-1 first,i.e., res[c(-3,-4,...)]
  }
}

OR operator in switch-case?

You cannot use || operators in between 2 case. But you can use multiple case values without using a break between them. The program will then jump to the respective case and then it will look for code to execute until it finds a "break". As a result these cases will share the same code.

switch(value) 
{ 
    case 0: 
    case 1: 
        // do stuff for if case 0 || case 1 
        break; 
    // other cases 
    default: 
        break; 
}

Replace text in HTML page with jQuery

The html replace idea is good, but if done to the document.body, the page will blink and ads will disappear.

My solution:
$("*:contains('purrfect')").each(function() { var replaced = $(this).html().replace(/purrfect/g, "purrfect"); $(this).html(replaced); });

SQL Server: Multiple table joins with a WHERE clause

SELECT Computer.Computer_Name, Application1.Name, Max(Soft.[Version]) as Version1
FROM Application1
inner JOIN Software
    ON Application1.ID = Software.Application_Id
cross join Computer
Left JOIN Software_Computer
    ON Software_Computer.Computer_Id = Computer.ID and Software_Computer.Software_Id = Software.Id
Left JOIN Software as Soft
    ON Soft.Id = Software_Computer.Software_Id
WHERE Computer.ID = 1 
GROUP BY Computer.Computer_Name, Application1.Name 

100% width background image with an 'auto' height

Tim S. was much closer to a "correct" answer then the currently accepted one. If you want to have a 100% width, variable height background image done with CSS, instead of using cover (which will allow the image to extend out from the sides) or contain (which does not allow the image to extend out at all), just set the CSS like so:

body {
    background-image: url(img.jpg);
    background-position: center top;
    background-size: 100% auto;
}

This will set your background image to 100% width and allow the height to overflow. Now you can use media queries to swap out that image instead of relying on JavaScript.

EDIT: I just realized (3 months later) that you probably don't want the image to overflow; you seem to want the container element to resize based on it's background-image (to preserve it's aspect ratio), which is not possible with CSS as far as I know.

Hopefully soon you'll be able to use the new srcset attribute on the img element. If you want to use img elements now, the currently accepted answer is probably best.

However, you can create a responsive background-image element with a constant aspect ratio using purely CSS. To do this, you set the height to 0 and set the padding-bottom to a percentage of the element's own width, like so:

.foo {
    height: 0;
    padding: 0; /* remove any pre-existing padding, just in case */
    padding-bottom: 75%; /* for a 4:3 aspect ratio */
    background-image: url(foo.png);
    background-position: center center;
    background-size: 100%;
    background-repeat: no-repeat;
}

In order to use different aspect ratios, divide the height of the original image by it's own width, and multiply by 100 to get the percentage value. This works because padding percentage is always calculated based on width, even if it's vertical padding.

ADB.exe is obsolete and has serious performance problems

If you are stuck after following each of the steps outlined in above, I will suggest you combine more than one answers. The answers of @Kuya and @??? worked for me. Try them out. I can explain more if the steps are yielding results for you.

Setting Django up to use MySQL

Actually, there are many issues with different environments, python versions, so on. You might also need to install python dev files, so to 'brute-force' the installation I would run all of these:

sudo apt-get install python-dev python3-dev
sudo apt-get install libmysqlclient-dev
pip install MySQL-python
pip install pymysql
pip install mysqlclient

You should be good to go with the accepted answer. And can remove the unnecessary packages if that's important to you.

ResourceDictionary in a separate assembly

Resource-Only DLL is an option for you. But it is not required necessarily unless you want to modify resources without recompiling applications. Have just one common ResourceDictionary file is also an option. It depends how often you change resources and etc.

<ResourceDictionary Source="pack://application:,,,/
     <MyAssembly>;component/<FolderStructureInAssembly>/<ResourceFile.xaml>"/>

MyAssembly - Just assembly name without extension

FolderStructureInAssembly - If your resources are in a folde, specify folder structure

When you are doing this it's better to aware of siteOfOrigin as well.

WPF supports two authorities: application:/// and siteoforigin:///. The application:/// authority identifies application data files that are known at compile time, including resource and content files. The siteoforigin:/// authority identifies site of origin files. The scope of each authority is shown in the following figure.

enter image description here

Populate unique values into a VBA array from Excel

Combining the Dictionary approach from Tim with the variant array from Jean_Francois below.

The array you want is in objDict.keys

enter image description here

Sub A_Unique_B()
Dim X
Dim objDict As Object
Dim lngRow As Long

Set objDict = CreateObject("Scripting.Dictionary")
X = Application.Transpose(Range([a1], Cells(Rows.Count, "A").End(xlUp)))

For lngRow = 1 To UBound(X, 1)
    objDict(X(lngRow)) = 1
Next
Range("B1:B" & objDict.Count) = Application.Transpose(objDict.keys)
End Sub

C# - Winforms - Global Variables

yes you can by using static class. like this:

static class Global
{
    private static string _globalVar = "";

    public static string GlobalVar
    {
        get { return _globalVar; }
        set { _globalVar = value; }
    }
}

and for using any where you can write:

GlobalClass.GlobalVar = "any string value"

What's the best UML diagramming tool?

You should try Creately. Runs in your browser and can do team collaboration.

supports sequence diagrams, class, ER, usecase etc. works great and has a free version available.

Creately.com

Make more than one chart in same IPython Notebook cell

Something like this:

import matplotlib.pyplot as plt
... code for plot 1 ...
plt.show()
... code for plot 2...
plt.show()

Note that this will also work if you are using the seaborn package for plotting:

import matplotlib.pyplot as plt
import seaborn as sns
sns.barplot(... code for plot 1 ...) # plot 1
plt.show()
sns.barplot(... code for plot 2 ...) # plot 2
plt.show()

shorthand c++ if else statement

Yes:

bigInt.sign = !(number < 0);

The ! operator always evaluates to true or false. When converted to int, these become 1 and 0 respectively.

Of course this is equivalent to:

bigInt.sign = (number >= 0);

Here the parentheses are redundant but I add them for clarity. All of the comparison and relational operator evaluate to true or false.

Removing elements from an array in C

There are really two separate issues. The first is keeping the elements of the array in proper order so that there are no "holes" after removing an element. The second is actually resizing the array itself.

Arrays in C are allocated as a fixed number of contiguous elements. There is no way to actually remove the memory used by an individual element in the array but the elements can be shifted to fill the hole made by removing an element. For example:

void remove_element(array_type *array, int index, int array_length)
{
   int i;
   for(i = index; i < array_length - 1; i++) array[i] = array[i + 1];
}

Statically allocated arrays can not be resized. Dynamically allocated arrays can be resized with realloc(). This will potentially move the entire array to another location in memory, so all pointers to the array or to its elements will have to be updated. For example:

remove_element(array, index, array_length);  /* First shift the elements, then reallocate */
array_type *tmp = realloc(array, (array_length - 1) * sizeof(array_type) );
if (tmp == NULL && array_length > 1) {
   /* No memory available */
   exit(EXIT_FAILURE);
}
array_length = array_length - 1;
array = tmp;

realloc will return a NULL pointer if the requested size is 0, or if there is an error. Otherwise it returns a pointer to the reallocated array. The temporary pointer is used to detect errors when calling realloc because instead of exiting it is also possible to just leave the original array as it was. When realloc fails to reallocate an array it does not alter the original array.

Note that both of these operations will be fairly slow if the array is large or if a lot of elements are removed. There are other data structures like linked lists and hashes that can be used if efficient insertion and deletion is a priority.

List all column except for one in R

You can index and use a negative sign to drop the 3rd column:

data[,-3]

Or you can list only the first 2 columns:

data[,c("c1", "c2")]
data[,1:2]

Don't forget the comma and referencing data frames works like this: data[row,column]

Using onBlur with JSX and React

There are a few problems here.

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

2: you need a place to render the error.

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

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

In C - check if a char exists in a char array

You want

strchr (const char *s, int c)

If the character c is in the string s it returns a pointer to the location in s. Otherwise it returns NULL. So just use your list of invalid characters as the string.

Stop form refreshing page on submit

Just found a very simple yet working solution, by removing <form></form> from the section I wanted to prevent from posting and refreshing.

<select id="youId" name="yourName">
<select> 
<option value="1</option>
<option value="2</option>
<option value="3</option>
</select>
<input id="formStockVal1" type="number"><br><br>
<form> 
<button type="reset" id="stockCancel">Cancel</button>
<button type="reset" id="stockConfirm">Add</button>
</form>

Here only Buttons submit as they should.

java.lang.ClassNotFoundException: org.springframework.core.io.Resource

There is a version conflict between jar/dependency please check all version of spring is same. if you use maven remove version of dependency and use Spring.io dependency.it handle version conflict. Add this in your pom

 <dependency>
            <groupId>io.spring.platform</groupId>
            <artifactId>platform-bom</artifactId>
            <version>2.0.1.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
  </dependency>

ADB No Devices Found

I have a Motorola Razr and I was having trouble identifying my device. What I did was:

1 - From the command prompt (as an administrator) -> adb kill-servers

2 - Downloaded Motorola Device Manager here -> https://motorola-global-portal.custhelp.com/app/answers/detail/a_id/88481

3 - I waited until the installation was complete.

4 - From the command prompt (as an administrator) -> adb devices

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

I guess an img tag is needed as a child of an a tag, the following way:

<a download="YourFileName.jpeg" href="data:image/jpeg;base64,iVBO...CYII=">
    <img src="data:image/jpeg;base64,iVBO...CYII="></img>
</a>

or

<a download="YourFileName.jpeg" href="/path/to/OtherFile.jpg">
    <img src="/path/to/OtherFile.jpg"></img>
</a>

Only using the a tag as explained in #15 didn't worked for me with the latest version of Firefox and Chrome, but putting the same image data in both a.href and img.src tags worked for me.

From JavaScript it could be generated like this:

var data = canvas.toDataURL("image/jpeg");

var img = document.createElement('img');
img.src = data;

var a = document.createElement('a');
a.setAttribute("download", "YourFileName.jpeg");
a.setAttribute("href", data);
a.appendChild(img);

var w = open();
w.document.title = 'Export Image';
w.document.body.innerHTML = 'Left-click on the image to save it.';
w.document.body.appendChild(a);

Apple Mach-O Linker Error when compiling for device

I got the same issue when i export FMDB module in xcode 4.6. Later i found a fmdb.m in my my file list which was causing this issue. After i removed from the project it works fine

Create File If File Does Not Exist

Yes, you need to negate File.Exists(path) if you want to check if the file doesn't exist.

Is there a way to provide named parameters in a function call in JavaScript?

ES2015 and later

In ES2015, parameter destructuring can be used to simulate named parameters. It would require the caller to pass an object, but you can avoid all of the checks inside the function if you also use default parameters:

myFunction({ param1 : 70, param2 : 175});

function myFunction({param1, param2}={}){
  // ...function body...
}

// Or with defaults, 
function myFunc({
  name = 'Default user',
  age = 'N/A'
}={}) {
  // ...function body...
}

ES5

There is a way to come close to what you want, but it is based on the output of Function.prototype.toString [ES5], which is implementation dependent to some degree, so it might not be cross-browser compatible.

The idea is to parse the parameter names from the string representation of the function so that you can associate the properties of an object with the corresponding parameter.

A function call could then look like

func(a, b, {someArg: ..., someOtherArg: ...});

where a and b are positional arguments and the last argument is an object with named arguments.

For example:

var parameterfy = (function() {
    var pattern = /function[^(]*\(([^)]*)\)/;

    return function(func) {
        // fails horribly for parameterless functions ;)
        var args = func.toString().match(pattern)[1].split(/,\s*/);

        return function() {
            var named_params = arguments[arguments.length - 1];
            if (typeof named_params === 'object') {
                var params = [].slice.call(arguments, 0, -1);
                if (params.length < args.length) {
                    for (var i = params.length, l = args.length; i < l; i++) {
                        params.push(named_params[args[i]]);
                    }
                    return func.apply(this, params);
                }
            }
            return func.apply(null, arguments);
        };
    };
}());

Which you would use as:

var foo = parameterfy(function(a, b, c) {
    console.log('a is ' + a, ' | b is ' + b, ' | c is ' + c);     
});

foo(1, 2, 3); // a is 1  | b is 2  | c is 3
foo(1, {b:2, c:3}); // a is 1  | b is 2  | c is 3
foo(1, {c:3}); // a is 1  | b is undefined  | c is 3
foo({a: 1, c:3}); // a is 1  | b is undefined  | c is 3 

DEMO

There are some drawbacks to this approach (you have been warned!):

  • If the last argument is an object, it is treated as a "named argument objects"
  • You will always get as many arguments as you defined in the function, but some of them might have the value undefined (that's different from having no value at all). That means you cannot use arguments.length to test how many arguments have been passed.

Instead of having a function creating the wrapper, you could also have a function which accepts a function and various values as arguments, such as

call(func, a, b, {posArg: ... });

or even extend Function.prototype so that you could do:

foo.execute(a, b, {posArg: ...});

How do I use reflection to call a generic method?

Calling a generic method with a type parameter known only at runtime can be greatly simplified by using a dynamic type instead of the reflection API.

To use this technique the type must be known from the actual object (not just an instance of the Type class). Otherwise, you have to create an object of that type or use the standard reflection API solution. You can create an object by using the Activator.CreateInstance method.

If you want to call a generic method, that in "normal" usage would have had its type inferred, then it simply comes to casting the object of unknown type to dynamic. Here's an example:

class Alpha { }
class Beta { }
class Service
{
    public void Process<T>(T item)
    {
        Console.WriteLine("item.GetType(): " + item.GetType()
                          + "\ttypeof(T): " + typeof(T));
    }
}

class Program
{
    static void Main(string[] args)
    {
        var a = new Alpha();
        var b = new Beta();

        var service = new Service();
        service.Process(a); // Same as "service.Process<Alpha>(a)"
        service.Process(b); // Same as "service.Process<Beta>(b)"

        var objects = new object[] { a, b };
        foreach (var o in objects)
        {
            service.Process(o); // Same as "service.Process<object>(o)"
        }
        foreach (var o in objects)
        {
            dynamic dynObj = o;
            service.Process(dynObj); // Or write "service.Process((dynamic)o)"
        }
    }
}

And here's the output of this program:

item.GetType(): Alpha    typeof(T): Alpha
item.GetType(): Beta     typeof(T): Beta
item.GetType(): Alpha    typeof(T): System.Object
item.GetType(): Beta     typeof(T): System.Object
item.GetType(): Alpha    typeof(T): Alpha
item.GetType(): Beta     typeof(T): Beta

Process is a generic instance method that writes the real type of the passed argument (by using the GetType() method) and the type of the generic parameter (by using typeof operator).

By casting the object argument to dynamic type we deferred providing the type parameter until runtime. When the Process method is called with the dynamic argument then the compiler doesn't care about the type of this argument. The compiler generates code that at runtime checks the real types of passed arguments (by using reflection) and choose the best method to call. Here there is only this one generic method, so it's invoked with a proper type parameter.

In this example, the output is the same as if you wrote:

foreach (var o in objects)
{
    MethodInfo method = typeof(Service).GetMethod("Process");
    MethodInfo generic = method.MakeGenericMethod(o.GetType());
    generic.Invoke(service, new object[] { o });
}

The version with a dynamic type is definitely shorter and easier to write. You also shouldn't worry about performance of calling this function multiple times. The next call with arguments of the same type should be faster thanks to the caching mechanism in DLR. Of course, you can write code that cache invoked delegates, but by using the dynamic type you get this behaviour for free.

If the generic method you want to call don't have an argument of a parametrized type (so its type parameter can't be inferred) then you can wrap the invocation of the generic method in a helper method like in the following example:

class Program
{
    static void Main(string[] args)
    {
        object obj = new Alpha();

        Helper((dynamic)obj);
    }

    public static void Helper<T>(T obj)
    {
        GenericMethod<T>();
    }

    public static void GenericMethod<T>()
    {
        Console.WriteLine("GenericMethod<" + typeof(T) + ">");
    }
}

Increased type safety

What is really great about using dynamic object as a replacement for using reflection API is that you only lose compile time checking of this particular type that you don't know until runtime. Other arguments and the name of the method are staticly analysed by the compiler as usual. If you remove or add more arguments, change their types or rename method name then you'll get a compile-time error. This won't happen if you provide the method name as a string in Type.GetMethod and arguments as the objects array in MethodInfo.Invoke.

Below is a simple example that illustrates how some errors can be caught at compile time (commented code) and other at runtime. It also shows how the DLR tries to resolve which method to call.

interface IItem { }
class FooItem : IItem { }
class BarItem : IItem { }
class Alpha { }

class Program
{
    static void Main(string[] args)
    {
        var objects = new object[] { new FooItem(), new BarItem(), new Alpha() };
        for (int i = 0; i < objects.Length; i++)
        {
            ProcessItem((dynamic)objects[i], "test" + i, i);

            //ProcesItm((dynamic)objects[i], "test" + i, i);
            //compiler error: The name 'ProcesItm' does not
            //exist in the current context

            //ProcessItem((dynamic)objects[i], "test" + i);
            //error: No overload for method 'ProcessItem' takes 2 arguments
        }
    }

    static string ProcessItem<T>(T item, string text, int number)
        where T : IItem
    {
        Console.WriteLine("Generic ProcessItem<{0}>, text {1}, number:{2}",
                          typeof(T), text, number);
        return "OK";
    }
    static void ProcessItem(BarItem item, string text, int number)
    {
        Console.WriteLine("ProcessItem with Bar, " + text + ", " + number);
    }
}

Here we again execute some method by casting the argument to the dynamic type. Only verification of first argument's type is postponed to runtime. You will get a compiler error if the name of the method you're calling doesn't exist or if other arguments are invalid (wrong number of arguments or wrong types).

When you pass the dynamic argument to a method then this call is lately bound. Method overload resolution happens at runtime and tries to choose the best overload. So if you invoke the ProcessItem method with an object of BarItem type then you'll actually call the non-generic method, because it is a better match for this type. However, you'll get a runtime error when you pass an argument of the Alpha type because there's no method that can handle this object (a generic method has the constraint where T : IItem and Alpha class doesn't implement this interface). But that's the whole point. The compiler doesn't have information that this call is valid. You as a programmer know this, and you should make sure that this code runs without errors.

Return type gotcha

When you're calling a non-void method with a parameter of dynamic type, its return type will probably be dynamic too. So if you'd change previous example to this code:

var result = ProcessItem((dynamic)testObjects[i], "test" + i, i);

then the type of the result object would be dynamic. This is because the compiler don't always know which method will be called. If you know the return type of the function call then you should implicitly convert it to the required type so the rest of the code is statically typed:

string result = ProcessItem((dynamic)testObjects[i], "test" + i, i);

You'll get a runtime error if the type doesn't match.

Actually, if you try to get the result value in the previous example then you'll get a runtime error in the second loop iteration. This is because you tried to save the return value of a void function.

Is it possible to deserialize XML into List<T>?

Yes, it does deserialize to List<>. No need to keep it in an array and wrap/encapsulate it in a list.

public class UserHolder
{
    private List<User> users = null;

    public UserHolder()
    {
    }

    [XmlElement("user")]
    public List<User> Users
    {
        get { return users; }
        set { users = value; }
    }
}

Deserializing code,

XmlSerializer xs = new XmlSerializer(typeof(UserHolder));
UserHolder uh = (UserHolder)xs.Deserialize(new StringReader(str));

Dynamically Add Variable Name Value Pairs to JSON Object

if my understanding of your initial JSON is correct, either of these solutions might help you loop through all ip ids & assign each one, a new object.

// initial JSON
var ips = {ipId1: {}, ipId2: {}};

// Solution1
Object.keys(ips).forEach(function(key) {
  ips[key] = {name: 'value', anotherName: 'another value'};
});

// Solution 2
Object.keys(ips).forEach(function(key) {
  Object.assign(ips[key],{name: 'value', anotherName: 'another value'});
});

To confirm:

console.log(JSON.stringify(ips, null, 2));

The above statement spits:

{
  "ipId1": {
    "name":"value",
    "anotherName":"another value"
  },
  "ipId2": {
    "name":"value",
    "anotherName":"another value"
  }
}

split string in two on given index and return both parts

Try this

_x000D_
_x000D_
function split_at_index(value, index)
{
 return value.substring(0, index) + "," + value.substring(index);
}

console.log(split_at_index('3123124', 2));
_x000D_
_x000D_
_x000D_

Handle ModelState Validation in ASP.NET Web API

Or, if you are looking for simple collection of errors for your apps.. here is my implementation of this:

public override void OnActionExecuting(HttpActionContext actionContext)
    {
        var modelState = actionContext.ModelState;

        if (!modelState.IsValid) 
        {

            var errors = new List<string>();
            foreach (var state in modelState)
            {
                foreach (var error in state.Value.Errors)
                {
                    errors.Add(error.ErrorMessage);
                }
            }

            var response = new { errors = errors };

            actionContext.Response = actionContext.Request
                .CreateResponse(HttpStatusCode.BadRequest, response, JsonMediaTypeFormatter.DefaultMediaType);
        }
    }

Error Message Response will look like:

{
  "errors": [
    "Please enter a valid phone number (7+ more digits)",
    "Please enter a valid e-mail address"
  ]
}

Copy all values from fields in one class to another through reflection

I think you can try dozer. It has good support for bean to bean conversion. Its also easy to use. You can either inject it into your spring application or add the jar in class path and its done.

For an example of your case :

 DozerMapper mapper = new DozerMapper();
A a= new A();
CopyA copyA = new CopyA();
a.set... // set fields of a.
mapper.map(a,copyOfA); // will copy all fields from a to copyA

how to hide <li> bullets in navigation menu and footer links BUT show them for listing items

You need to define a class for the bullets you want to hide. For examples

.no-bullets {
    list-style-type: none;
}

Then apply it to the list you want hidden bullets:

<ul class="no-bullets">

All other lists (without a specific class) will show the bulltets as usual.

How to prevent Screen Capture in Android

I saw all of the answers which are appropriate only for a single activity but there is my solution which will block screenshot for all of the activities without adding any code to the activity. First of all make an Custom Application class and add a registerActivityLifecycleCallbacks.Then register it in your manifest.

MyApplicationContext.class

public class MyApplicationContext extends Application {
    private  Context context;
    public void onCreate() {
        super.onCreate();
        context = getApplicationContext();
        setupActivityListener();
    }

    private void setupActivityListener() {
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                activity.getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);            }
            @Override
            public void onActivityStarted(Activity activity) {
            }
            @Override
            public void onActivityResumed(Activity activity) {

            }
            @Override
            public void onActivityPaused(Activity activity) {

            }
            @Override
            public void onActivityStopped(Activity activity) {
            }
            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
            }
            @Override
            public void onActivityDestroyed(Activity activity) {
            }
        });
    }



}

Manifest

 <application
        android:name=".MyApplicationContext"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

Active Menu Highlight CSS

Another variation with a simple 2-line listener

$( ".menu_button" ).click(function() {

    $( ".menu_button" ).removeClass('menu_button_highlight');
    $(this).addClass('menu_button_highlight');
});

=====

    <a class='menu_button' href='#admin'>Admin</a>
    <br/>

    <a class='menu_button' href='#user_manager'>User Manager</a>
    <br/>

    <a class='menu_button' href='#invite_codes'>Invite Codes</a>

====

.menu_button {

    padding: 0 5px;
}

.menu_button_highlight {

    background: #ffe94c;
}

Include of non-modular header inside framework module

Make sure the header files are publicly available as part of the framework's public headers.

Goto Framework -> Target -> Build Phases and drag to move the relevant header files from Project to Public. Hope that helps!

Screenshot

Environment Specific application.properties file in Spring Boot application

Yes you can. Since you are using spring, check out @PropertySource anotation.

Anotate your configuration with

@PropertySource("application-${spring.profiles.active}.properties")

You can call it what ever you like, and add inn multiple property files if you like too. Can be nice if you have more sets and/or defaults that belongs to all environments (can be written with @PropertySource{...,...,...} as well).

@PropertySources({
  @PropertySource("application-${spring.profiles.active}.properties"),
  @PropertySource("my-special-${spring.profiles.active}.properties"),
  @PropertySource("overridden.properties")})

Then you can start the application with environment

-Dspring.active.profiles=test

In this example, name will be replaced with application-test-properties and so on.

How do I call paint event?

Maybe this is an old question and that´s the reason why these answers didn't work for me ... using Visual Studio 2019, after some investigating, this is the solution I've found:

this.InvokePaint(this, new PaintEventArgs(this.CreateGraphics(), this.DisplayRectangle));

Emulate a 403 error page

For this you must first say for the browser that the user receive an error 403. For this you can use this code:

header("HTTP/1.1 403 Forbidden" );

Then, the script send "error, error, error, error, error.......", so you must stop it. You can use

exit;

With this two lines the server send an error and stop the script.

Don't forget : that emulate the error, but you must set it in a .htaccess file, with

ErrorDocument 403 /error403.php

Browser can't access/find relative resources like CSS, images and links when calling a Servlet which forwards to a JSP

Below code worked for me.

instead of use <%@ include file="styles/default.css"%>

Using Cygwin to Compile a C program; Execution error

If you are not comfortable with bash, you can continue to work in a standard windows command (i.e. DOS) shell.

For this to work you must add C:\cygwin\bin (or your local alternative) to the Windows PATH variable.

With this done, you may: 1) Open a command (DOS) shell 2) Change the directory to the location of your code (c:, then cd path\to\file) 3) gcc myProgram.c -o myProgram

As mentioned in nik's response, the "Using Cygwin" documentation is a great place to learn more.

Auto margins don't center image in page

For a bootstrap button:

display: table; 
margin: 0 auto;

What does the construct x = x || y mean?

double pipe operator

is this example usefull?

var section = document.getElementById('special');
if(!section){
     section = document.getElementById('main');
}

can also be

var section = document.getElementById('special') || document.getElementById('main');

Making HTTP Requests using Chrome Developer tools

To GET requests with headers, use this format.

   fetch('http://example.com', {
      method: 'GET',
      headers: new Headers({
               'Content-Type': 'application/json',
               'someheader': 'headervalue'
               })
    })
    .then(res => res.json())
    .then(console.log)

Angular exception: Can't bind to 'ngForIn' since it isn't a known native property

Since this is at least the third time I've wasted more than 5 min on this problem I figured I'd post the Q & A. I hope it helps someone else down the road... probably me!

I typed in instead of of in the ngFor expression.

Befor 2-beta.17, it should be:

<div *ngFor="#talk of talks">

As of beta.17, use the let syntax instead of #. See the UPDATE further down for more info.


Note that the ngFor syntax "desugars" into the following:

<template ngFor #talk [ngForOf]="talks">
  <div>...</div>
</template>

If we use in instead, it turns into

<template ngFor #talk [ngForIn]="talks">
  <div>...</div>
</template>

Since ngForIn isn't an attribute directive with an input property of the same name (like ngIf), Angular then tries to see if it is a (known native) property of the template element, and it isn't, hence the error.

UPDATE - as of 2-beta.17, use the let syntax instead of #. This updates to the following:

<div *ngFor="let talk of talks">

Note that the ngFor syntax "desugars" into the following:

<template ngFor let-talk [ngForOf]="talks">
  <div>...</div>
</template>

If we use in instead, it turns into

<template ngFor let-talk [ngForIn]="talks">
  <div>...</div>
</template>

Angular directive how to add an attribute to the element?

A directive which adds another directive to the same element:

Similar answers:

Here is a plunker: http://plnkr.co/edit/ziU8d826WF6SwQllHHQq?p=preview

app.directive("myDir", function($compile) {
  return {
    priority:1001, // compiles first
    terminal:true, // prevent lower priority directives to compile after it
    compile: function(el) {
      el.removeAttr('my-dir'); // necessary to avoid infinite compile loop
      el.attr('ng-click', 'fxn()');
      var fn = $compile(el);
      return function(scope){
        fn(scope);
      };
    }
  };
});

Much cleaner solution - not to use ngClick at all:

A plunker: http://plnkr.co/edit/jY10enUVm31BwvLkDIAO?p=preview

app.directive("myDir", function($parse) {
  return {
    compile: function(tElm,tAttrs){
      var exp = $parse('fxn()');
      return function (scope,elm){
        elm.bind('click',function(){
          exp(scope);
        });  
      };
    }
  };
});

Microsoft Visual C++ Compiler for Python 3.4

Unfortunately to be able to use the extension modules provided by others you'll be forced to use the official compiler to compile Python. These are:

Alternatively, you can use MinGw to compile extensions in a way that won't depend on others.

See: https://docs.python.org/2/install/#gnu-c-cygwin-MinGW or https://docs.python.org/3.4/install/#gnu-c-cygwin-mingw

This allows you to have one compiler to build your extensions for both versions of Python, Python 2.x and Python 3.x.

twitter bootstrap autocomplete dropdown / combobox with Knockoutjs

Does the basic HTML5 datalist work? It's clean and you don't have to play around with the messy third party code. W3SCHOOL tutorial

The MDN Documentation is very eloquent and features examples.

mysql command for showing current configuration variables

What you are looking for is this:

SHOW VARIABLES;  

You can modify it further like any query:

SHOW VARIABLES LIKE '%max%';  

Spring AMQP + RabbitMQ 3.3.5 ACCESS_REFUSED - Login was refused using authentication mechanism PLAIN

if you use the number as your password, maybe you should try to change your password using string.

I can login using deltaqin:000000 on the website, but had this while running the program. then change the password to deltaiqn. and it works.

Convert string to date in Swift

Swift 3.0 - 4.2

import Foundation

extension String {

    func toDate(withFormat format: String = "yyyy-MM-dd HH:mm:ss")-> Date?{

        let dateFormatter = DateFormatter()
        dateFormatter.timeZone = TimeZone(identifier: "Asia/Tehran")
        dateFormatter.locale = Locale(identifier: "fa-IR")
        dateFormatter.calendar = Calendar(identifier: .gregorian)
        dateFormatter.dateFormat = format
        let date = dateFormatter.date(from: self)

        return date

    }
}

extension Date {

    func toString(withFormat format: String = "EEEE ? d MMMM yyyy") -> String {

        let dateFormatter = DateFormatter()
        dateFormatter.locale = Locale(identifier: "fa-IR")
        dateFormatter.timeZone = TimeZone(identifier: "Asia/Tehran")
        dateFormatter.calendar = Calendar(identifier: .persian)
        dateFormatter.dateFormat = format
        let str = dateFormatter.string(from: self)

        return str
    }
}

What is the default access modifier in Java?

Is the access modifier of this constructor protected or package?

I think implicitly your constructors access modifier would be your class's access modifier. as your class has public access, constructor would have public access implicitly

With jQuery, how do I capitalize the first letter of a text field while the user is still editing that field?

A turkish one. If someone is still interested.

 $('input[type="text"]').keyup(function() {
    $(this).val($(this).val().replace(/^([a-zA-Z\s\ö\ç\s\i\i\g\ü\Ö\Ç\S\I\G\Ü])|\s+([a-zA-Z\s\ö\ç\s\i\i\g\ü\Ö\Ç\S\I\G\Ü])/g, function ($1) {
        if ($1 == "i")
            return "I";
        else if ($1 == " i")
            return " I";
        return $1.toUpperCase();
    }));
});

Javascript: Unicode string to hex

A more up to date solution, for encoding:

// This is the same for all of the below, and
// you probably won't need it except for debugging
// in most cases.
function bytesToHex(bytes) {
  return Array.from(
    bytes,
    byte => byte.toString(16).padStart(2, "0")
  ).join("");
}

// You almost certainly want UTF-8, which is
// now natively supported:
function stringToUTF8Bytes(string) {
  return new TextEncoder().encode(string);
}

// But you might want UTF-16 for some reason.
// .charCodeAt(index) will return the underlying
// UTF-16 code-units (not code-points!), so you
// just need to format them in whichever endian order you want.
function stringToUTF16Bytes(string, littleEndian) {
  const bytes = new Uint8Array(string.length * 2);
  // Using DataView is the only way to get a specific
  // endianness.
  const view = new DataView(bytes.buffer);
  for (let i = 0; i != string.length; i++) {
    view.setUint16(i, string.charCodeAt(i), littleEndian);
  }
  return bytes;
}

// And you might want UTF-32 in even weirder cases.
// Fortunately, iterating a string gives the code
// points, which are identical to the UTF-32 encoding,
// though you still have the endianess issue.
function stringToUTF32Bytes(string, littleEndian) {
  const codepoints = Array.from(string, c => c.codePointAt(0));
  const bytes = new Uint8Array(codepoints.length * 4);
  // Using DataView is the only way to get a specific
  // endianness.
  const view = new DataView(bytes.buffer);
  for (let i = 0; i != codepoints.length; i++) {
    view.setUint32(i, codepoints[i], littleEndian);
  }
  return bytes;
}

Examples:

bytesToHex(stringToUTF8Bytes("hello ?? "))
// "68656c6c6f20e6bca2e5ad9720f09f918d"
bytesToHex(stringToUTF16Bytes("hello ?? ", false))
// "00680065006c006c006f00206f225b570020d83ddc4d"
bytesToHex(stringToUTF16Bytes("hello ?? ", true))
// "680065006c006c006f002000226f575b20003dd84ddc"
bytesToHex(stringToUTF32Bytes("hello ?? ", false))
// "00000068000000650000006c0000006c0000006f0000002000006f2200005b57000000200001f44d"
bytesToHex(stringToUTF32Bytes("hello ?? ", true))
// "68000000650000006c0000006c0000006f00000020000000226f0000575b0000200000004df40100"

For decoding, it's generally a lot simpler, you just need:

function hexToBytes(hex) {
    const bytes = new Uint8Array(hex.length / 2);
    for (let i = 0; i !== bytes.length; i++) {
        bytes[i] = parseInt(hex.substr(i * 2, 2), 16);
    }
    return bytes;
}

then use the encoding parameter of TextDecoder:

// UTF-8 is default
new TextDecoder().decode(hexToBytes("68656c6c6f20e6bca2e5ad9720f09f918d"));
// but you can also use:
new TextDecoder("UTF-16LE").decode(hexToBytes("680065006c006c006f002000226f575b20003dd84ddc"))
new TextDecoder("UTF-16BE").decode(hexToBytes("00680065006c006c006f00206f225b570020d83ddc4d"));
// "hello ?? "

Here's the list of allowed encoding names: https://www.w3.org/TR/encoding/#names-and-labels

You might notice UTF-32 is not on that list, which is a pain, so:

function bytesToStringUTF32(bytes, littleEndian) {
  const view = new DataView(bytes.buffer);
  const codepoints = new Uint32Array(view.byteLength / 4);
  for (let i = 0; i !== codepoints.length; i++) {
    codepoints[i] = view.getUint32(i * 4, littleEndian);
  }
  return String.fromCodePoint(...codepoints);
}

Then:

bytesToStringUTF32(hexToBytes("00000068000000650000006c0000006c0000006f0000002000006f2200005b57000000200001f44d"), false)
bytesToStringUTF32(hexToBytes("68000000650000006c0000006c0000006f00000020000000226f0000575b0000200000004df40100"), true)
// "hello ?? "

Difference between left join and right join in SQL Server

(INNER) JOIN: Returns records that have matching values in both tables.

LEFT (OUTER) JOIN: Return all records from the left table, and the matched records from the right table.

RIGHT (OUTER) JOIN: Return all records from the right table, and the matched records from the left table.

FULL (OUTER) JOIN: Return all records when there is a match in either left or right table

For example, lets suppose we have two table with following records:

Table A

id   firstname   lastname
___________________________
1     Ram         Thapa
2     sam         Koirala
3     abc         xyz
6    sruthy       abc

Table B

id2   place
_____________
1      Nepal
2      USA
3      Lumbini
5      Kathmandu

Inner Join

Note: It give the intersection of two table.

Inner Join

Syntax

SELECT column_name FROM table1 INNER JOIN table2 ON table1.column_name = table2.column_name;

Apply it in your sample table:

SELECT TableA.firstName,TableA.lastName,TableB.Place FROM TableA INNER JOIN TableB ON TableA.id = TableB.id2;

Result will be:

firstName       lastName       Place
_____________________________________
  Ram         Thapa             Nepal
  sam         Koirala            USA
  abc         xyz              Lumbini

Left Join

Note : will give all selected rows in TableA, plus any common selected rows in TableB.

Left join

SELECT column_name(s) FROM table1 LEFT JOIN table2 ON table1.column_name = table2.column_name;

Apply it in your sample table

SELECT TableA.firstName,TableA.lastName,TableB.Place FROM TableA LEFT JOIN TableB ON TableA.id = TableB.id2;

Result will be:

firstName   lastName    Place
______________________________
 Ram         Thapa      Nepal
 sam         Koirala    USA
 abc         xyz        Lumbini
sruthy       abc        Null

Right Join

Note:will give all selected rows in TableB, plus any common selected rows in TableA.

Right Join

Syntax:

SELECT column_name(s) FROM table1 RIGHT JOIN table2 ON table1.column_name = table2.column_name;

Apply it in your samole table:

SELECT TableA.firstName,TableA.lastName,TableB.Place FROM TableA RIGHT JOIN TableB ON TableA.id = TableB.id2;

Result will bw:

firstName   lastName     Place
______________________________
Ram         Thapa         Nepal
sam         Koirala       USA
abc         xyz           Lumbini
Null        Null          Kathmandu

Full Join

Note : It is same as union operation, it will return all selected values from both tables.

Full join

Syntax:

SELECT column_name(s) FROM table1 FULL OUTER JOIN table2 ON table1.column_name = table2.column_name;

Apply it in your samp[le table:

SELECT TableA.firstName,TableA.lastName,TableB.Place FROM TableA FULL JOIN TableB ON TableA.id = TableB.id2;

Result will be:

firstName   lastName    Place
______________________________
 Ram         Thapa      Nepal
 sam         Koirala    USA
 abc         xyz        Lumbini
sruthy       abc        Null
 Null         Null      Kathmandu

Some facts

For INNER joins the order doesn't matter

For (LEFT, RIGHT or FULL) OUTER joins,the order matter

Find More at w3schools

What is the difference between BIT and TINYINT in MySQL?

All these theoretical discussions are great, but in reality, at least if you're using MySQL and really for SQLServer as well, it's best to stick with non-binary data for your booleans for the simple reason that it's easier to work with when you're outputting the data, querying and so on. It is especially important if you're trying to achieve interoperability between MySQL and SQLServer (i.e. you sync data between the two), because the handling of BIT datatype is different in the two of them. SO in practice you will have a lot less hassles if you stick with a numeric datatype. I would recommend for MySQL to stick with BOOL or BOOLEAN which gets stored as TINYINT(1). Even the way MySQL Workbench and MySQL Administrator display the BIT datatype isn't nice (it's a little symbol for binary data). So be practical and save yourself the hassles (and unfortunately I'm speaking from experience).

Java Serializable Object to Byte Array

code example with java 8+:

public class Person implements Serializable {

private String lastName;
private String firstName;

public Person() {
}

public Person(String firstName, String lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
}

public void setFirstName(String firstName) {
    this.firstName = firstName;
}

public String getFirstName() {
    return firstName;
}

public String getLastName() {
    return lastName;
}

public void setLastName(String lastName) {
    this.lastName = lastName;
}

@Override
public String toString() {
    return "firstName: " + firstName + ", lastName: " + lastName;
}
}


public interface PersonMarshaller {
default Person fromStream(InputStream inputStream) {
    try (ObjectInputStream objectInputStream = new ObjectInputStream(inputStream)) {
        Person person= (Person) objectInputStream.readObject();
        return person;
    } catch (IOException | ClassNotFoundException e) {
        System.err.println(e.getMessage());
        return null;
    }
}

default OutputStream toStream(Person person) {
    try (OutputStream outputStream = new ByteArrayOutputStream()) {
        ObjectOutput objectOutput = new ObjectOutputStream(outputStream);
        objectOutput.writeObject(person);
        objectOutput.flush();
        return outputStream;
    } catch (IOException e) {
        System.err.println(e.getMessage());
        return null;
    }

}

}

Finish an activity from another activity

See my answer to Stack Overflow question Finish All previous activities.

What you need is to add the Intent.FLAG_CLEAR_TOP. This flag makes sure that all activities above the targeted activity in the stack are finished and that one is shown.

Another thing that you need is the SINGLE_TOP flag. With this one you prevent Android from creating a new activity if there is one already created in the stack.

Just be wary that if the activity was already created, the intent with these flags will be delivered in the method called onNewIntent(intent) (you need to overload it to handle it) in the target activity.

Then in onNewIntent you have a method called restart or something that will call finish() and launch a new intent toward itself, or have a repopulate() method that will set the new data. I prefer the second approach, it is less expensive and you can always extract the onCreate logic into a separate method that you can call for populate.

Best Java obfuscator?

I used to work with Klassmaster in my previous company and it works really well and can integrate pretty good with build systems (maven support is excellent). But it's not free though.

How to get the browser language using JavaScript

Try this script to get your browser language

_x000D_
_x000D_
<script type="text/javascript">_x000D_
var userLang = navigator.language || navigator.userLanguage; _x000D_
alert ("The language is: " + userLang);_x000D_
</script>
_x000D_
_x000D_
_x000D_

Cheers

How to duplicate a whole line in Vim?

Do this:

First, yy to copy the current line, and then p to paste.

Accessing private member variables from prototype-defined functions

In current JavaScript, I'm fairly certain that there is one and only one way to have private state, accessible from prototype functions, without adding anything public to this. The answer is to use the "weak map" pattern.

To sum it up: The Person class has a single weak map, where the keys are the instances of Person, and the values are plain objects that are used for private storage.

Here is a fully functional example: (play at http://jsfiddle.net/ScottRippey/BLNVr/)

var Person = (function() {
    var _ = weakMap();
    // Now, _(this) returns an object, used for private storage.
    var Person = function(first, last) {
        // Assign private storage:
        _(this).firstName = first;
        _(this).lastName = last;
    }
    Person.prototype = {
        fullName: function() {
            // Retrieve private storage:
            return _(this).firstName + _(this).lastName;
        },
        firstName: function() {
            return _(this).firstName;
        },
        destroy: function() {
            // Free up the private storage:
            _(this, true);
        }
    };
    return Person;
})();

function weakMap() {
    var instances=[], values=[];
    return function(instance, destroy) {
        var index = instances.indexOf(instance);
        if (destroy) {
            // Delete the private state:
            instances.splice(index, 1);
            return values.splice(index, 1)[0];
        } else if (index === -1) {
            // Create the private state:
            instances.push(instance);
            values.push({});
            return values[values.length - 1];
        } else {
            // Return the private state:
            return values[index];
        }
    };
}

Like I said, this is really the only way to achieve all 3 parts.

There are two caveats, however. First, this costs performance -- every time you access the private data, it's an O(n) operation, where n is the number of instances. So you won't want to do this if you have a large number of instances. Second, when you're done with an instance, you must call destroy; otherwise, the instance and the data will not be garbage collected, and you'll end up with a memory leak.

And that's why my original answer, "You shouldn't", is something I'd like to stick to.

How to use OpenFileDialog to select a folder?

As a note for future users who would like to avoid using FolderBrowserDialog, Microsoft once released an API called the WindowsAPICodePack that had a helpful dialog called CommonOpenFileDialog, that could be set into a IsFolderPicker mode. The API is available from Microsoft as a NuGet package.

This is all I needed to install and use the CommonOpenFileDialog. (NuGet handled the dependencies)

Install-Package Microsoft.WindowsAPICodePack-Shell

For the include line:

using Microsoft.WindowsAPICodePack.Dialogs;

Usage:

CommonOpenFileDialog dialog = new CommonOpenFileDialog();
dialog.InitialDirectory = "C:\\Users";
dialog.IsFolderPicker = true;
if (dialog.ShowDialog() == CommonFileDialogResult.Ok)
{
    MessageBox.Show("You selected: " + dialog.FileName);
}

How to disable/enable select field using jQuery?

To be able to disable/enable selects first of all your selects need an ID or class. Then you could do something like this:

Disable:

$('#id').attr('disabled', 'disabled');

Enable:

$('#id').removeAttr('disabled');

Show only two digit after decimal

How about String.format("%.2f", i2)?

What does the "at" (@) symbol do in Python?

It indicates that you are using a decorator. Here is Bruce Eckel's example from 2008.

What is the color code for transparency in CSS?

There is no hex code for transparency. For CSS, you can use either transparent or rgba(0, 0, 0, 0).

React-Native: Application has not been registered error

After have read all the above, I have found that there could be another reason for this.

In my case:

react-native-cli: 2.0.1

react-native: 0.60.4

and following structure:

enter image description here

First has to be noted that index.android is not been update in Android Studio when the build run by Metro builder( react-native run-android) so it has to be done manually. Also in Android studio does not "read" the

app.json(created by default together with index.js, that renamed index.android.js):

 {
    "name": "authApp",
    "displayName": "authApp"
 }

and so this like

(in my case)

import {authApp as appName} from './app.json';

cause the fact that android studio does not know what authApp refer to. I fix for the moment referring to the app name with its string name and not using that import from app.json:

AppRegistry.registerComponent('authApp', () => MyApp);

What does "exec sp_reset_connection" mean in Sql Server Profiler?

It's an indication that connection pooling is being used (which is a good thing).

How to make an Android Spinner with initial text "Select One"?

 ArrayList<String> sizes = new ArrayList<>();

 spinner = (Spinner) findViewById(R.id.spinner_size);

    if (sizes != null && !sizes.isEmpty()) {

        //SORT ArrayList If You Want Data in ASC or DSC Order

        sizes.add("28");
        sizes.add("29");
        sizes.add("31");

        sizes.add("Choose Size"); //adding String at the end of ArrayList
        Collections.reverse(sizes); //Last Item Will Be Shown As A Spinner Title

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, sizes);
        spinner.setAdapter(adapter);

Simply use arraylist.add("Your Data") method to add item at the end of arrayList then just reverse it using Collection.reverse(arrayList) so that the Title be the 1st Item in Spinner. You can also sort the item before adding the data at the end. enter image description here

Best way to compare two complex objects

I would say that:

Object1.Equals(Object2)

would be what you're looking for. That's if you're looking to see if the objects are the same, which is what you seem to be asking.

If you want to check to see if all the child objects are the same, run them through a loop with the Equals() method.

message box in jquery

Download file from web in Python 3

from urllib import request

def get(url):
    with request.urlopen(url) as r:
        return r.read()


def download(url, file=None):
    if not file:
        file = url.split('/')[-1]
    with open(file, 'wb') as f:
        f.write(get(url))

How do I make Java register a string input with spaces?

in.next() will return space-delimited strings. Use in.nextLine() if you want to read the whole line. After reading the string, use question = question.replaceAll("\\s","") to remove spaces.

Way to get number of digits in an int?

Marian's Solution, now with Ternary:

 public int len(int n){
        return (n<100000)?((n<100)?((n<10)?1:2):(n<1000)?3:((n<10000)?4:5)):((n<10000000)?((n<1000000)?6:7):((n<100000000)?8:((n<1000000000)?9:10)));
    }

Because we can.

:first-child not working as expected

You could wrap your h1 tags in another div and then the first one would be the first-child. That div doesn't even need styles. It's just a way to segregate those children.

<div class="h1-holder">
    <h1>Title 1</h1>
    <h1>Title 2</h1>
</div>

Creating a PHP header/footer

the simpler, the better.

index.php

<? 
if (empty($_SERVER['QUERY_STRING'])) { 
  $name="index"; 
} else { 
  $name=basename($_SERVER['QUERY_STRING']); 
} 
$file="txt/".$name.".htm"; 
if (is_readable($file)) { 
  include 'header.php';
  readfile($file);
} else { 
  header("HTTP/1.0 404 Not Found");
  exit;
} 
?>

header.php

<a href="index.php">Main page</a><br>
<a href=?about>About</a><br>
<a href=?links>Links</a><br>
<br><br> 

the actual static html pages stored in the txt folder in the page.htm format

jQuery Datepicker localization

I just Added

jQuery.datetimepicker.setLocale('fr');

and It's worked

how to set width for PdfPCell in ItextSharp

Why not use a PdfPTable object for this? Create a fixed width table and use a float array to set the widths of the columns

PdfPTable table = new PdfPTable(10);
table.HorizontalAlignment = 0;
table.TotalWidth = 500f;
table.LockedWidth = true;
float[] widths = new float[] { 20f, 60f, 60f, 30f, 50f, 80f, 50f, 50f, 50f, 50f };
table.SetWidths(widths);

addCell(table, "SER.\nNO.", 2);

addCell(table, "TYPE OF SHIPPING", 1);
addCell(table, "ORDER NO.", 1);
addCell(table, "QTY.", 1);
addCell(table, "DISCHARGE PPORT", 1);

addCell(table, "DESCRIPTION OF GOODS", 2);

addCell(table, "LINE DOC. RECL DATE", 1);

addCell(table, "CLEARANCE DATE", 2);
addCell(table, "CUSTOM PERMIT NO.", 2);
addCell(table, "DISPATCH DATE", 2);

addCell(table, "AWB/BL NO.", 1);
addCell(table, "COMPLEX NAME", 1);
addCell(table, "G. W. Kgs.", 1);
addCell(table, "DESTINATION", 1);
addCell(table, "OWNER DOC. RECL DATE", 1);

....

private static void addCell(PdfPTable table, string text, int rowspan)
{
    BaseFont bfTimes = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false);
    iTextSharp.text.Font times = new iTextSharp.text.Font(bfTimes, 6, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK);

    PdfPCell cell = new PdfPCell(new Phrase(text, times));
    cell.Rowspan = rowspan;
    cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
    cell.VerticalAlignment = PdfPCell.ALIGN_MIDDLE;
    table.AddCell(cell);
}

have a look at this tutorial too...

What's the best visual merge tool for Git?

You can change the tool used by git mergetool by passing git mergetool -t=<tool> or --tool=<tool>. To change the default (from vimdiff) use git config merge.tool <tool>.

How to grep for contents after pattern?

Modern BASH has support for regular expressions:

while read -r line; do
  if [[ $line =~ ^potato:\ ([0-9]+) ]]; then
    echo "${BASH_REMATCH[1]}"
  fi
done

how to implement login auth in node.js

Actually this is not really the answer of the question, but this is a better way to do it.

I suggest you to use connect/express as http server, since they save you a lot of time. You obviously don't want to reinvent the wheel. In your case session management is much easier with connect/express.

Beside that for authentication I suggest you to use everyauth. Which supports a lot of authentication strategies. Awesome for rapid development.

All this can be easily down with some copy pasting from their documentation!

jQuery Scroll to bottom of page/iframe

For example:

$('html, body').scrollTop($(document).height());

Checking for empty queryset in Django

Since version 1.2, Django has QuerySet.exists() method which is the most efficient:

if orgs.exists():
    # Do this...
else:
    # Do that...

But if you are going to evaluate QuerySet anyway it's better to use:

if orgs:
   ...

For more information read QuerySet.exists() documentation.

Changing background color of selected cell?

This worked perfectly with grouped calls: Implement a custom subclass of UITableViewCell

This will respect corners and such...

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];

    if(selected)
        [self setBackgroundColor:[UIColor colorWithRed:(245/255.0) green:(255/255.0) blue:(255/255.0) alpha:1]];
    else
        [self setBackgroundColor:[UIColor whiteColor]];

}

How to close a GUI when I push a JButton?

Add your button:

JButton close = new JButton("Close");

Add an ActionListener:

close.addActionListner(new CloseListener());

Add a class for the Listener implementing the ActionListener interface and override its main function:

private class CloseListener implements ActionListener{
    @Override
    public void actionPerformed(ActionEvent e) {
        //DO SOMETHING
        System.exit(0);
    }
}

This might be not the best way, but its a point to start. The class for example can be made public and not as a private class inside another one.

DataGridView - Focus a specific cell

You can try this for DataGrid:

DataGridCellInfo cellInfo = new DataGridCellInfo(myDataGrid.Items[colRow], myDataGrid.Columns[colNum]);
DataGridCell cellToFocus = (DataGridCell)cellInfo.Column.GetCellContent(cellInfo.Item).Parent;
ViewControlHelper.SetFocus(cellToFocus, e);

Get epoch for a specific date using Javascript

You can also use Date.now() function.

Named regular expression group "(?P<group_name>regexp)": what does "P" stand for?

Pattern! The group names a (sub)pattern for later use in the regex. See the documentation here for details about how such groups are used.

Unzip files (7-zip) via cmd command

In Windows 10 I had to run the batch file as an administrator.

Rename master branch for both local and remote Git repositories

You may do the following:

git -m master master-old #rename current master
git checkout -b master   #create a new branch master
git push -f origin master #force push to master

But force pushing is a bad idea if other people are sharing this repository. Force push will cause their revision history to conflict with the new one.

How do you run your own code alongside Tkinter's event loop?

The solution posted by Bjorn results in a "RuntimeError: Calling Tcl from different appartment" message on my computer (RedHat Enterprise 5, python 2.6.1). Bjorn might not have gotten this message, since, according to one place I checked, mishandling threading with Tkinter is unpredictable and platform-dependent.

The problem seems to be that app.start() counts as a reference to Tk, since app contains Tk elements. I fixed this by replacing app.start() with a self.start() inside __init__. I also made it so that all Tk references are either inside the function that calls mainloop() or are inside functions that are called by the function that calls mainloop() (this is apparently critical to avoid the "different apartment" error).

Finally, I added a protocol handler with a callback, since without this the program exits with an error when the Tk window is closed by the user.

The revised code is as follows:

# Run tkinter code in another thread

import tkinter as tk
import threading

class App(threading.Thread):

    def __init__(self):
        threading.Thread.__init__(self)
        self.start()

    def callback(self):
        self.root.quit()

    def run(self):
        self.root = tk.Tk()
        self.root.protocol("WM_DELETE_WINDOW", self.callback)

        label = tk.Label(self.root, text="Hello World")
        label.pack()

        self.root.mainloop()


app = App()
print('Now we can continue running code while mainloop runs!')

for i in range(100000):
    print(i)

Assign a variable inside a Block to a variable outside a Block

To assign a variable inside block which outside of block always use __block specifier before that variable your code should be like this:-

__block Person *aPerson = nil;

jQuery events .load(), .ready(), .unload()

NOTE: .load() & .unload() have been deprecated


$(window).load();

Will execute after the page along with all its contents are done loading. This means that all images, CSS (and content defined by CSS like custom fonts and images), scripts, etc. are all loaded. This happens event fires when your browser's "Stop" -icon becomes gray, so to speak. This is very useful to detect when the document along with all its contents are loaded.

$(document).ready();

This on the other hand will fire as soon as the web browser is capable of running your JavaScript, which happens after the parser is done with the DOM. This is useful if you want to execute JavaScript as soon as possible.

$(window).unload();

This event will be fired when you are navigating off the page. That could be Refresh/F5, pressing the previous page button, navigating to another website or closing the entire tab/window.

To sum up, ready() will be fired before load(), and unload() will be the last to be fired.

Get drop down value

<select onchange = "selectChanged(this.value)">
  <item value = "1">one</item>
  <item value = "2">two</item>
</select>

and then the javascript...

function selectChanged(newvalue) {
  alert("you chose: " + newvalue);
}

Get current folder path

You should not use Directory.GetCurrentDirectory() in your case, as the current directory may differ from the execution folder, especially when you execute the program through a shortcut.

It's better to use Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); for your purpose. This returns the pathname where the currently executing assembly resides.

While my suggested approach allows you to differentiate between the executing assembly, the entry assembly or any other loaded assembly, as Soner Gönül said in his answer,

System.IO.Path.GetDirectoryName(Application.ExecutablePath);

may also be sufficient. This would be equal to

System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);

Splitting words into letters in Java

 char[] result = "Stack Me 123 Heppa1 oeu".toCharArray();

How to find the duration of difference between two dates in java?

This is a program I wrote, which gets the number of days between 2 dates(no time here).

import java.util.Scanner;
public class HelloWorld {
 public static void main(String args[]) {
  Scanner s = new Scanner(System.in);
  System.out.print("Enter starting date separated by dots: ");
  String inp1 = s.nextLine();
  System.out.print("Enter ending date separated by dots: ");
  String inp2 = s.nextLine();
  int[] nodim = {
   0,
   31,
   28,
   31,
   30,
   31,
   30,
   31,
   31,
   30,
   31,
   30,
   31
  };
  String[] inpArr1 = split(inp1);
  String[] inpArr2 = split(inp2);
  int d1 = Integer.parseInt(inpArr1[0]);
  int m1 = Integer.parseInt(inpArr1[1]);
  int y1 = Integer.parseInt(inpArr1[2]);
  int d2 = Integer.parseInt(inpArr2[0]);
  int m2 = Integer.parseInt(inpArr2[1]);
  int y2 = Integer.parseInt(inpArr2[2]);
  if (y1 % 4 == 0) nodim[2] = 29;
  int diff = m1 == m2 && y1 == y2 ? d2 - (d1 - 1) : (nodim[m1] - (d1 - 1));
  int mm1 = m1 + 1, mm2 = m2 - 1, yy1 = y1, yy2 = y2;
  for (; yy1 <= yy2; yy1++, mm1 = 1) {
   mm2 = yy1 == yy2 ? (m2 - 1) : 12;
   if (yy1 % 4 == 0) nodim[2] = 29;
   else nodim[2] = 28;
   if (mm2 == 0) {
    mm2 = 12;
    yy2 = yy2 - 1;
   }
   for (; mm1 <= mm2 && yy1 <= yy2; mm1++) diff = diff + nodim[mm1];
  }
  System.out.print("No. of days from " + inp1 + " to " + inp2 + " is " + diff);
 }
 public static String[] split(String s) {
  String[] retval = {
   "",
   "",
   ""
  };
  s = s + ".";
  s = s + " ";
  for (int i = 0; i <= 2; i++) {
   retval[i] = s.substring(0, s.indexOf("."));
   s = s.substring((s.indexOf(".") + 1), s.length());
  }
  return retval;
 }
}

http://pastebin.com/HRsjTtUf

How to create bitmap from byte array?

In addition, you can simply convert byte array to Bitmap.

var bmp = new Bitmap(new MemoryStream(imgByte));

You can also get Bitmap from file Path directly.

Bitmap bmp = new Bitmap(Image.FromFile(filePath));

Unique on a dataframe with only selected columns

Here are a couple dplyr options that keep non-duplicate rows based on columns id and id2:

library(dplyr)                                        
df %>% distinct(id, id2, .keep_all = TRUE)
df %>% group_by(id, id2) %>% filter(row_number() == 1)
df %>% group_by(id, id2) %>% slice(1)

How can I concatenate a string within a loop in JSTL/JSP?

Perhaps this will work?

<c:forEach items="${myParams.items}" var="currentItem" varStatus="stat">
  <c:set var="myVar" value="${stat.first ? '' : myVar} ${currentItem}" />
</c:forEach>

Set value of textarea in jQuery

Just use this code and you will always have the value:

var t = $(this); var v = t.val() || t.html() || t.text();

So it will check val() and set its value. If val() gets an empty string, NULL, NaN o.s. it will check for html() and then for text()...

Change hover color on a button with Bootstrap customization

I had to add !important to get it to work. I also made my own class button-primary-override.

.button-primary-override:hover, 
.button-primary-override:active,
.button-primary-override:focus,
.button-primary-override:visited{
    background-color: #42A5F5 !important;
    border-color: #42A5F5 !important;
    background-image: none !important;
    border: 0 !important;
}

TypeError: only length-1 arrays can be converted to Python scalars while trying to exponentially fit data

Non-numpy functions like math.abs() or math.log10() don't play nicely with numpy arrays. Just replace the line raising an error with:

m = np.log10(np.abs(x))

Apart from that the np.polyfit() call will not work because it is missing a parameter (and you are not assigning the result for further use anyway).

What does ==$0 (double equals dollar zero) mean in Chrome Developer Tools?

This is Chrome's hint to tell you that if you type $0 on the console, it will be equivalent to that specific element.

Internally, Chrome maintains a stack, where $0 is the selected element, $1 is the element that was last selected, $2 would be the one that was selected before $1 and so on.

Here are some of its applications:

  • Accessing DOM elements from console: $0
  • Accessing their properties from console: $0.parentElement
  • Updating their properties from console: $1.classList.add(...)
  • Updating CSS elements from console: $0.styles.backgroundColor="aqua"
  • Triggering CSS events from console: $0.click()
  • And doing a lot more complex stuffs, like: $0.appendChild(document.createElement("div"))

Watch all of this in action:

enter image description here

Backing statement:

Yes, I agree there are better ways to perform these actions, but this feature can come out handy in certain intricate scenarios, like when a DOM element needs to be clicked but it is not possible to do so from the UI because it is covered by other elements or, for some reason, is not visible on UI at that moment.

Overriding a JavaScript function while referencing the original

Passing arbitrary arguments:

a = override(a, function(original_a) {
    if (condition) { new_code(); original_a.apply(this, arguments) ; }
    else { original_a.apply(this, arguments); other_new_code(); }
});

How to concatenate multiple column values into a single column in Panda dataframe

I think you are missing one %s

df['combined']=df.apply(lambda x:'%s_%s_%s' % (x['bar'],x['foo'],x['new']),axis=1)

How to identify numpy types in python?

The solution I've come up with is:

isinstance(y, (np.ndarray, np.generic) )

However, it's not 100% clear that all numpy types are guaranteed to be either np.ndarray or np.generic, and this probably isn't version robust.

Where can I find documentation on formatting a date in JavaScript?

Example code:

var d = new Date();
var time = d.toISOString().replace(/.*?T(\d+:\d+:\d+).*/, "$1");

Output:

"13:45:20"

How do I print a datetime in the local timezone?

As of python 3.2, using only standard library functions:

u_tm = datetime.datetime.utcfromtimestamp(0)
l_tm = datetime.datetime.fromtimestamp(0)
l_tz = datetime.timezone(l_tm - u_tm)

t = datetime.datetime(2009, 7, 10, 18, 44, 59, 193982, tzinfo=l_tz)
str(t)
'2009-07-10 18:44:59.193982-07:00'

Just need to use l_tm - u_tm or u_tm - l_tm depending whether you want to show as + or - hours from UTC. I am in MST, which is where the -07 comes from. Smarter code should be able to figure out which way to subtract.

And only need to calculate the local timezone once. That is not going to change. At least until you switch from/to Daylight time.

UINavigationBar custom back button without title

This did the trick for me

[[UIBarButtonItem appearance] 
setBackButtonTitlePositionAdjustment:UIOffsetMake(-1000, -1000) 
forBarMetrics:UIBarMetricsDefault];

All the best

Android M - check runtime permission - how to determine if the user checked "Never ask again"?

Complete explanation for every case of permission

/**
 *    Case 1: User doesn't have permission
 *    Case 2: User has permission
 *
 *    Case 3: User has never seen the permission Dialog
 *    Case 4: User has denied permission once but he din't clicked on "Never Show again" check box
 *    Case 5: User denied the permission and also clicked on the "Never Show again" check box.
 *    Case 6: User has allowed the permission
 *
 */
public void handlePermission() {
    if (ContextCompat.checkSelfPermission(MainActivity.this,
            Manifest.permission.WRITE_EXTERNAL_STORAGE)
            != PackageManager.PERMISSION_GRANTED) {
        // This is Case 1. Now we need to check further if permission was shown before or not

        if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)) {

            // This is Case 4.
        } else {
            // This is Case 3. Request for permission here
        }

    } else {
        // This is Case 2. You have permission now you can do anything related to it
    }
}

public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {

    if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
        // This is Case 2 (Permission is now granted)
    } else {
        // This is Case 1 again as Permission is not granted by user

        //Now further we check if used denied permanently or not
        if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            // case 4 User has denied permission but not permanently

        } else {
            // case 5. Permission denied permanently.
            // You can open Permission setting's page from here now.
        }

    }
}

Bootstrap 3 - disable navbar collapse

The nabvar will collapse on small devices. The point of collapsing is defined by @grid-float-breakpoint in variables. By default this will by before 768px. For screens below the 768 pixels screen width, the navbar will look like:

enter image description here

It's possible to change the @grid-float-breakpoint in variables.less and recompile Bootstrap. When doing this you also will have to change @screen-xs-max in navbar.less. You will have to set this value to your new @grid-float-breakpoint -1. See also: https://github.com/twbs/bootstrap/pull/10465. This is needed to change navbar forms and dropdowns at the @grid-float-breakpoint to their mobile version too.

Easiest way is to customize bootstrap

find variable:

 @grid-float-breakpoint

which is set to @screen-sm, you can change it according to your needs. Hope it helps!


For SAAS Users

add your custom variables like $grid-float-breakpoint: 0px; before the @import "bootstrap.scss";

Finding Android SDK on Mac and adding to PATH

In my case, I had to create local.properties file with sdk.dir=PATH_TO_ANDROID_SDK in my machine. It seems that, it's regarding the android sdk path setup. Hence, it could also be set in ANDROID_HOME env. variable too.

Run jar file in command prompt

Try this

java -jar <jar-file-name>.jar

How to append one file to another in Linux from the shell?

You can also do this without cat, though honestly cat is more readable:

>> file1 < file2

The >> appends STDIN to file1 and the < dumps file2 to STDIN.

NuGet behind a proxy

To anyone using VS2015: I was encountering a "407 Proxy Authentication required" error, which broke my build. After a few hours investigating, it turns out MSBuild wasn't sending credentials when trying to download Nuget as part of the 'DownloadNuGet' target. The solution was to add the following XML to C:\Program Files (x86)\MSBuild\14.0\Bin\MSBuild.exe.config inside the <configuration> element:

<system.net>
            <defaultProxy useDefaultCredentials="true">
            </defaultProxy>
</system.net>

What does "Failure [INSTALL_FAILED_OLDER_SDK]" mean in Android Studio?

Make sure you don't have a minSdkVersion set in your build.gradle with a value higher than 8. If you don't specify it at all, it's supposed to use the value in your AndroidManfiest.xml, which seems to already be properly set.

SMTP Connect() failed. Message was not sent.Mailer error: SMTP Connect() failed

To get it working, I had to go to myaccount.google.com -> "connected apps & sites", and turn "Allow less secure apps" to "ON" (near the bottom of the page).