Programs & Examples On #Argparse

A Python module for implementing command-line interfaces

Argparse optional positional arguments?

parser.add_argument also has a switch required. You can use required=False. Here is a sample snippet with Python 2.7:

parser = argparse.ArgumentParser(description='get dir')
parser.add_argument('--dir', type=str, help='dir', default=os.getcwd(), required=False)
args = parser.parse_args()

Why use argparse rather than optparse?

As of python 2.7, optparse is deprecated, and will hopefully go away in the future.

argparse is better for all the reasons listed on its original page (https://code.google.com/archive/p/argparse/):

  • handling positional arguments
  • supporting sub-commands
  • allowing alternative option prefixes like + and /
  • handling zero-or-more and one-or-more style arguments
  • producing more informative usage messages
  • providing a much simpler interface for custom types and actions

More information is also in PEP 389, which is the vehicle by which argparse made it into the standard library.

Argparse: Required arguments listed under "optional arguments"?

Building off of @Karl Rosaen

parser = argparse.ArgumentParser()
optional = parser._action_groups.pop() # Edited this line
required = parser.add_argument_group('required arguments')
# remove this line: optional = parser...
required.add_argument('--required_arg', required=True)
optional.add_argument('--optional_arg')
parser._action_groups.append(optional) # added this line
return parser.parse_args()

and this outputs:

usage: main.py [-h] [--required_arg REQUIRED_ARG]
           [--optional_arg OPTIONAL_ARG]

required arguments:
  --required_arg REQUIRED_ARG

optional arguments:
  -h, --help                    show this help message and exit
  --optional_arg OPTIONAL_ARG

Check if argparse optional argument is set or not

In order to address @kcpr's comment on the (currently accepted) answer by @Honza Osobne

Unfortunately it doesn't work then the argument got it's default value defined.

one can first check if the argument was provided by comparing it with the Namespace object and providing the default=argparse.SUPPRESS option (see @hpaulj's and @Erasmus Cedernaes answers and this python3 doc) and if it hasn't been provided, then set it to a default value.

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--infile', default=argparse.SUPPRESS)
args = parser.parse_args()
if 'infile' in args: 
    # the argument is in the namespace, it's been provided by the user
    # set it to what has been provided
    theinfile = args.infile
    print('argument \'--infile\' was given, set to {}'.format(theinfile))
else:
    # the argument isn't in the namespace
    # set it to a default value
    theinfile = 'your_default.txt'
    print('argument \'--infile\' was not given, set to default {}'.format(theinfile))

Usage

$ python3 testargparse_so.py
argument '--infile' was not given, set to default your_default.txt

$ python3 testargparse_so.py --infile user_file.txt
argument '--infile' was given, set to user_file.txt

Python argparse command line flags without arguments

As you have it, the argument w is expecting a value after -w on the command line. If you are just looking to flip a switch by setting a variable True or False, have a look here (specifically store_true and store_false)

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-w', action='store_true')

where action='store_true' implies default=False.

Conversely, you could haveaction='store_false', which implies default=True.

Display help message with python argparse when script is called without any arguments

Set your positional arguments with nargs, and check if positional args are empty.

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('file', nargs='?')
args = parser.parse_args()
if not args.file:
    parser.print_help()

Reference Python nargs

argparse module How to add option without any argument?

As @Felix Kling suggested use action='store_true':

>>> from argparse import ArgumentParser
>>> p = ArgumentParser()
>>> _ = p.add_argument('-f', '--foo', action='store_true')
>>> args = p.parse_args()
>>> args.foo
False
>>> args = p.parse_args(['-f'])
>>> args.foo
True

How can I pass a list as a command-line argument with argparse?

I prefer passing a delimited string which I parse later in the script. The reasons for this are; the list can be of any type int or str, and sometimes using nargs I run into problems if there are multiple optional arguments and positional arguments.

parser = ArgumentParser()
parser.add_argument('-l', '--list', help='delimited list input', type=str)
args = parser.parse_args()
my_list = [int(item) for item in args.list.split(',')]

Then,

python test.py -l "265340,268738,270774,270817" [other arguments]

or,

python test.py -l 265340,268738,270774,270817 [other arguments]

will work fine. The delimiter can be a space, too, which would though enforce quotes around the argument value like in the example in the question.

Or you can use a lambda type as suggested in the comments by Chepner:

parser.add_argument('-l', '--list', help='delimited list input', 
    type=lambda s: [int(item) for item in s.split(',')])

Python argparse: default value or specified value

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--example', nargs='?', const=1, type=int)
args = parser.parse_args()
print(args)

% test.py 
Namespace(example=None)
% test.py --example
Namespace(example=1)
% test.py --example 2
Namespace(example=2)

  • nargs='?' means 0-or-1 arguments
  • const=1 sets the default when there are 0 arguments
  • type=int converts the argument to int

If you want test.py to set example to 1 even if no --example is specified, then include default=1. That is, with

parser.add_argument('--example', nargs='?', const=1, type=int, default=1)

then

% test.py 
Namespace(example=1)

Parsing boolean values with argparse

I think the most canonical way will be:

parser.add_argument('--ensure', nargs='*', default=None)

ENSURE = config.ensure is None

Simple argparse example wanted: 1 argument, 3 results

The simplest answer!

P.S. the one who wrote the document of argparse is foolish

python code:

import argparse
parser = argparse.ArgumentParser(description='')
parser.add_argument('--o_dct_fname',type=str)
parser.add_argument('--tp',type=str)
parser.add_argument('--new_res_set',type=int)
args = parser.parse_args()
o_dct_fname = args.o_dct_fname
tp = args.tp
new_res_set = args.new_res_set

running code

python produce_result.py --o_dct_fname o_dct --tp father_child --new_res_set 1

Find a file in python

If you are working with Python 2 you have a problem with infinite recursion on windows caused by self-referring symlinks.

This script will avoid following those. Note that this is windows-specific!

import os
from scandir import scandir
import ctypes

def is_sym_link(path):
    # http://stackoverflow.com/a/35915819
    FILE_ATTRIBUTE_REPARSE_POINT = 0x0400
    return os.path.isdir(path) and (ctypes.windll.kernel32.GetFileAttributesW(unicode(path)) & FILE_ATTRIBUTE_REPARSE_POINT)

def find(base, filenames):
    hits = []

    def find_in_dir_subdir(direc):
        content = scandir(direc)
        for entry in content:
            if entry.name in filenames:
                hits.append(os.path.join(direc, entry.name))

            elif entry.is_dir() and not is_sym_link(os.path.join(direc, entry.name)):
                try:
                    find_in_dir_subdir(os.path.join(direc, entry.name))
                except UnicodeDecodeError:
                    print "Could not resolve " + os.path.join(direc, entry.name)
                    continue

    if not os.path.exists(base):
        return
    else:
        find_in_dir_subdir(base)

    return hits

It returns a list with all paths that point to files in the filenames list. Usage:

find("C:\\", ["file1.abc", "file2.abc", "file3.abc", "file4.abc", "file5.abc"])

make div's height expand with its content

Looks like this works

html {
 width:100%;
 height:auto;
 min-height:100%
} 

It takes the screen size as minimum, and if the content expands it grows.

password for postgres

Set the default password in the .pgpass file. If the server does not save the password, it is because it is not set in the .pgpass file, or the permissions are open and the file is therefore ignored.

Read more about the password file here.

Also, be sure to check the permissions: on *nix systems the permissions on .pgpass must disallow any access to world or group; achieve this by the command chmod 0600 ~/.pgpass. If the permissions are less strict than this, the file will be ignored.

Have you tried logging-in using PGAdmin? You can save the password there, and modify the pgpass file.

How to specify an alternate location for the .m2 folder or settings.xml permanently?

It's funny how other answers ignore the fact that you can't write to that file...

There are a few workarounds that come to my mind which could help use an arbitrary C:\redirected\settings.xml and use the mvn command as usual happily ever after.

mvn alias

In a Unix shell (or on Cygwin) you can create

alias mvn='mvn --global-settings "C:\redirected\settings.xml"'

so when you're calling mvn blah blah from anywhere the config is "automatically" picked up.
See How to create alias in cmd? if you want this, but don't have a Unix shell.

mvn wrapper

Configure your environment so that mvn is resolved to a wrapper script when typed in the command line:

  • Remove your MVN_HOME/bin or M2_HOME/bin from your PATH so mvn is not resolved any more.
  • Add a folder to PATH (or use an existing one)
  • In that folder create an mvn.bat file with contents:

    call C:\your\path\to\maven\bin\mvn.bat --global-settings "C:\redirected\settings.xml" %*
    

Note: if you want some projects to behave differently you can just create mvn.bat in the same folder as pom.xml so when you run plain mvn it resolves to the local one.

Use where mvn at any time to check how it is resolved, the first one will be run when you type mvn.

mvn.bat hack

If you have write access to C:\your\path\to\maven\bin\mvn.bat, edit the file and add set MAVEN_CMD_LINE_ARG to the :runm2 part:

@REM Start MAVEN2
:runm2
set MAVEN_CMD_LINE_ARGS=--global-settings "C:\redirected\settings.xml" %MAVEN_CMD_LINE_ARGS%
set CLASSWORLDS_LAUNCHER=...

mvn.sh hack

For completeness, you can change the C:\your\path\to\maven\bin\mvn shell script too by changing the exec "$JAVACMD" command's

${CLASSWORLDS_LAUNCHER} "$@"

part to

${CLASSWORLDS_LAUNCHER} --global-settings "C:\redirected\settings.xml" "$@"

Suggestion/Rant

As a person in IT it's funny that you don't have access to your own home folder, for me this constitutes as incompetence from the company you're working for: this is equivalent of hiring someone to do software development, but not providing even the possibility to use anything other than notepad.exe or Microsoft Word to edit the source files. I'd suggest to contact your help desk or administrator and request write access at least to that particular file so that you can change the path of the local repository.

Disclaimer: None of these are tested for this particular use case, but I successfully used all of them previously for various other software.

CodeIgniter activerecord, retrieve last insert id?

if($this->db->insert('Your_tablename', $your_data)) {
    return $this->db->insert_id();
}
return false 

How do I convert a org.w3c.dom.Document object to a String?

If you are ok to do transformation, you may try this.

DocumentBuilderFactory domFact = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = domFact.newDocumentBuilder();
Document doc = builder.parse(st);
DOMSource domSource = new DOMSource(doc);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.transform(domSource, result);
System.out.println("XML IN String format is: \n" + writer.toString());

What is the convention for word separator in Java package names?

All three are not the conventions.

Use com.stackoverflow.mypackage.

The package names do not follow camel casing or underscores or hyphens package naming convention.

Also, Google Java Style Guide specifies exactly the same (i.e. com.stackoverflow.mypackage) convention:

5.2.1 Package names

Package names are all lowercase, with consecutive words simply concatenated together (no underscores). For example, com.example.deepspace, not com.example.deepSpace or com.example.deep_space.

Google Java Style Guide: 5.2 Rules by identifier type: 5.2.1 Package names.

Read url to string in few lines of java code

Here's Jeanne's lovely answer, but wrapped in a tidy function for muppets like me:

private static String getUrl(String aUrl) throws MalformedURLException, IOException
{
    String urlData = "";
    URL urlObj = new URL(aUrl);
    URLConnection conn = urlObj.openConnection();
    try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) 
    {
        urlData = reader.lines().collect(Collectors.joining("\n"));
    }
    return urlData;
}

How to inject JPA EntityManager using spring

Yes, although it's full of gotchas, since JPA is a bit peculiar. It's very much worth reading the documentation on injecting JPA EntityManager and EntityManagerFactory, without explicit Spring dependencies in your code:

http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/orm.html#orm-jpa

This allows you to either inject the EntityManagerFactory, or else inject a thread-safe, transactional proxy of an EntityManager directly. The latter makes for simpler code, but means more Spring plumbing is required.

How to debug "ImagePullBackOff"?

Run docker login

Push the image to docker hub

Re-create pod

This solved the problem for me. Hope it helps.

Is there any JSON Web Token (JWT) example in C#?

This is my implementation of (Google) JWT Validation in .NET. It is based on other implementations on Stack Overflow and GitHub gists.

using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Net.Http;
using System.Security.Claims;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;

namespace QuapiNet.Service
{
    public class JwtTokenValidation
    {
        public async Task<Dictionary<string, X509Certificate2>> FetchGoogleCertificates()
        {
            using (var http = new HttpClient())
            {
                var response = await http.GetAsync("https://www.googleapis.com/oauth2/v1/certs");

                var dictionary = await response.Content.ReadAsAsync<Dictionary<string, string>>();
                return dictionary.ToDictionary(x => x.Key, x => new X509Certificate2(Encoding.UTF8.GetBytes(x.Value)));
            }
        }

        private string CLIENT_ID = "xxx.apps.googleusercontent.com";

        public async Task<ClaimsPrincipal> ValidateToken(string idToken)
        {
            var certificates = await this.FetchGoogleCertificates();

            TokenValidationParameters tvp = new TokenValidationParameters()
            {
                ValidateActor = false, // check the profile ID

                ValidateAudience = true, // check the client ID
                ValidAudience = CLIENT_ID,

                ValidateIssuer = true, // check token came from Google
                ValidIssuers = new List<string> { "accounts.google.com", "https://accounts.google.com" },

                ValidateIssuerSigningKey = true,
                RequireSignedTokens = true,
                IssuerSigningKeys = certificates.Values.Select(x => new X509SecurityKey(x)),
                IssuerSigningKeyResolver = (token, securityToken, kid, validationParameters) =>
                {
                    return certificates
                    .Where(x => x.Key.ToUpper() == kid.ToUpper())
                    .Select(x => new X509SecurityKey(x.Value));
                },
                ValidateLifetime = true,
                RequireExpirationTime = true,
                ClockSkew = TimeSpan.FromHours(13)
            };

            JwtSecurityTokenHandler jsth = new JwtSecurityTokenHandler();
            SecurityToken validatedToken;
            ClaimsPrincipal cp = jsth.ValidateToken(idToken, tvp, out validatedToken);

            return cp;
        }
    }
}

Note that, in order to use it, you need to add a reference to the NuGet package System.Net.Http.Formatting.Extension. Without this, the compiler will not recognize the ReadAsAsync<> method.

Stop/Close webcam stream which is opened by navigator.mediaDevices.getUserMedia

Use any of these functions:

// stop both mic and camera
function stopBothVideoAndAudio(stream) {
    stream.getTracks().forEach(function(track) {
        if (track.readyState == 'live') {
            track.stop();
        }
    });
}

// stop only camera
function stopVideoOnly(stream) {
    stream.getTracks().forEach(function(track) {
        if (track.readyState == 'live' && track.kind === 'video') {
            track.stop();
        }
    });
}

// stop only mic
function stopAudioOnly(stream) {
    stream.getTracks().forEach(function(track) {
        if (track.readyState == 'live' && track.kind === 'audio') {
            track.stop();
        }
    });
}

TabLayout tab selection

you should use a viewPager to use viewPager.setCurrentItem()

 viewPager.setCurrentItem(n);
 tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                viewPager.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

What's a .sh file?

If you open your second link in a browser you'll see the source code:

#!/bin/bash
# Script to download individual .nc files from the ORNL
# Daymet server at: http://daymet.ornl.gov

[...]

# For ranges use {start..end}
# for individul vaules, use: 1 2 3 4 
for year in {2002..2003}
do
   for tile in {1159..1160}
        do wget --limit-rate=3m http://daymet.ornl.gov/thredds/fileServer/allcf/${year}/${tile}_${year}/vp.nc -O ${tile}_${year}_vp.nc
        # An example using curl instead of wget
    #do curl --limit-rate 3M -o ${tile}_${year}_vp.nc http://daymet.ornl.gov/thredds/fileServer/allcf/${year}/${tile}_${year}/vp.nc
     done
done

So it's a bash script. Got Linux?


In any case, the script is nothing but a series of HTTP retrievals. Both wget and curl are available for most operating systems and almost all language have HTTP libraries so it's fairly trivial to rewrite in any other technology. There're also some Windows ports of bash itself (git includes one). Last but not least, Windows 10 now has native support for Linux binaries.

MSVCP140.dll missing

That usually means that your friend does not have the Microsoft redistributable for Visual C++. I am of course assuming you are using VC++ and not MingW or another compiler. Since your friend does not have VS installed as well there is no guarantee he has the redist installed.

VC++ Distro

HTML5 Canvas and Anti-aliasing

Here's a workaround that requires you to draw lines pixel by pixel, but will prevent anti aliasing.

// some helper functions
// finds the distance between points
function DBP(x1,y1,x2,y2) {
    return Math.sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1));
}
// finds the angle of (x,y) on a plane from the origin
function getAngle(x,y) { return Math.atan(y/(x==0?0.01:x))+(x<0?Math.PI:0); }
// the function
function drawLineNoAliasing(ctx, sx, sy, tx, ty) {
    var dist = DBP(sx,sy,tx,ty); // length of line
    var ang = getAngle(tx-sx,ty-sy); // angle of line
    for(var i=0;i<dist;i++) {
        // for each point along the line
        ctx.fillRect(Math.round(sx + Math.cos(ang)*i), // round for perfect pixels
                     Math.round(sy + Math.sin(ang)*i), // thus no aliasing
                     1,1); // fill in one pixel, 1x1
    }
}

Basically, you find the length of the line, and step by step traverse that line, rounding each position, and filling in a pixel.

Call it with

var context = cv.getContext("2d");
drawLineNoAliasing(context, 20,30,20,50); // line from (20,30) to (20,50)

Java current machine name and logged in user?

To get the currently logged in user:

System.getProperty("user.name"); //platform independent 

and the hostname of the machine:

java.net.InetAddress localMachine = java.net.InetAddress.getLocalHost();
System.out.println("Hostname of local machine: " + localMachine.getHostName());

How do I resolve git saying "Commit your changes or stash them before you can merge"?

This solved my error:

I am on branch : "A"

git stash

Move to master branch:

git checkout master <br>
git pull*

Move back to my branch: "A"

git checkout A <br>
git stash pop*

Python 3: ImportError "No Module named Setuptools"

The solution which worked for me was to upgrade my setuptools:

python3 -m pip install --upgrade pip setuptools wheel

Copy data from one existing row to another existing row in SQL?

Maybe I read the problem wrong, but I believe you already have inserted the course 11 records and simply need to update those that meet the criteria you listed with course 6's data.

If this is the case, you'll want to use an UPDATE...FROM statement:

UPDATE MyTable
SET
    complete = 1,
    complete_date = newdata.complete_date,
    post_score = newdata.post_score
FROM
    (
    SELECT
        userID,
        complete_date,
        post_score
    FROM MyTable
    WHERE
        courseID = 6
        AND complete = 1
        AND complete_date > '8/1/2008'
    ) newdata
WHERE
    CourseID = 11
    AND userID = newdata.userID

See this related SO question for more info

How to display a list inline using Twitter's Bootstrap

According to the Bootstrap documentation, you need to add the class 'inline' to your list; like this:

<ul class="inline">
    <li>Item one</li>
    <li>Item two</li>
    <li>Item three</li>
</ul>

However, this does not work as there seems to be some CSS missing in the Bootstrap CSS file referring to the class 'inline'. So additionally, add the following lines to your CSS file to make it work:

ul.inline > li, ol.inline > li {
    display: inline-block;
    padding-right: 5px;
    padding-left: 5px;
}

How to query first 10 rows and next time query other 10 rows from table

Just use the LIMIT clause.

SELECT * FROM `msgtable` WHERE `cdate`='18/07/2012' LIMIT 10

And from the next call you can do this way:

SELECT * FROM `msgtable` WHERE `cdate`='18/07/2012' LIMIT 10 OFFSET 10

More information on OFFSET and LIMIT on LIMIT and OFFSET.

Using variables in Nginx location rules

You can't. Nginx doesn't really support variables in config files, and its developers mock everyone who ask for this feature to be added:

"[Variables] are rather costly compared to plain static configuration. [A] macro expansion and "include" directives should be used [with] e.g. sed + make or any other common template mechanism." http://nginx.org/en/docs/faq/variables_in_config.html

You should either write or download a little tool that will allow you to generate config files from placeholder config files.

Update The code below still works, but I've wrapped it all up into a small PHP program/library called Configurator also on Packagist, which allows easy generation of nginx/php-fpm etc config files, from templates and various forms of config data.

e.g. my nginx source config file looks like this:

location  / {
    try_files $uri /routing.php?$args;
    fastcgi_pass   unix:%phpfpm.socket%/php-fpm-www.sock;
    include       %mysite.root.directory%/conf/fastcgi.conf;
}

And then I have a config file with the variables defined:

phpfpm.socket=/var/run/php-fpm.socket
mysite.root.directory=/home/mysite

And then I generate the actual config file using that. It looks like you're a Python guy, so a PHP based example may not help you, but for anyone else who does use PHP:

<?php

require_once('path.php');

$filesToGenerate = array(
    'conf/nginx.conf' => 'autogen/nginx.conf',
    'conf/mysite.nginx.conf' => 'autogen/mysite.nginx.conf',
    'conf/mysite.php-fpm.conf' => 'autogen/mysite.php-fpm.conf',
    'conf/my.cnf' => 'autogen/my.cnf',
);

$environment = 'amazonec2';

if ($argc >= 2){
    $environmentRequired = $argv[1];

    $allowedVars = array(
        'amazonec2',
        'macports',
    );

    if (in_array($environmentRequired, $allowedVars) == true){
        $environment = $environmentRequired;
    }
}
else{
    echo "Defaulting to [".$environment."] environment";
}

$config = getConfigForEnvironment($environment);

foreach($filesToGenerate as $inputFilename => $outputFilename){
    generateConfigFile(PATH_TO_ROOT.$inputFilename, PATH_TO_ROOT.$outputFilename, $config);
}


function    getConfigForEnvironment($environment){
    $config = parse_ini_file(PATH_TO_ROOT."conf/deployConfig.ini", TRUE);
    $configWithMarkers = array();
    foreach($config[$environment] as $key => $value){
        $configWithMarkers['%'.$key.'%'] = $value;
    }

    return  $configWithMarkers;
}


function    generateConfigFile($inputFilename, $outputFilename, $config){

    $lines = file($inputFilename);

    if($lines === FALSE){
        echo "Failed to read [".$inputFilename."] for reading.";
        exit(-1);
    }

    $fileHandle = fopen($outputFilename, "w");

    if($fileHandle === FALSE){
        echo "Failed to read [".$outputFilename."] for writing.";
        exit(-1);
    }

    $search = array_keys($config);
    $replace = array_values($config);

    foreach($lines as $line){
        $line = str_replace($search, $replace, $line);
        fwrite($fileHandle, $line);
    }

    fclose($fileHandle);
}

?>

And then deployConfig.ini looks something like:

[global]

;global variables go here.

[amazonec2]
nginx.log.directory = /var/log/nginx
nginx.root.directory = /usr/share/nginx
nginx.conf.directory = /etc/nginx
nginx.run.directory  = /var/run
nginx.user           = nginx

[macports]
nginx.log.directory = /opt/local/var/log/nginx
nginx.root.directory = /opt/local/share/nginx
nginx.conf.directory = /opt/local/etc/nginx
nginx.run.directory  = /opt/local/var/run
nginx.user           = _www

php - How do I fix this illegal offset type error

check $xml->entry[$i] exists and is an object before trying to get a property of it

 if(isset($xml->entry[$i]) && is_object($xml->entry[$i])){
   $source = $xml->entry[$i]->source;          
   $s[$source] += 1;
 }

or $source might not be a legal array offset but an array, object, resource or possibly null

SQL 'like' vs '=' performance

You are asking the wrong question. In databases is not the operator performance that matters, is always the SARGability of the expression, and the coverability of the overall query. Performance of the operator itself is largely irrelevant.

So, how do LIKE and = compare in terms of SARGability? LIKE, when used with an expression that does not start with a constant (eg. when used LIKE '%something') is by definition non-SARGabale. But does that make = or LIKE 'something%' SARGable? No. As with any question about SQL performance the answer does not lie with the query of the text, but with the schema deployed. These expression may be SARGable if an index exists to satisfy them.

So, truth be told, there are small differences between = and LIKE. But asking whether one operator or other operator is 'faster' in SQL is like asking 'What goes faster, a red car or a blue car?'. You should eb asking questions about the engine size and vechicle weight, not about the color... To approach questions about optimizing relational tables, the place to look is your indexes and your expressions in the WHERE clause (and other clauses, but it usually starts with the WHERE).

How to install a private NPM module without my own registry?

I had this same problem, and after some searching around, I found Reggie (https://github.com/mbrevoort/node-reggie). It looks pretty solid. It allows for lightweight publishing of NPM modules to private servers. Not perfect (no authentication upon installation), and it's still really young, but I tested it locally, and it seems to do what it says it should do.

That is... (and this just from their docs)

npm install -g reggie
reggie-server -d ~/.reggie

then cd into your module directory and...

reggie -u http://<host:port> publish 
reggie -u http://127.0.0.1:8080 publish 

finally, you can install packages from reggie just by using that url either in a direct npm install command, or from within a package.json... like so

npm install http://<host:port>/package/<name>/<version>
npm install http://<host:port>/package/foo/1.0.0

or..

dependencies: {
    "foo": "http://<host:port>/package/foo/1.0.0"
}

Remove Project from Android Studio

You must close the project, hover over the project in the welcome screen, then press the delete button.

How do I pass JavaScript values to Scriptlet in JSP?

This is for other people landing here. First of all you need a servlet. I used a @POST request. Now in your jsp file you have two ways to do this:

  1. The complicated way with AJAX, in case you are new to jsp: You need to do a post with the javascript var that you want to use in you java class and use JSP to call your java function from inside your request:

    $(document).ready(function() {
        var sendVar = "hello";
        $('#domId').click(function (e)
        {                               
            $.ajax({
                type: "post",
                url: "/", //or whatever your url is
                data: "var=" + sendVar ,
                success: function(){      
                        console.log("success: " + sendVar );                            
                      <% 
                          String received= request.getParameter("var");
    
                          if(received == null || received.isEmpty()){
                              received = "some default value";
                          }
                          MyJavaClass.processJSvar(received); 
                      %>;                            
    
                }
            });
        });
    
    });
    
  2. The easy way just with JSP:

    <form id="myform" method="post" action="http://localhost:port/index.jsp">
         <input type="hidden" name="inputName" value=""/>
                   <% 
                          String pg = request.getParameter("inputName");
    
                          if(pg == null || pg.isEmpty()){
                              pg = "some default value";
                          }
                          DatasyncMain.changeToPage(pg); 
                      %>;     
    </form>
    

Of course in this case you still have to load the input value from JS (so far I haven't figured out another way to load it).

Handler "ExtensionlessUrlHandler-Integrated-4.0" has a bad module "ManagedPipelineHandler" in its module list

I'm working on Windows Server 2012. .NET Extensibility 4.5 feature is on. WebDAVModule removed. I was still getting 500.21 error on ASP.NET route '/docs'.

Changing 'skipManagedModules' to false fixed the problem.

<applicationInitialization doAppInitAfterRestart="true" skipManagedModules="false">
        <add initializationPage="/docs" />    
</applicationInitialization>

Thanks to https://groups.google.com/forum/#!topic/bonobo-git-server/GbdMXdDO4tI

How do you set a default value for a MySQL Datetime column?

If you have already created the table then you can use

To change default value to current date time

ALTER TABLE <TABLE_NAME> 
CHANGE COLUMN <COLUMN_NAME> <COLUMN_NAME> DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP;

To change default value to '2015-05-11 13:01:01'

ALTER TABLE <TABLE_NAME> 
CHANGE COLUMN <COLUMN_NAME> <COLUMN_NAME> DATETIME NOT NULL DEFAULT '2015-05-11 13:01:01';

change image opacity using javascript

In fact, you need to use CSS.

document.getElementById("myDivId").setAttribute("style","opacity:0.5; -moz-opacity:0.5; filter:alpha(opacity=50)");

It works on FireFox, Chrome and IE.

How to vertical align an inline-block in a line of text?

display: inline-block is your friend you just need all three parts of the construct - before, the "block", after - to be one, then you can vertically align them all to the middle:

Working Example

(it looks like your picture anyway ;))

CSS:

p, div {
  display: inline-block; 
  vertical-align: middle;
}
p, div {
  display: inline !ie7; /* hack for IE7 and below */
}

table {
  background: #000; 
  color: #fff; 
  font-size: 16px; 
  font-weight: bold; margin: 0 10px;
}

td {
  padding: 5px; 
  text-align: center;
}

HTML:

<p>some text</p> 
<div>
  <table summary="">
  <tr><td>A</td></tr>
  <tr><td>B</td></tr>
  <tr><td>C</td></tr>
  <tr><td>D</td></tr>
  </table>
</div> 
<p>continues afterwards</p>

Change default text in input type="file"?

_x000D_
_x000D_
$(document).ready(function () {_x000D_
 $('#choose-file').change(function () {_x000D_
  var i = $(this).prev('label').clone();_x000D_
  var file = $('#choose-file')[0].files[0].name;_x000D_
  $(this).prev('label').text(file);_x000D_
 }); _x000D_
 });
_x000D_
.custom-file-upload{_x000D_
  background: #f7f7f7; _x000D_
  padding: 8px;_x000D_
  border: 1px solid #e3e3e3; _x000D_
  border-radius: 5px; _x000D_
  border: 1px solid #ccc; _x000D_
  display: inline-block;_x000D_
  padding: 6px 12px;_x000D_
  cursor: pointer;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
can you try this_x000D_
_x000D_
<label for="choose-file" class="custom-file-upload" id="choose-file-label">_x000D_
   Upload Document_x000D_
</label>_x000D_
<input name="uploadDocument" type="file" id="choose-file" _x000D_
   accept=".jpg,.jpeg,.pdf,doc,docx,application/msword,.png" style="display: none;" />
_x000D_
_x000D_
_x000D_

Appending to an object

Try this:

alerts.splice(0,0,{"app":"goodbyeworld","message":"cya"});

Works pretty well, it'll add it to the start of the array.

Use a cell value in VBA function with a variable

No need to activate or selection sheets or cells if you're using VBA. You can access it all directly. The code:

Dim rng As Range
For Each rng In Sheets("Feuil2").Range("A1:A333")
    Sheets("Classeur2.csv").Cells(rng.Value, rng.Offset(, 1).Value) = "1"
Next rng

is producing the same result as Joe's code.

If you need to switch sheets for some reasons, use Application.ScreenUpdating = False at the beginning of your macro (and Application.ScreenUpdating=True at the end). This will remove the screenflickering - and speed up the execution.

How to set the maximum memory usage for JVM?

If you want to limit memory for jvm (not the heap size ) ulimit -v

To get an idea of the difference between jvm and heap memory , take a look at this excellent article http://blogs.vmware.com/apps/2011/06/taking-a-closer-look-at-sizing-the-java-process.html

How to enable authentication on MongoDB through Docker?

Better solutions for furthering:
https://blog.madisonhub.org/setting-up-a-mongodb-server-with-auth-on-docker/ https://docs.mongodb.com/v2.6/tutorial/add-user-administrator/

Here's what I did for the same problem, and it worked.

  1. Run the mongo docker instance on your server

    docker run -d -p 27017:27017 -v ~/dataMongo:/data/db mongo
    
  2. Open bash on the running docker instance.

    docker ps
    

    CONTAINER IDIMAGE COMMAND CREATED STATUS PORTS NAMES

    b07599e429fb mongo "docker-entrypoint..." 35 minutes ago Up 35 minutes 0.0.0.0:27017->27017/tcp musing_stallman

    docker exec -it b07599e429fb bash
    root@b07599e429fb:/#
    

    Reference- https://github.com/arunoda/meteor-up-legacy/wiki/Accessing-the-running-Mongodb-docker-container-from-command-line-on-EC2

  3. Enter the mongo shell by typing mongo.

    root@b07599e429fb:/# mongo
    
  4. For this example, I will set up a user named ian and give that user read & write access to the cool_db database.

    > use cool_db
    
    > db.createUser({
        user: 'ian',
        pwd: 'secretPassword',
        roles: [{ role: 'readWrite', db:'cool_db'}]
    })
    

    Reference: https://ianlondon.github.io/blog/mongodb-auth/ (First point only)

  5. Exit from mongod shell and bash.

  6. Stop the docker instance using the below command.

    docker stop mongo
    
  7. Now run the mongo docker with auth enabled.

    docker run -d -p 27017:27017 -v ~/dataMongo:/data/db mongo mongod --auth
    

    Reference: How to enable authentication on MongoDB through Docker? (Usman Ismail's answer to this question)

  8. I was able to connect to the instance running on a Google Cloud server from my local windows laptop using the below command.

    mongo <ip>:27017/cool_db -u ian -p secretPassword
    

    Reference: how can I connect to a remote mongo server from Mac OS terminal

Simple way to count character occurrences in a string

Something a bit more functional, without Regex:

public static int count(String s, char c) {
    return s.length()==0 ? 0 : (s.charAt(0)==c ? 1 : 0) + count(s.substring(1),c);
}

It's no tail recursive, for the sake of clarity.

All possible array initialization syntaxes

Just a note

The following arrays:

string[] array = new string[2];
string[] array2 = new string[] { "A", "B" };
string[] array3 = { "A" , "B" };
string[] array4 = new[] { "A", "B" };

Will be compiled to:

string[] array = new string[2];
string[] array2 = new string[] { "A", "B" };
string[] array3 = new string[] { "A", "B" };
string[] array4 = new string[] { "A", "B" };

What is @ModelAttribute in Spring MVC?

I know this is an old thread, but I thought I throw my hat in the ring and see if I can muddy the water a little bit more :)

I found my initial struggle to understand @ModelAttribute was a result of Spring's decision to combine several annotations into one. It became clearer once I split it into several smaller annotations:

For parameter annotations, think of @ModelAttribute as the equivalent of @Autowired + @Qualifier i.e. it tries to retrieve a bean with the given name from the Spring managed model. If the named bean is not found, instead of throwing an error or returning null, it implicitly takes on the role of @Bean i.e. Create a new instance using the default constructor and add the bean to the model.

For method annotations, think of @ModelAttribute as the equivalent of @Bean + @Before, i.e. it puts the bean constructed by user's code in the model and it's always called before a request handling method.

Figuratively, I see @ModelAttribute as the following (please don't take it literally!!):

@Bean("person")
@Before
public Person createPerson(){
  return new Person();
}

@RequestMapping(...)
public xxx handlePersonRequest( (@Autowired @Qualifier("person") | @Bean("person")) Person person, xxx){
  ...
}

As you can see, Spring made the right decision to make @ModelAttribute an all-encompassing annotation; no one wants to see an annotation smorgasbord.

How to get the background color code of an element in hex?

Adding on @Newred solution. If your style has more than just the background-color you can use this:

$(this).attr('style').split(';').filter(item => item.startsWith('background-color'))[0].split(":")[1]

Application_Start not firing?

I had made some changes based on "Code Analysis on Build" from Visual Studio. Code Analysis suggested "CA1822 Mark members as static" for Application_Start() in Global.asax. I did that and ended up with this problem.

I suggest suppressing this Code Analysis message, and not alter the signature of methods/classes automatically created by platform used for bootstrapping the Application. The signature of the method Application_Start probably was non-static for a reason.

I reverted to this method-signature and Application_Start() was firing again:

    protected void Application_Start()
    { ... }

How do you subtract Dates in Java?

Here's the basic approach,

DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

Date beginDate = dateFormat.parse("2013-11-29");
Date endDate = dateFormat.parse("2013-12-4");

Calendar beginCalendar = Calendar.getInstance();
beginCalendar.setTime(beginDate);

Calendar endCalendar = Calendar.getInstance();
endCalendar.setTime(endDate);

There is simple way to implement it. We can use Calendar.add method with loop. The minus days between beginDate and endDate, and the implemented code as below,

int minusDays = 0;
while (true) {
  minusDays++;

  // Day increasing by 1
  beginCalendar.add(Calendar.DAY_OF_MONTH, 1);

  if (dateFormat.format(beginCalendar.getTime()).
            equals(dateFormat.format(endCalendar).getTime())) {
    break;
  }
}
System.out.println("The subtraction between two days is " + (minusDays + 1));**

Console logging for react?

If you want to log inside JSX you can create a dummy component
which plugs where you wish to log:

_x000D_
_x000D_
const Console = prop => (
  console[Object.keys(prop)[0]](...Object.values(prop))
  ,null // ? React components must return something 
)

// Some component with JSX and a logger inside
const App = () => 
  <div>
    <p>imagine this is some component</p>
    <Console log='foo' />
    <p>imagine another component</p>
    <Console warn='bar' />
  </div>

// Render 
ReactDOM.render(
  <App />,
  document.getElementById("react")
)
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react"></div>
_x000D_
_x000D_
_x000D_

javascript /jQuery - For Loop

.each() should work for you. http://api.jquery.com/jQuery.each/ or http://api.jquery.com/each/ or you could use .map.

var newArray = $(array).map(function(i) {
    return $('#event' + i, response).html();
});

Edit: I removed the adding of the prepended 0 since it is suggested to not use that.

If you must have it use

var newArray = $(array).map(function(i) {
    var number = '' + i;
    if (number.length == 1) {
        number = '0' + number;
    }   
    return $('#event' + number, response).html();
});

How to generate and validate a software license key?

You can use a free third party solution to handle this for you such as Quantum-Key.Net It's free and handles payments via paypal through a web sales page it creates for you, key issuing via email and locks key use to a specific computer to prevent piracy.

Your should also take care to obfuscate/encrypt your code or it can easily be reverse engineered using software such as De4dot and .NetReflector. A good free code obfuscator is ConfuserEx wich is fast and simple to use and more effective than expensive alternatives.

You should run your finished software through De4Dot and .NetReflector to reverse-engineer it and see what a cracker would see if they did the same thing and to make sure you have not left any important code exposed or undisguised.

Your software will still be crackable but for the casual cracker it may well be enough to put them off and these simple steps will also prevent your code being extracted and re-used.

https://quantum-key.net

How to use ConfuserEx?

https://github.com/0xd4d/de4dot

https://www.red-gate.com/dynamic/products/dotnet-development/reflector/download

How to fetch the dropdown values from database and display in jsp

  1. Make the database connection and retrieve the query result.
  2. Traverse through the result and display the query results.

The example code below demonstrates this in detail.

<%@page import="java.sql.*, java.io.*,listresult"%> //import the required library

<%

String label = request.getParameter("label"); // retrieving a variable from a previous page

Connection dbc = null; //Make connection to the database
Class.forName("com.mysql.jdbc.Driver");
dbc = DriverManager.getConnection("jdbc:mysql://localhost:3306/works", "root", "root");
if (dbc != null) 
{
    System.out.println("Connection successful");
}

ResultSet rs = listresult.dbresult.func(dbc, label); //This function is in the end. The function is defined in another package- listresult

%>

<form name="demo form" method="post">

    <table>
        <tr>
            <td>
                Label Name:
            </td>

            <td>
                <input type="text" name="label" value="<%=rs.getString("labelname")%>">
            </td>

            <td>
                <select name="label">
                <option value="">SELECT</option>

                <% while (rs.next()) {%>

                    <option value="<%=rs.getString("lname")%>"><%=rs.getString("lname")%>
                    </option>

                <%}%>
                </select>
            </td>
        </tr>
    </table>

</form>

//The function:

public static ResultSet func(Connection dbc, String x)
{
    ResultSet rs = null;
    String sql;
    PreparedStatement pst;
    try
    {
        sql = "select lname from demo where label like '" + x + "'";
        pst = dbc.prepareStatement(sql);
        rs = pst.executeQuery();
    } 
    catch (Exception e) 
    {
        e.printStackTrace();
        String sqlMessage = e.getMessage();
    }
    return rs;
}

I have tried to make this example as detailed as possible. Do ask if you have any queries.

How do I change a PictureBox's image?

You can use the ImageLocation property of pictureBox1:

pictureBox1.ImageLocation = @"C:\Users\MSI\Desktop\MYAPP\Slider\Slider\bt1.jpg";

Class method differences in Python: bound, unbound and static

that is an error.

first of all, first line should be like this (be careful of capitals)

class Test(object):

Whenever you call a method of a class, it gets itself as the first argument (hence the name self) and method_two gives this error

>>> a.method_two()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: method_two() takes no arguments (1 given)

Android: show soft keyboard automatically when focus is on an EditText

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

I call this in onCreate() to show keyboard automatically, when I came in the Activity.

How to get instance variables in Python?

Suggest

>>> print vars.__doc__
vars([object]) -> dictionary

Without arguments, equivalent to locals().
With an argument, equivalent to object.__dict__.

In otherwords, it essentially just wraps __dict__

Change directory in Node.js command prompt

If you mean to change default directory for "Node.js command prompt", when you launch it, then (Windows case)

  1. go the directory where NodeJS was installed
  2. find file nodevars.bat
  3. open it with editor as administrator
  4. change the default path in the row which looks like

    if "%CD%\"=="%~dp0" cd /d "%HOMEDRIVE%%HOMEPATH%"
    

with your path. It could be for example

    if "%CD%\"=="%~dp0" cd /d "c://MyDirectory/"

if you mean to change directory once when you launched "Node.js command prompt", then execute the following command in the Node.js command prompt:

     cd c:/MyDirectory/

Is it possible to insert HTML content in XML document?

The purpose of BASE64 encoding is to take binary data and be able to persist that to a string. That benefit comes at a cost, an increase in the size of the result (I think it's a 4 to 3 ratio). There are two solutions. If you know the data will be well formed XML, include it directly. The other, an better option, is to include the HTML in a CDATA section within an element within the XML.

Converting serial port data to TCP/IP in a Linux environment

All the tools you would need are already available to you on most modern distributions of Linux.

As several have pointed out you can pipe the serial data through netcat. However you would need to relaunch a new instance each time there is a connection. In order to have this persist between connections you can create a xinetd service using the following configuration:

service testservice
{
    port        = 5900
    socket_type = stream
    protocol    = tcp
    wait        = yes
    user        = root
    server      = /usr/bin/netcat
    server_args = "-l 5900 < /dev/ttyS0"
}

Be sure to change the /dev/ttyS0 to match the serial device you are attempting to interface with.

SQL Server: Maximum character length of object names

128 characters. This is the max length of the sysname datatype (nvarchar(128)).

How to access the request body when POSTing using Node.js and Express?

This can be achieved without body-parser dependency as well, listen to request:data and request:end and return the response on end of request, refer below code sample. ref:https://nodejs.org/en/docs/guides/anatomy-of-an-http-transaction/#request-body

var express = require('express');
var app = express.createServer(express.logger());

app.post('/', function(request, response) {

    // push the data to body
    var body = [];
    request.on('data', (chunk) => {
      body.push(chunk);
    }).on('end', () => {
      // on end of data, perform necessary action
      body = Buffer.concat(body).toString();
      response.write(request.body.user);
      response.end();
    });
});

How to do a less than or equal to filter in Django queryset?

Less than or equal:

User.objects.filter(userprofile__level__lte=0)

Greater than or equal:

User.objects.filter(userprofile__level__gte=0)

Likewise, lt for less than and gt for greater than. You can find them all in the documentation.

How to add column to numpy array

The easiest solution is to use numpy.insert().

The Advantage of np.insert() over np.append is that you can insert the new columns into custom indices.

import numpy as np

X = np.arange(20).reshape(10,2)

X = np.insert(X, [0,2], np.random.rand(X.shape[0]*2).reshape(-1,2)*10, axis=1)
'''

How do I get the first element from an IEnumerable<T> in .net?

If you can use LINQ you can use:

var e = enumerable.First();

This will throw an exception though if enumerable is empty: in which case you can use:

var e = enumerable.FirstOrDefault();

FirstOrDefault() will return default(T) if the enumerable is empty, which will be null for reference types or the default 'zero-value' for value types.

If you can't use LINQ, then your approach is technically correct and no different than creating an enumerator using the GetEnumerator and MoveNext methods to retrieve the first result (this example assumes enumerable is an IEnumerable<Elem>):

Elem e = myDefault;
using (IEnumerator<Elem> enumer = enumerable.GetEnumerator()) {
    if (enumer.MoveNext()) e = enumer.Current;
}

Joel Coehoorn mentioned .Single() in the comments; this will also work, if you are expecting your enumerable to contain exactly one element - however it will throw an exception if it is either empty or larger than one element. There is a corresponding SingleOrDefault() method that covers this scenario in a similar fashion to FirstOrDefault(). However, David B explains that SingleOrDefault() may still throw an exception in the case where the enumerable contains more than one item.

Edit: Thanks Marc Gravell for pointing out that I need to dispose of my IEnumerator object after using it - I've edited the non-LINQ example to display the using keyword to implement this pattern.

How to convert (transliterate) a string from utf8 to ASCII (single byte) in c#?

I was able to figure it out. In case someone wants to know below the code that worked for me:

ASCIIEncoding ascii = new ASCIIEncoding();
byte[] byteArray = Encoding.UTF8.GetBytes(sOriginal);
byte[] asciiArray = Encoding.Convert(Encoding.UTF8, Encoding.ASCII, byteArray);
string finalString = ascii.GetString(asciiArray);

Let me know if there is a simpler way o doing it.

Android ListView selected item stay highlighted

Simplistic way is,if you are using listview in a xml,use this attributes on your listview,

android:choiceMode="singleChoice"
android:listSelector="#your color code"

if not using xml,by programatically

listview.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);
listview.setSelector(android.R.color.holo_blue_light);

How to compare Boolean?

Using direct conditions (like ==, !=, !condition) will have a slight performance improvement over the .equals(condition) as in one case you are calling the method from an object whereas direct comparisons are performed directly.

Disable Pinch Zoom on Mobile Web

Unfortunately, the offered solution doesn't work in Safari 10+, since Apple has decided to ignore user-scalable=no. This thread has more details and some JS hacks: disable viewport zooming iOS 10+ safari?

How can moment.js be imported with typescript?

Update

Apparently, moment now provides its own type definitions (according to sivabudh at least from 2.14.1 upwards), thus you do not need typings or @types at all.

import * as moment from 'moment' should load the type definitions provided with the npm package.

That said however, as said in moment/pull/3319#issuecomment-263752265 the moment team seems to have some issues in maintaining those definitions (they are still searching someone who maintains them).


You need to install moment typings without the --ambient flag.

Then include it using import * as moment from 'moment'

Updating version numbers of modules in a multi-module Maven project

Use versions:set from the versions-maven plugin:

mvn versions:set -DnewVersion=2.50.1-SNAPSHOT

It will adjust all pom versions, parent versions and dependency versions in a multi-module project.

If you made a mistake, do

mvn versions:revert

afterwards, or

mvn versions:commit

if you're happy with the results.


Note: this solution assumes that all modules use the aggregate pom as parent pom also, a scenario that was considered standard at the time of this answer. If that is not the case, go for Garret Wilson's answer.

Left Join without duplicate rows from left table

Try an OUTER APPLY

SELECT 
    C.Content_ID,
    C.Content_Title,
    C.Content_DatePublished,
    M.Media_Id
FROM 
    tbl_Contents C
    OUTER APPLY
    (
        SELECT TOP 1 *
        FROM tbl_Media M 
        WHERE M.Content_Id = C.Content_Id 
    ) m
ORDER BY 
    C.Content_DatePublished ASC

Alternatively, you could GROUP BY the results

SELECT 
    C.Content_ID,
    C.Content_Title,
    C.Content_DatePublished,
    M.Media_Id
FROM 
    tbl_Contents C
    LEFT OUTER JOIN tbl_Media M ON M.Content_Id = C.Content_Id 
GROUP BY
    C.Content_ID,
    C.Content_Title,
    C.Content_DatePublished,
    M.Media_Id
ORDER BY
    C.Content_DatePublished ASC

The OUTER APPLY selects a single row (or none) that matches each row from the left table.

The GROUP BY performs the entire join, but then collapses the final result rows on the provided columns.

How do I convert hex to decimal in Python?

You could use a literal eval:

>>> ast.literal_eval('0xdeadbeef')
3735928559

Or just specify the base as argument to int:

>>> int('deadbeef', 16)
3735928559

A trick that is not well known, if you specify the base 0 to int, then Python will attempt to determine the base from the string prefix:

>>> int("0xff", 0)
255
>>> int("0o644", 0)
420
>>> int("0b100", 0)
4
>>> int("100", 0)
100

Good way of getting the user's location in Android

This is my solution which works fairly well:

private Location bestLocation = null;
private Looper looper;
private boolean networkEnabled = false, gpsEnabled = false;

private synchronized void setLooper(Looper looper) {
    this.looper = looper;
}

private synchronized void stopLooper() {
    if (looper == null) return;
    looper.quit();
}

@Override
protected void runTask() {
    final LocationManager locationManager = (LocationManager) service
            .getSystemService(Context.LOCATION_SERVICE);
    final SharedPreferences prefs = getPreferences();
    final int maxPollingTime = Integer.parseInt(prefs.getString(
            POLLING_KEY, "0"));
    final int desiredAccuracy = Integer.parseInt(prefs.getString(
            DESIRED_KEY, "0"));
    final int acceptedAccuracy = Integer.parseInt(prefs.getString(
            ACCEPTED_KEY, "0"));
    final int maxAge = Integer.parseInt(prefs.getString(AGE_KEY, "0"));
    final String whichProvider = prefs.getString(PROVIDER_KEY, "any");
    final boolean canUseGps = whichProvider.equals("gps")
            || whichProvider.equals("any");
    final boolean canUseNetwork = whichProvider.equals("network")
            || whichProvider.equals("any");
    if (canUseNetwork)
        networkEnabled = locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    if (canUseGps)
        gpsEnabled = locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);
    // If any provider is enabled now and we displayed a notification clear it.
    if (gpsEnabled || networkEnabled) removeErrorNotification();
    if (gpsEnabled)
        updateBestLocation(locationManager
                .getLastKnownLocation(LocationManager.GPS_PROVIDER));
    if (networkEnabled)
        updateBestLocation(locationManager
                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER));
    if (desiredAccuracy == 0
            || getLocationQuality(desiredAccuracy, acceptedAccuracy,
                    maxAge, bestLocation) != LocationQuality.GOOD) {
        // Define a listener that responds to location updates
        LocationListener locationListener = new LocationListener() {

            public void onLocationChanged(Location location) {
                updateBestLocation(location);
                if (desiredAccuracy != 0
                        && getLocationQuality(desiredAccuracy,
                                acceptedAccuracy, maxAge, bestLocation)
                                == LocationQuality.GOOD)
                    stopLooper();
            }

            public void onProviderEnabled(String provider) {
                if (isSameProvider(provider,
                        LocationManager.NETWORK_PROVIDER))networkEnabled =true;
                else if (isSameProvider(provider,
                        LocationManager.GPS_PROVIDER)) gpsEnabled = true;
                // The user has enabled a location, remove any error
                // notification
                if (canUseGps && gpsEnabled || canUseNetwork
                        && networkEnabled) removeErrorNotification();
            }

            public void onProviderDisabled(String provider) {
                if (isSameProvider(provider,
                        LocationManager.NETWORK_PROVIDER))networkEnabled=false;
                else if (isSameProvider(provider,
                        LocationManager.GPS_PROVIDER)) gpsEnabled = false;
                if (!gpsEnabled && !networkEnabled) {
                    showErrorNotification();
                    stopLooper();
                }
            }

            public void onStatusChanged(String provider, int status,
                    Bundle extras) {
                Log.i(LOG_TAG, "Provider " + provider + " statusChanged");
                if (isSameProvider(provider,
                        LocationManager.NETWORK_PROVIDER)) networkEnabled = 
                        status == LocationProvider.AVAILABLE
                        || status == LocationProvider.TEMPORARILY_UNAVAILABLE;
                else if (isSameProvider(provider,
                        LocationManager.GPS_PROVIDER))
                    gpsEnabled = status == LocationProvider.AVAILABLE
                      || status == LocationProvider.TEMPORARILY_UNAVAILABLE;
                // None of them are available, stop listening
                if (!networkEnabled && !gpsEnabled) {
                    showErrorNotification();
                    stopLooper();
                }
                // The user has enabled a location, remove any error
                // notification
                else if (canUseGps && gpsEnabled || canUseNetwork
                        && networkEnabled) removeErrorNotification();
            }
        };
        if (networkEnabled || gpsEnabled) {
            Looper.prepare();
            setLooper(Looper.myLooper());
            // Register the listener with the Location Manager to receive
            // location updates
            if (canUseGps)
                locationManager.requestLocationUpdates(
                        LocationManager.GPS_PROVIDER, 1000, 1,
                        locationListener, Looper.myLooper());
            if (canUseNetwork)
                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER, 1000, 1,
                        locationListener, Looper.myLooper());
            Timer t = new Timer();
            t.schedule(new TimerTask() {

                @Override
                public void run() {
                    stopLooper();
                }
            }, maxPollingTime * 1000);
            Looper.loop();
            t.cancel();
            setLooper(null);
            locationManager.removeUpdates(locationListener);
        } else // No provider is enabled, show a notification
        showErrorNotification();
    }
    if (getLocationQuality(desiredAccuracy, acceptedAccuracy, maxAge,
            bestLocation) != LocationQuality.BAD) {
        sendUpdate(new Event(EVENT_TYPE, locationToString(desiredAccuracy,
                acceptedAccuracy, maxAge, bestLocation)));
    } else Log.w(LOG_TAG, "LocationCollector failed to get a location");
}

private synchronized void showErrorNotification() {
    if (notifId != 0) return;
    ServiceHandler handler = service.getHandler();
    NotificationInfo ni = NotificationInfo.createSingleNotification(
            R.string.locationcollector_notif_ticker,
            R.string.locationcollector_notif_title,
            R.string.locationcollector_notif_text,
            android.R.drawable.stat_notify_error);
    Intent intent = new Intent(
            android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
    ni.pendingIntent = PendingIntent.getActivity(service, 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    Message msg = handler.obtainMessage(ServiceHandler.SHOW_NOTIFICATION);
    msg.obj = ni;
    handler.sendMessage(msg);
    notifId = ni.id;
}

private void removeErrorNotification() {
    if (notifId == 0) return;
    ServiceHandler handler = service.getHandler();
    if (handler != null) {
        Message msg = handler.obtainMessage(
                ServiceHandler.CLEAR_NOTIFICATION, notifId, 0);
        handler.sendMessage(msg);
        notifId = 0;
    }
}

@Override
public void interrupt() {
    stopLooper();
    super.interrupt();
}

private String locationToString(int desiredAccuracy, int acceptedAccuracy,
        int maxAge, Location location) {
    StringBuilder sb = new StringBuilder();
    sb.append(String.format(
            "qual=%s time=%d prov=%s acc=%.1f lat=%f long=%f",
            getLocationQuality(desiredAccuracy, acceptedAccuracy, maxAge,
                    location), location.getTime() / 1000, // Millis to
                                                            // seconds
            location.getProvider(), location.getAccuracy(), location
                    .getLatitude(), location.getLongitude()));
    if (location.hasAltitude())
        sb.append(String.format(" alt=%.1f", location.getAltitude()));
    if (location.hasBearing())
        sb.append(String.format(" bearing=%.2f", location.getBearing()));
    return sb.toString();
}

private enum LocationQuality {
    BAD, ACCEPTED, GOOD;

    public String toString() {
        if (this == GOOD) return "Good";
        else if (this == ACCEPTED) return "Accepted";
        else return "Bad";
    }
}

private LocationQuality getLocationQuality(int desiredAccuracy,
        int acceptedAccuracy, int maxAge, Location location) {
    if (location == null) return LocationQuality.BAD;
    if (!location.hasAccuracy()) return LocationQuality.BAD;
    long currentTime = System.currentTimeMillis();
    if (currentTime - location.getTime() < maxAge * 1000
            && location.getAccuracy() <= desiredAccuracy)
        return LocationQuality.GOOD;
    if (acceptedAccuracy == -1
            || location.getAccuracy() <= acceptedAccuracy)
        return LocationQuality.ACCEPTED;
    return LocationQuality.BAD;
}

private synchronized void updateBestLocation(Location location) {
    bestLocation = getBestLocation(location, bestLocation);
}

protected Location getBestLocation(Location location,
        Location currentBestLocation) {
    if (currentBestLocation == null) {
        // A new location is always better than no location
        return location;
    }
    if (location == null) return currentBestLocation;
    // Check whether the new location fix is newer or older
    long timeDelta = location.getTime() - currentBestLocation.getTime();
    boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
    boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
    boolean isNewer = timeDelta > 0;
    // If it's been more than two minutes since the current location, use
    // the new location
    // because the user has likely moved
    if (isSignificantlyNewer) {
        return location;
        // If the new location is more than two minutes older, it must be
        // worse
    } else if (isSignificantlyOlder) {
        return currentBestLocation;
    }
    // Check whether the new location fix is more or less accurate
    int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation
            .getAccuracy());
    boolean isLessAccurate = accuracyDelta > 0;
    boolean isMoreAccurate = accuracyDelta < 0;
    boolean isSignificantlyLessAccurate = accuracyDelta > 200;
    // Check if the old and new location are from the same provider
    boolean isFromSameProvider = isSameProvider(location.getProvider(),
            currentBestLocation.getProvider());
    // Determine location quality using a combination of timeliness and
    // accuracy
    if (isMoreAccurate) {
        return location;
    } else if (isNewer && !isLessAccurate) {
        return location;
    } else if (isNewer && !isSignificantlyLessAccurate
            && isFromSameProvider) {
        return location;
    }
    return bestLocation;
}

/** Checks whether two providers are the same */
private boolean isSameProvider(String provider1, String provider2) {
    if (provider1 == null) return provider2 == null;
    return provider1.equals(provider2);
}

Converting List<Integer> to List<String>

You can't avoid the "boxing overhead"; Java's faux generic containers can only store Objects, so your ints must be boxed into Integers. In principle it could avoid the downcast from Object to Integer (since it's pointless, because Object is good enough for both String.valueOf and Object.toString) but I don't know if the compiler is smart enough to do that. The conversion from String to Object should be more or less a no-op, so I would be disinclined to worry about that one.

How to remove trailing whitespaces with sed?

var1="\t\t Test String trimming   "
echo $var1
Var2=$(echo "${var1}" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')
echo $Var2

ASP.NET Web API session or something?

Now in 2017 with ASP.Net Core you can do it as explained here.

The Microsoft.AspNetCore.Session package provides middleware for managing session state.

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
  // Adds a default in-memory implementation of IDistributedCache.
    services.AddDistributedMemoryCache();

    services.AddSession(options =>
    {
        // Set a short timeout for easy testing.
        options.IdleTimeout = TimeSpan.FromSeconds(10);
        options.Cookie.HttpOnly = true;
    });
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseSession();
}

From the Docs: Introduction to session and application state in ASP.NET Core

Already tested on a working project

How to check if a variable is a dictionary in Python?

The OP did not exclude the starting variable, so for completeness here is how to handle the generic case of processing a supposed dictionary that may include items as dictionaries.

Also following the pure Python(3.8) recommended way to test for dictionary in the above comments.

from collections.abc import Mapping

dict = {'abc': 'abc', 'def': {'ghi': 'ghi', 'jkl': 'jkl'}}

def parse_dict(in_dict): 
    if isinstance(in_dict, Mapping):
        for k_outer, v_outer in in_dict.items():
            if isinstance(v_outer, Mapping):
                for k_inner, v_inner in v_outer.items():
                    print(k_inner, v_inner)
            else:
                print(k_outer, v_outer)

parse_dict(dict)

How can I show current location on a Google Map on Android Marshmallow?

Sorry but that's just much too much overhead (above), short and quick, if you have the MapFragment, you also have to map, just do the following:

if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            googleMap.setMyLocationEnabled(true)
} else {
    // Show rationale and request permission.
}

Code is in Kotlin, hope you don't mind.

have fun

Btw I think this one is a duplicate of: Show Current Location inside Google Map Fragment

What is the difference between YAML and JSON?

Technically YAML offers a lot more than JSON (YAML v1.2 is a superset of JSON):

  • comments
  • anchors and inheritance - example of 3 identical items:

    item1: &anchor_name
      name: Test
      title: Test title
    item2: *anchor_name
    item3:
      <<: *anchor_name
      # You may add extra stuff.
    
  • ...

Most of the time people will not use those extra features and the main difference is that YAML uses indentation whilst JSON uses brackets. This makes YAML more concise and readable (for the trained eye).

Which one to choose?

  • YAML extra features and concise notation makes it a good choice for configuration files (non-user provided files).
  • JSON limited features, wide support, and faster parsing makes it a great choice for interoperability and user provided data.

jQuery .val() vs .attr("value")

In attr('value') you're specifically saying you're looking for the value of an attribute named vaule. It is preferable to use val() as this is jQuery's out of the box feature for extracting the value out of form elements.

How to right align widget in horizontal linear layout Android?

this is my xml, dynamic component to align right, in my case i use 3 button

 <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/checkinInputCodeMember">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="7"
                android:orientation="vertical" />

            <androidx.appcompat.widget.AppCompatButton
                android:id="@+id/bttn_extends"
                style="@style/Widget.AppCompat.Button.Borderless"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="right"
                android:textColor="@color/colorAccent"
                android:text="3"/>

            <androidx.appcompat.widget.AppCompatButton
                android:id="@+id/bttn_checkout"
                style="@style/Widget.AppCompat.Button.Borderless"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="right"
                android:textColor="@color/colorAccent"
                android:text="2"/>

            <androidx.appcompat.widget.AppCompatButton
                android:id="@+id/checkinButtonScanQrCodeMember"
                style="@style/Widget.AppCompat.Button.Borderless"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="right"
                android:textColor="@color/colorAccent"
                android:text="1"/>


        </LinearLayout>

and the result

you can hide the right first button with change visibility GONE, and this my code

 <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/checkinInputCodeMember">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="7"
                android:orientation="vertical" />

            <androidx.appcompat.widget.AppCompatButton
                android:id="@+id/bttn_extends"
                style="@style/Widget.AppCompat.Button.Borderless"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="right"
                android:textColor="@color/colorAccent"
                android:text="3"/>

            <androidx.appcompat.widget.AppCompatButton
                android:id="@+id/bttn_checkout"
                style="@style/Widget.AppCompat.Button.Borderless"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="right"
                android:textColor="@color/colorAccent"
                android:text="2"/>

            <androidx.appcompat.widget.AppCompatButton
                android:id="@+id/checkinButtonScanQrCodeMember"
                style="@style/Widget.AppCompat.Button.Borderless"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="right"
                android:text="1"
                android:textColor="@color/colorAccent"
                **android:visibility="gone"**/>


        </LinearLayout>

still align right, after visibility gone first right component

result code 1

result code 2

What is the difference between Collection and List in Java?

Collection is a high-level interface describing Java objects that can contain collections of other objects. It's not very specific about how they are accessed, whether multiple copies of the same object can exist in the same collection, or whether the order is important. List is specifically an ordered collection of objects. If you put objects into a List in a particular order, they will stay in that order.

And deciding where to use these two interfaces is much less important than deciding what the concrete implementation you use is. This will have implications for the time and space performance of your program. For example, if you want a list, you could use an ArrayList or a LinkedList, each of which is going to have implications for the application. For other collection types (e.g. Sets), similar considerations apply.

Objective-C declared @property attributes (nonatomic, copy, strong, weak)

Great answers! One thing that I would like to clarify deeper is nonatomic/atomic. The user should understand that this property - "atomicity" spreads only on the attribute's reference and not on it's contents. I.e. atomic will guarantee the user atomicity for reading/setting the pointer and only the pointer to the attribute. For example:

@interface MyClass: NSObject
@property (atomic, strong) NSDictionary *dict;
...

In this case it is guaranteed that the pointer to the dict will be read/set in the atomic manner by different threads. BUT the dict itself (the dictionary dict pointing to) is still thread unsafe, i.e. all read/add operations to the dictionary are still thread unsafe.

If you need thread safe collection you either have bad architecture (more often) OR real requirement (more rare). If it is "real requirement" - you should either find good&tested thread safe collection component OR be prepared for trials and tribulations writing your own one. It latter case look at "lock-free", "wait-free" paradigms. Looks like rocket-science at a first glance, but could help you achieving fantastic performance in comparison to "usual locking".

laravel foreach loop in controller

Hi, this will throw an error:

foreach ($product->sku as $sku){ 
// Code Here
}

because you cannot loop a model with a specific column ($product->sku) from the table.
So you must loop on the whole model:

foreach ($product as $p) {
// code
}

Inside the loop you can retrieve whatever column you want just adding "->[column_name]"

foreach ($product as $p) {
echo $p->sku;
}

Have a great day

How do I delete specific characters from a particular String in Java?

Note that the word boundaries also depend on the Locale. I think the best way to do it using standard java.text.BreakIterator. Here is an example from the java.sun.com tutorial.

import java.text.BreakIterator;
import java.util.Locale;

public static void main(String[] args) {
    String text = "\n" +
            "\n" +
            "For example I'm extracting a text String from a text file and I need those words to form an array. However, when I do all that some words end with comma (,) or a full stop (.) or even have brackets attached to them (which is all perfectly normal).\n" +
            "\n" +
            "What I want to do is to get rid of those characters. I've been trying to do that using those predefined String methods in Java but I just can't get around it.\n" +
            "\n" +
            "Every help appreciated. Thanx";
    BreakIterator wordIterator = BreakIterator.getWordInstance(Locale.getDefault());
    extractWords(text, wordIterator);
}

static void extractWords(String target, BreakIterator wordIterator) {
    wordIterator.setText(target);
    int start = wordIterator.first();
    int end = wordIterator.next();

    while (end != BreakIterator.DONE) {
        String word = target.substring(start, end);
        if (Character.isLetterOrDigit(word.charAt(0))) {
            System.out.println(word);
        }
        start = end;
        end = wordIterator.next();
    }
}

Source: http://java.sun.com/docs/books/tutorial/i18n/text/word.html

How do I write a batch script that copies one directory to another, replaces old files?

It seems that the latest function for this in windows 7 is robocopy.

Usage example:

robocopy <source> <destination> /e /xf <file to exclude> <another file>

/e copies subdirectories including empty ones, /xf excludes certain files from being copied.

More options here: http://technet.microsoft.com/en-us/library/cc733145(v=ws.10).aspx

Automatically create an Enum based on values in a database lookup table?

Just showing the answer of Pandincus with "of the shelf" code and some explanation: You need two solutions for this example ( I know it could be done via one also ; ), let the advanced students present it ...

So here is the DDL SQL for the table :

USE [ocms_dev]
    GO

CREATE TABLE [dbo].[Role](
    [RoleId] [int] IDENTITY(1,1) NOT NULL,
    [RoleName] [varchar](50) NULL
) ON [PRIMARY]

So here is the console program producing the dll:

using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Reflection.Emit;
using System.Data.Common;
using System.Data;
using System.Data.SqlClient;

namespace DynamicEnums
{
    class EnumCreator
    {
        // after running for first time rename this method to Main1
        static void Main ()
        {
            string strAssemblyName = "MyEnums";
            bool flagFileExists = System.IO.File.Exists (
                   AppDomain.CurrentDomain.SetupInformation.ApplicationBase + 
                   strAssemblyName + ".dll"
            );

            // Get the current application domain for the current thread
            AppDomain currentDomain = AppDomain.CurrentDomain;

            // Create a dynamic assembly in the current application domain,
            // and allow it to be executed and saved to disk.
            AssemblyName name = new AssemblyName ( strAssemblyName );
            AssemblyBuilder assemblyBuilder = 
                    currentDomain.DefineDynamicAssembly ( name,
                            AssemblyBuilderAccess.RunAndSave );

            // Define a dynamic module in "MyEnums" assembly.
            // For a single-module assembly, the module has the same name as
            // the assembly.
            ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule (
                    name.Name, name.Name + ".dll" );

            // Define a public enumeration with the name "MyEnum" and
            // an underlying type of Integer.
            EnumBuilder myEnum = moduleBuilder.DefineEnum (
                    "EnumeratedTypes.MyEnum",
                    TypeAttributes.Public,
                    typeof ( int )
            );

            #region GetTheDataFromTheDatabase
            DataTable tableData = new DataTable ( "enumSourceDataTable" );

            string connectionString = "Integrated Security=SSPI;Persist " +
                    "Security Info=False;Initial Catalog=ocms_dev;Data " +
                    "Source=ysg";

            using (SqlConnection connection = 
                    new SqlConnection ( connectionString ))
            {

                SqlCommand command = connection.CreateCommand ();
                command.CommandText = string.Format ( "SELECT [RoleId], " + 
                        "[RoleName] FROM [ocms_dev].[dbo].[Role]" );

                Console.WriteLine ( "command.CommandText is " + 
                        command.CommandText );

                connection.Open ();
                tableData.Load ( command.ExecuteReader ( 
                        CommandBehavior.CloseConnection
                ) );
            } //eof using

            foreach (DataRow dr in tableData.Rows)
            {
                myEnum.DefineLiteral ( dr[1].ToString (),
                        Convert.ToInt32 ( dr[0].ToString () ) );
            }
            #endregion GetTheDataFromTheDatabase

            // Create the enum
            myEnum.CreateType ();

            // Finally, save the assembly
            assemblyBuilder.Save ( name.Name + ".dll" );
        } //eof Main 
    } //eof Program
} //eof namespace 

Here is the Console programming printing the output ( remember that it has to reference the dll ). Let the advance students present the solution for combining everything in one solution with dynamic loading and checking if there is already build dll.

// add the reference to the newly generated dll
use MyEnums ; 

class Program
{
    static void Main ()
    {
        Array values = Enum.GetValues ( typeof ( EnumeratedTypes.MyEnum ) );

        foreach (EnumeratedTypes.MyEnum val in values)
        {
            Console.WriteLine ( String.Format ( "{0}: {1}",
                    Enum.GetName ( typeof ( EnumeratedTypes.MyEnum ), val ),
                    val ) );
        }

        Console.WriteLine ( "Hit enter to exit " );
        Console.ReadLine ();
    } //eof Main 
} //eof Program

How do I get Flask to run on port 80?

I had to set FLASK_RUN_PORT in my environment to the specified port number. Next time you start your app, Flask will load that environment variable with the port number you selected.

Python Error: "ValueError: need more than 1 value to unpack"

You have to pass the arguments in the terminal in order to store them in 'argv'. This variable holds the arguments you pass to your Python script when you run it. It later unpacks the arguments and store them in different variables you specify in the program e.g.

script, first, second = argv
print "Your file is:", script
print "Your first entry is:", first
print "Your second entry is:" second

Then in your command line you have to run your code like this,

$python ex14.py Hamburger Pizza

Your output will look like this:

Your file is: ex14.py
Your first entry is: Hamburger
Your second entry is: Pizza

How can I remove the "No file chosen" tooltip from a file input in Chrome?

I came up with a hacky solution that totally removes "No file chosen" plus the extra space that is added after that text (in Chrome I get something like: "No file chosen ").

This was totally messing up my page alignment, so I really fought with it to find a solution. Inside the input tag's style attribute, setting "width" to the width of the button will eliminate the trailing text and spaces. Since the width of the button is not the same in all browsers (it's a little smaller in Firefox, for example), you'll also want to set the style's color to the same color as the background of the page (otherwise a stray "No" may show through). My input file tag looks like this:

<input style="float:left; **width:88px;** **color:#000000;**" type="file" id="fileInput" onclick="fileOpen()">    

String "true" and "false" to boolean

You could add to the String class to have the method of to_boolean. Then you could do 'true'.to_boolean or '1'.to_boolean

class String
  def to_boolean
    self == 'true' || self == '1'
  end
end

How to scale a UIImageView proportionally?

I think you can do something like

image.center = [[imageView window] center];

How can I permanently enable line numbers in IntelliJ?

IntelliJ 2019 community edition has line number by default. If you want to show or hide line numbers, go to the following settings to change the appearance.

go to ? File ? Setting ? Editor ? General ? Appearance ? [Check] Show line numbers

show_line_numbers

Hiding elements in responsive layout?

For Bootstrap 4.0 beta (and I assume this will stay for final) there is a change - be aware that the hidden classes were removed.

See the docs: https://getbootstrap.com/docs/4.0/utilities/display/

In order to hide the content on mobile and display on the bigger devices you have to use the following classes:

d-none d-sm-block

The first class set display none all across devices and the second one display it for devices "sm" up (you could use md, lg, etc. instead of sm if you want to show on different devices.

I suggest to read about that before migration:

https://getbootstrap.com/docs/4.0/migration/#responsive-utilities

Don't understand why UnboundLocalError occurs (closure)

To modify a global variable inside a function, you must use the global keyword.

When you try to do this without the line

global counter

inside of the definition of increment, a local variable named counter is created so as to keep you from mucking up the counter variable that the whole program may depend on.

Note that you only need to use global when you are modifying the variable; you could read counter from within increment without the need for the global statement.

How do I edit SSIS package files?

I prefer to use :

(from SSDT visual studio just opened) file> open > file > locate dtsx file > open

then you can edit work and save

Java: Why is the Date constructor deprecated, and what do I use instead?

You can make a method just like new Date(year,month,date) in your code by using Calendar class.

private Date getDate(int year,int month,int date){
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.YEAR, year);
    cal.set(Calendar.MONTH, month-1);
    cal.set(Calendar.DAY_OF_MONTH, day);
    return cal.getTime();
}

It will work just like the deprecated constructor of Date

Parsing string as JSON with single quotes?

If you are sure your JSON is safely under your control (not user input) then you can simply evaluate the JSON. Eval accepts all quote types as well as unquoted property names.

var str = "{'a':1}";
var myObject = (0, eval)('(' + str + ')');

The extra parentheses are required due to how the eval parser works. Eval is not evil when it is used on data you have control over. For more on the difference between JSON.parse and eval() see JSON.parse vs. eval()

Access item in a list of lists

50 - List1[0][0] + List[0][1] - List[0][2]

List[0] gives you the first list in the list (try out print List[0]). Then, you index into it again to get the items of that list. Think of it this way: (List1[0])[0].

How to solve ADB device unauthorized in Android ADB host device?

I had to check the box for the debugger on the phone "always allow on this phone". I then did a adb devices and then entered the adb command to clear the adds. It worked fine. Before that, it did not recognize the pm and other commands

Troubleshooting "program does not contain a static 'Main' method" when it clearly does...?

It is important that the Main method is placed in the class that is properly configured in Visual Studio as a start-up object:

  • Right-click your project in project explorer; choose "Properties..."
  • In the properties dialog, choose "Application" tab
  • In the application tab, choose SimpleAIMLEditor.Program from the drop-down for your start-up object

Now run your application again. The error will disappear.

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"

Conversion failed when converting the nvarchar value ... to data type int

don't use string concatenation to produce sql, you can use sp_executesql system stored prcedure to execute sql statement with parameters

create procedure getdata @ID int, @frm varchar(250), @to varchar(250) as
begin
    declare @sql nvarchar(max), @paramDefs nvarchar(max);

    set nocount on;

    set @sql = N'select EmpName, Address, Salary from Emp_Tb where @id is null or Emp_Id_Pk = @id';
    set @paramDefs = N'@id int';
    execute sp_executesql @sql, @paramDefs, @id = @ID;
end

see sp_executesql

How can I escape a single quote?

As you’re in the context of HTML, you need to use HTML to represent that character. And for HTML you need to use a numeric character reference &#39; (&#x27; hexadecimal):

<input type='text' id='abc' value='hel&#39;lo'>

@Scope("prototype") bean scope not creating new bean

By default, Spring beans are singletons. The problem arises when we try to wire beans of different scopes. For example, a prototype bean into a singleton. This is known as the scoped bean injection problem.

Another way to solve the problem is method injection with the @Lookup annotation.

Here is a nice article on this issue of injecting prototype beans into a singleton instance with multiple solutions.

https://www.baeldung.com/spring-inject-prototype-bean-into-singleton

Mobile Safari: Javascript focus() method on inputfield only works with click?

UPDATE

I also tried this, but to no avail:

$(document).ready(function() {
$('body :not(.wr-dropdown)').bind("click", function(e) {
    $('.test').focus();
})
$('.wr-dropdown').on('change', function(e) {
    if ($(".wr-dropdow option[value='/search']")) {
        setTimeout(function(e) {
            $('body :not(.wr-dropdown)').trigger("click");
        },3000)         
    } 
}); 

});

I am confused as to why you say this isn't working because your JSFiddle is working just fine, but here is my suggestion anyway...

Try this line of code in your SetTimeOut function on your click event:

document.myInput.focus();

myInput correlates to the name attribute of the input tag.

<input name="myInput">

And use this code to blur the field:

document.activeElement.blur();

Removing Data From ElasticSearch

For mass-delete by query you may use special delete by query API:

$ curl -XDELETE 'http://localhost:9200/twitter/tweet/_query' -d '{
    "query" : {
        "term" : { "user" : "kimchy" }
    }
}

In history that API was deleted and then reintroduced again

Who interesting it has long history.

  1. In first version of that answer I refer to documentation of elasticsearch version 1.6. In it that functionality was marked as deprecated but works good.
  2. In elasticsearch version 2.0 it was moved to separate plugin. And even reasons why it became plugin explained.
  3. And it again appeared in core API in version 5.0!

PHP shorthand for isset()?

PHP 7.4+; with the null coalescing assignment operator

$var ??= '';

PHP 7.0+; with the null coalescing operator

$var = $var ?? '';

PHP 5.3+; with the ternary operator shorthand

isset($var) ?: $var = '';

Or for all/older versions with isset:

$var = isset($var) ? $var : '';

or

!isset($var) && $var = '';

Your project contains error(s), please fix it before running it

I had this exact problem when trying to run the Doodlz app, from the book Android for Programmers, on Mac OS X with Eclipse Juno.

After downloading and unzipping the demos from the book, I forgot to change the permission of the files. They were read-only on my system so this was the first issue.

The second issue was solved by selecting a build target on Eclipse. This was fixed by going to: Project > Properties , and clicking the Android field on the left panel to be able to select one option as the Project Build Target, which in my case was:

  Target Name     Vendor         Platform    API Level
> Google APIs     Google Inc.    4.0.3       15

Then cleaning and rebuilding the project showed no errors.

Finally, to run the app right-click the package (at the Package Explorer tab) and then select: Run As > Android Application

CSS hover vs. JavaScript mouseover

A very big difference is that ":hover" state is automatically deactivated when the mouse moves out of the element. As a result any styles that are applied on hover are automatically reversed. On the other hand, with the javascript approach, you would have to define both "onmouseover" and "onmouseout" events. If you only define "onmouseover" the styles that are applied "onmouseover" will persist even after you mouse out unless you have explicitly defined "onmouseout".

Remove all git files from a directory?

The .git folder is only stored in the root directory of the repo, not all the sub-directories like subversion. You should be able to just delete that one folder, unless you are using Submodules...then they will have one too.

You must add a reference to assembly 'netstandard, Version=2.0.0.0

Might have todo with one of these:

  1. Install a newer SDK.
  2. In .csproj check for Reference Include="netstandard"
  3. Check the assembly versions in the compilation tags in the Views\Web.config and Web.config.

textarea character limit

I think that doing this might be easier than most people think!

Try this:

var yourTextArea = document.getElementById("usertext").value;
// In case you want to limit the number of characters in no less than, say, 10
// or no more than 400.        
    if (yourTextArea.length < 10 || yourTextArea.length > 400) {
        alert("The field must have no less than 10 and no more than 400 characters.");
        return false;
    }

Please let me know it this was useful. And if so, vote up! Thx!

Daniel

How do you find what version of libstdc++ library is installed on your linux machine?

What exactly do you want to know?

The shared library soname? That's part of the filename, libstdc++.so.6, or shown by readelf -d /usr/lib64/libstdc++.so.6 | grep soname.

The minor revision number? You should be able to get that by simply checking what the symlink points to:

$ ls -l  /usr/lib/libstdc++.so.6
lrwxrwxrwx. 1 root root 19 Mar 23 09:43 /usr/lib/libstdc++.so.6 -> libstdc++.so.6.0.16

That tells you it's 6.0.16, which is the 16th revision of the libstdc++.so.6 version, which corresponds to the GLIBCXX_3.4.16 symbol versions.

Or do you mean the release it comes from? It's part of GCC so it's the same version as GCC, so unless you've screwed up your system by installing unmatched versions of g++ and libstdc++.so you can get that from:

$ g++ -dumpversion
4.6.3

Or, on most distros, you can just ask the package manager. On my Fedora host that's

$ rpm -q libstdc++
libstdc++-4.6.3-2.fc16.x86_64
libstdc++-4.6.3-2.fc16.i686

As other answers have said, you can map releases to library versions by checking the ABI docs

Appending the same string to a list of strings in Python

Updating with more options

list1 = ['foo', 'fob', 'faz', 'funk']
addstring = 'bar'
for index, value in enumerate(list1):
    list1[index] = addstring + value #this will prepend the string
    #list1[index] = value + addstring this will append the string

Avoid using keywords as variables like 'list', renamed 'list' as 'list1' instead

How to convert InputStream to FileInputStream

You need something like:

    URL resource = this.getClass().getResource("/path/to/resource.res");
    File is = null;
    try {
        is = new File(resource.toURI());
    } catch (URISyntaxException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    try {
        FileInputStream input = new FileInputStream(is);
    } catch (FileNotFoundException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

But it will work only within your IDE, not in runnable JAR. I had same problem explained here.

Abstract Class:-Real Time Example

Here, Something about abstract class...

  1. Abstract class is an incomplete class so we can't instantiate it.
  2. If methods are abstract, class must be abstract.
  3. In abstract class, we use abstract and concrete method both.
  4. It is illegal to define a class abstract and final both.

Real time example--

If you want to make a new car(WagonX) in which all the another car's properties are included like color,size, engine etc.and you want to add some another features like model,baseEngine in your car.Then simply you create a abstract class WagonX where you use all the predefined functionality as abstract and another functionalities are concrete, which is is defined by you.
Another sub class which extend the abstract class WagonX,By default it also access the abstract methods which is instantiated in abstract class.SubClasses also access the concrete methods by creating the subclass's object.
For reusability the code, the developers use abstract class mostly.

abstract class WagonX
{
   public abstract void model();
   public abstract void color();
   public static void baseEngine()
    {
     // your logic here
    }
   public static void size()
   {
   // logic here
   }
}
class Car extends WagonX
{
public void model()
{
// logic here
}
public void color()
{
// logic here
}
}

Convert this string to datetime

The Problem is with your code formatting,

inorder to use strtotime() You should replace '06/Oct/2011:19:00:02' with 06/10/2011 19:00:02 and date('d/M/Y:H:i:s', $date); with date('d/M/Y H:i:s', $date);. Note the spaces in between.

So the final code looks like this

$s = '06/10/2011 19:00:02';
$date = strtotime($s);
echo date('d/M/Y H:i:s', $date);

AWS - Disconnected : No supported authentication methods available (server sent :publickey)

For me, I just had to tell FileZilla where the private keys were:

  1. Select Edit > Settings from the main menu
  2. In the Settings dialog box, go to Connection > SFTP
  3. Click the "Add key file..." button
  4. Navigate to and then select the desired PEM file(s)

Create new project on Android, Error: Studio Unknown host 'services.gradle.org'

I also faced it and encorrected it like below successfully.

File > Settings > Build, Execution, Deployment > Gradle > Use local gradle distribution

Set the home path as : C:/Program Files/Android/Android Studio/gradle/gradle-version

You may need to upgrade your gradle version.

How should I use Outlook to send code snippets?

If you attach your code as a text file and your recipient(s) have "show attachments inline" option set (I believe it's set by default), Outlook should not mangle your code but it will be copy/paste-able directly from email.

How to gzip all files in all sub-directories into one compressed file in bash

tar -zcvf compressFileName.tar.gz folderToCompress

everything in folderToCompress will go to compressFileName

Edit: After review and comments I realized that people may get confused with compressFileName without an extension. If you want you can use .tar.gz extension(as suggested) with the compressFileName

Python [Errno 98] Address already in use

This happens because you trying to run service at the same port and there is an already running application.

This can happen because your service is not stopped in the process stack. Then you just have to kill this process.

There is no need to install anything here is the one line command to kill all running python processes.

for Linux based OS:

Bash:

kill -9 $(ps -A | grep python | awk '{print $1}')

Fish:

kill -9 (ps -A | grep python | awk '{print $1}')

wait until all threads finish their work in java

Wait/block the Thread Main until some other threads complete their work.

As @Ravindra babu said it can be achieved in various ways, but showing with examples.

  • java.lang.Thread.join() Since:1.0

    public static void joiningThreads() throws InterruptedException {
        Thread t1 = new Thread( new LatchTask(1, null), "T1" );
        Thread t2 = new Thread( new LatchTask(7, null), "T2" );
        Thread t3 = new Thread( new LatchTask(5, null), "T3" );
        Thread t4 = new Thread( new LatchTask(2, null), "T4" );
    
        // Start all the threads
        t1.start();
        t2.start();
        t3.start();
        t4.start();
    
        // Wait till all threads completes
        t1.join();
        t2.join();
        t3.join();
        t4.join();
    }
    
  • java.util.concurrent.CountDownLatch Since:1.5

    • .countDown() « Decrements the count of the latch group.
    • .await() « The await methods block until the current count reaches zero.

    If you created latchGroupCount = 4 then countDown() should be called 4 times to make count 0. So, that await() will release the blocking threads.

    public static void latchThreads() throws InterruptedException {
        int latchGroupCount = 4;
        CountDownLatch latch = new CountDownLatch(latchGroupCount);
        Thread t1 = new Thread( new LatchTask(1, latch), "T1" );
        Thread t2 = new Thread( new LatchTask(7, latch), "T2" );
        Thread t3 = new Thread( new LatchTask(5, latch), "T3" );
        Thread t4 = new Thread( new LatchTask(2, latch), "T4" );
    
        t1.start();
        t2.start();
        t3.start();
        t4.start();
    
        //latch.countDown();
    
        latch.await(); // block until latchGroupCount is 0.
    }
    

Example code of Threaded class LatchTask. To test the approach use joiningThreads(); and latchThreads(); from main method.

class LatchTask extends Thread {
    CountDownLatch latch;
    int iterations = 10;
    public LatchTask(int iterations, CountDownLatch latch) {
        this.iterations = iterations;
        this.latch = latch;
    }

    @Override
    public void run() {
        String threadName = Thread.currentThread().getName();
        System.out.println(threadName + " : Started Task...");

        for (int i = 0; i < iterations; i++) {
            System.out.println(threadName + " : " + i);
            MainThread_Wait_TillWorkerThreadsComplete.sleep(1);
        }
        System.out.println(threadName + " : Completed Task");
        // countDown() « Decrements the count of the latch group.
        if(latch != null)
            latch.countDown();
    }
}
  • CyclicBarriers A synchronization aid that allows a set of threads to all wait for each other to reach a common barrier point.CyclicBarriers are useful in programs involving a fixed sized party of threads that must occasionally wait for each other. The barrier is called cyclic because it can be re-used after the waiting threads are released.
    CyclicBarrier barrier = new CyclicBarrier(3);
    barrier.await();
    
    For example refer this Concurrent_ParallelNotifyies class.

  • Executer framework: we can use ExecutorService to create a thread pool, and tracks the progress of the asynchronous tasks with Future.

    • submit(Runnable), submit(Callable) which return Future Object. By using future.get() function we can block the main thread till the working threads completes its work.

    • invokeAll(...) - returns a list of Future objects via which you can obtain the results of the executions of each Callable.

Find example of using Interfaces Runnable, Callable with Executor framework.


@See also

Installing a specific version of angular with angular cli

You can just have package.json with specific version and do npm install and it will install that version. Also you dont need to depend on angular-cli to develop your project.

How to Set a Custom Font in the ActionBar Title?

    ActionBar actionBar = getSupportActionBar();
    TextView tv = new TextView(getApplicationContext());
    Typeface typeface = ResourcesCompat.getFont(this, R.font.monotype_corsiva);
    RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.MATCH_PARENT, // Width of TextView
            RelativeLayout.LayoutParams.WRAP_CONTENT); // Height of TextView
    tv.setLayoutParams(lp);
    tv.setText("Your Text"); // ActionBar title text
    tv.setTextSize(25);
    tv.setTextColor(Color.WHITE);
    tv.setTypeface(typeface, typeface.ITALIC);
    actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
    actionBar.setCustomView(tv);

What is N-Tier architecture?

It's my understanding that N-Tier separates business logic, client access and data from each other using separate physical machines. The theory is that one of them can be updated independently of the others.

bash: pip: command not found

Based on this stackoverflow answer and some of the answers on this thread, I have created an alias in the rc file: alias pip="python -m pip"

There seem to be many different answers to this question but this seems to be the best-practice approach.

How do I call an Angular 2 pipe with multiple arguments?

Since beta.16 the parameters are not passed as array to the transform() method anymore but instead as individual parameters:

{{ myData | date:'fullDate':'arg1':'arg2' }}


export class DatePipe implements PipeTransform {    
  transform(value:any, arg1:any, arg2:any):any {
        ...
}

https://github.com/angular/angular/blob/master/CHANGELOG.md#200-beta16-2016-04-26

pipes now take a variable number of arguments, and not an array that contains all arguments.

How to include libraries in Visual Studio 2012?

Typically you need to do 5 things to include a library in your project:

1) Add #include statements necessary files with declarations/interfaces, e.g.:

#include "library.h"

2) Add an include directory for the compiler to look into

-> Configuration Properties/VC++ Directories/Include Directories (click and edit, add a new entry)

3) Add a library directory for *.lib files:

-> project(on top bar)/properties/Configuration Properties/VC++ Directories/Library Directories (click and edit, add a new entry)

4) Link the lib's *.lib files

-> Configuration Properties/Linker/Input/Additional Dependencies (e.g.: library.lib;

5) Place *.dll files either:

-> in the directory you'll be opening your final executable from or into Windows/system32

Is it good practice to use the xor operator for boolean checks?

I think it'd be okay if you commented it, e.g. // ^ == XOR.

PHP Warning Permission denied (13) on session_start()

PHP does not have permissions to write on /tmp directory. You need to use chmod command to open /tmp permissions.

How to create a directory if it doesn't exist using Node.js?

I had to create sub-directories if they didn't exist. I used this:

const path = require('path');
const fs = require('fs');

function ensureDirectoryExists(p) {
    //console.log(ensureDirectoryExists.name, {p});
    const d = path.dirname(p);
    if (d && d !== p) {
        ensureDirectoryExists(d);
    }
    if (!fs.existsSync(d)) {
        fs.mkdirSync(d);
    }
}

Running a cron job at 2:30 AM everyday

An easy way to write cron is to use the online cron generator It will generate the line for you. One thing to note is that if you wish to run it each day (not just weekdays) you need to highlight all the days.

Error message Strict standards: Non-static method should not be called statically in php

return false is usually meant to terminate the object creation with a failure. It is as simple as that.

Initial size for the ArrayList

ArrayList myList = new ArrayList(10);

//  myList.add(3, "DDD");
//  myList.add(9, "III");
    myList.add(0, "AAA");
    myList.add(1, "BBB");

    for(String item:myList){
        System.out.println("inside list : "+item);
    }

/*Declare the initial capasity of arraylist is nothing but saving shifting time in internally; when we add the element internally it check the capasity to increase the capasity, you could add the element at 0 index initially then 1 and so on. */

How to enable assembly bind failure logging (Fusion) in .NET

In my case helped type disk name in lower case

Wrong - C:\someFolder

Correct - c:\someFolder

Saving the PuTTY session logging

I always have to check my cheatsheet :-)

Step 1: right-click on the top of putty window and select 'Change settings'.

Step 2: type the name of the session and save.

That's it!. Enjoy!

iPhone app signing: A valid signing identity matching this profile could not be found in your keychain

Had the same problem yesterday. Now, after signing to the developer portal, for every invalid provisioning profile have a button "Renew". After renewing and downloading updated provisioning profile all seems to work as expected, so problem is definitely solved :)

Update: you may have to contact Apple to get a "Renew"-button, or they removed it -- and the solution is to just download it and add it to the keychain, no need to renew.

How to hash some string with sha256 in Java?

I traced the Apache code through DigestUtils and sha256 seems to default back to java.security.MessageDigest for calculation. Apache does not implement an independent sha256 solution. I was looking for an independent implementation to compare against the java.security library. FYI only.

Confirm password validation in Angular 6

It's not necessary to use nested form groups and a custom ErrorStateMatcher for confirm password validation. These steps were added to facilitate coordination between the password fields, but you can do that without all the overhead.

Here is an example:

this.registrationForm = this.fb.group({
  username: ['', Validators.required],
  email: ['', [Validators.required, Validators.email]],
  password1: ['', [Validators.required, (control) => this.validatePasswords(control, 'password1') ] ],
  password2: ['', [Validators.required, (control) => this.validatePasswords(control, 'password2') ] ]
});

Note that we are passing additional context to the validatePasswords method (whether the source is password1 or password2).

  validatePasswords(control: AbstractControl, name: string) {
    if (this.registrationForm === undefined || this.password1.value === '' || this.password2.value === '') {
      return null;
    } else if (this.password1.value === this.password2.value) {
      if (name === 'password1' && this.password2.hasError('passwordMismatch')) {
        this.password1.setErrors(null);
        this.password2.updateValueAndValidity();
      } else if (name === 'password2' && this.password1.hasError('passwordMismatch')) {
        this.password2.setErrors(null);
        this.password1.updateValueAndValidity();
      }
      return null;
    } else {
      return {'passwordMismatch': { value: 'The provided passwords do not match'}};
    }  

Note here that when the passwords match, we coordinate with the other password field to have its validation updated. This will clear any stale password mismatch errors.

And for completeness sake, here are the getters that define this.password1 and this.password2.

  get password1(): AbstractControl {
    return this.registrationForm.get('password1');
  }

  get password2(): AbstractControl {
    return this.registrationForm.get('password2');
  }

Get key by value in dictionary

Just my answer in lambda and filter.

filter( lambda x, dictionary=dictionary, search_age=int(search_age): dictionary[x] == search_age  , dictionary )

Setting an image for a UIButton in code

UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = CGRectMake(0, 0, 150, 44);
[btn setBackgroundImage:[UIImage imageNamed:@"buttonimage.png"] 
               forState:UIControlStateNormal];
[btn addTarget:self 
     action:@selector(btnSendComment_pressed:) 
     forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];

List<Map<String, String>> vs List<? extends Map<String, String>>

What I'm missing in the other answers is a reference to how this relates to co- and contravariance and sub- and supertypes (that is, polymorphism) in general and to Java in particular. This may be well understood by the OP, but just in case, here it goes:

Covariance

If you have a class Automobile, then Car and Truck are their subtypes. Any Car can be assigned to a variable of type Automobile, this is well-known in OO and is called polymorphism. Covariance refers to using this same principle in scenarios with generics or delegates. Java doesn't have delegates (yet), so the term applies only to generics.

I tend to think of covariance as standard polymorphism what you would expect to work without thinking, because:

List<Car> cars;
List<Automobile> automobiles = cars;
// You'd expect this to work because Car is-a Automobile, but
// throws inconvertible types compile error.

The reason of the error is, however, correct: List<Car> does not inherit from List<Automobile> and thus cannot be assigned to each other. Only the generic type parameters have an inherit relationship. One might think that the Java compiler simply isn't smart enough to properly understand your scenario there. However, you can help the compiler by giving him a hint:

List<Car> cars;
List<? extends Automobile> automobiles = cars;   // no error

Contravariance

The reverse of co-variance is contravariance. Where in covariance the parameter types must have a subtype relationship, in contravariance they must have a supertype relationship. This can be considered as an inheritance upper-bound: any supertype is allowed up and including the specified type:

class AutoColorComparer implements Comparator<Automobile>
    public int compare(Automobile a, Automobile b) {
        // Return comparison of colors
    }

This can be used with Collections.sort:

public static <T> void sort(List<T> list, Comparator<? super T> c)

// Which you can call like this, without errors:
List<Car> cars = getListFromSomewhere();
Collections.sort(cars, new AutoColorComparer());

You could even call it with a comparer that compares objects and use it with any type.

When to use contra or co-variance?

A bit OT perhaps, you didn't ask, but it helps understanding answering your question. In general, when you get something, use covariance and when you put something, use contravariance. This is best explained in an answer to Stack Overflow question How would contravariance be used in Java generics?.

So what is it then with List<? extends Map<String, String>>

You use extends, so the rules for covariance applies. Here you have a list of maps and each item you store in the list must be a Map<string, string> or derive from it. The statement List<Map<String, String>> cannot derive from Map, but must be a Map.

Hence, the following will work, because TreeMap inherits from Map:

List<Map<String, String>> mapList = new ArrayList<Map<String, String>>();
mapList.add(new TreeMap<String, String>());

but this will not:

List<? extends Map<String, String>> mapList = new ArrayList<? extends Map<String, String>>();
mapList.add(new TreeMap<String, String>());

and this will not work either, because it does not satisfy the covariance constraint:

List<? extends Map<String, String>> mapList = new ArrayList<? extends Map<String, String>>();
mapList.add(new ArrayList<String>());   // This is NOT allowed, List does not implement Map

What else?

This is probably obvious, but you may have already noted that using the extends keyword only applies to that parameter and not to the rest. I.e., the following will not compile:

List<? extends Map<String, String>> mapList = new List<? extends Map<String, String>>();
mapList.add(new TreeMap<String, Element>())  // This is NOT allowed

Suppose you want to allow any type in the map, with a key as string, you can use extend on each type parameter. I.e., suppose you process XML and you want to store AttrNode, Element etc in a map, you can do something like:

List<? extends Map<String, ? extends Node>> listOfMapsOfNodes = new...;

// Now you can do:
listOfMapsOfNodes.add(new TreeMap<Sting, Element>());
listOfMapsOfNodes.add(new TreeMap<Sting, CDATASection>());

Get data from file input in JQuery

FileReader API with jQuery, simple example.

_x000D_
_x000D_
( function ( $ ) {_x000D_
 // Add click event handler to button_x000D_
 $( '#load-file' ).click( function () {_x000D_
  if ( ! window.FileReader ) {_x000D_
   return alert( 'FileReader API is not supported by your browser.' );_x000D_
  }_x000D_
  var $i = $( '#file' ), // Put file input ID here_x000D_
   input = $i[0]; // Getting the element from jQuery_x000D_
  if ( input.files && input.files[0] ) {_x000D_
   file = input.files[0]; // The file_x000D_
   fr = new FileReader(); // FileReader instance_x000D_
   fr.onload = function () {_x000D_
    // Do stuff on onload, use fr.result for contents of file_x000D_
    $( '#file-content' ).append( $( '<div/>' ).html( fr.result ) )_x000D_
   };_x000D_
   //fr.readAsText( file );_x000D_
   fr.readAsDataURL( file );_x000D_
  } else {_x000D_
   // Handle errors here_x000D_
   alert( "File not selected or browser incompatible." )_x000D_
  }_x000D_
 } );_x000D_
} )( jQuery );
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="file" id="file" />_x000D_
<input type='button' id='load-file' value='Load'>_x000D_
<div id="file-content"></div>
_x000D_
_x000D_
_x000D_

To read as text... uncomment //fr.readAsText(file); line and comment fr.readAsDataURL(file);

Cmake is not able to find Python-libraries

This problem can also happen in Windows. Cmake looks into the registry and sometimes python values are not set. For those with similar problem:

http://ericsilva.org/2012/10/11/restoring-your-python-registry-in-windows/

Just create a .reg file to set the necessary keys and edit accordingly to match your setup.

Windows Registry Editor Version 5.00

[HKEY_CURRENT_USER\Software\Python]

[HKEY_CURRENT_USER\Software\Python\Pythoncore]

[HKEY_CURRENT_USER\Software\Python\Pythoncore\2.6]

[HKEY_CURRENT_USER\Software\Python\Pythoncore\2.6\InstallPath]
@="C:\\python26"

[HKEY_CURRENT_USER\Software\Python\Pythoncore\2.6\PythonPath]
@="C:\\python26;C:\\python26\\Lib\\;C:\\python26\\DLLs\\"

[HKEY_CURRENT_USER\Software\Python\Pythoncore\2.7]

[HKEY_CURRENT_USER\Software\Python\Pythoncore\2.7\InstallPath]
@="C:\\python27"

[HKEY_CURRENT_USER\Software\Python\Pythoncore\2.7\PythonPath]
@="C:\\python27;C:\\python27\\Lib\\;C:\\python27\\DLLs\\"

Difference between "managed" and "unmanaged"

Managed Code

Managed code is what Visual Basic .NET and C# compilers create. It runs on the CLR (Common Language Runtime), which, among other things, offers services like garbage collection, run-time type checking, and reference checking. So, think of it as, "My code is managed by the CLR."

Visual Basic and C# can only produce managed code, so, if you're writing an application in one of those languages you are writing an application managed by the CLR. If you are writing an application in Visual C++ .NET you can produce managed code if you like, but it's optional.

Unmanaged Code

Unmanaged code compiles straight to machine code. So, by that definition all code compiled by traditional C/C++ compilers is 'unmanaged code'. Also, since it compiles to machine code and not an intermediate language it is non-portable.

No free memory management or anything else the CLR provides.

Since you cannot create unmanaged code with Visual Basic or C#, in Visual Studio all unmanaged code is written in C/C++.

Mixing the two

Since Visual C++ can be compiled to either managed or unmanaged code it is possible to mix the two in the same application. This blurs the line between the two and complicates the definition, but it's worth mentioning just so you know that you can still have memory leaks if, for example, you're using a third party library with some badly written unmanaged code.

Here's an example I found by googling:

#using <mscorlib.dll>
using namespace System;

#include "stdio.h"

void ManagedFunction()
{
    printf("Hello, I'm managed in this section\n");
}

#pragma unmanaged
UnmanagedFunction()
{
    printf("Hello, I am unmanaged through the wonder of IJW!\n");
    ManagedFunction();
}

#pragma managed
int main()
{
    UnmanagedFunction();
    return 0;
}

How to delete a whole folder and content?

Simple way to delete all file from directory :

It is generic function for delete all images from directory by calling only

deleteAllImageFile(context);

public static void deleteAllFile(Context context) {
File directory = context.getExternalFilesDir(null);
        if (directory.isDirectory()) {
            for (String fileName: file.list()) {
                new File(file,fileName).delete();
            }
        }    
    } 

Min / Max Validator in Angular 2 Final

USE

Validators.min(5)

It can be used while creating a formGroup variable along with other validators, as in

dueAmount: ['', [Validators.required, Validators.pattern(/^[+]?([0-9]+(?:[\.][0-9]*)?|\.[0-9]+)$/), Validators.min(5)]]

Not sure if it is in Angular 2, but is available in Angular 5

Android: making a fullscreen application

Adding current working solution for 'FLAG_FULLSCREEN' is deprecated

Add the following to your theme in themes.xml

<item name="windowNoTitle">true</item>
<item name="windowActionBar">false</item>

Worked perfectly for me.

How to pass variable number of arguments to a PHP function

You can just call it.

function test(){        
     print_r(func_get_args());
}

test("blah");
test("blah","blah");

Output:

Array ( [0] => blah ) Array ( [0] => blah [1] => blah )

Text in HTML Field to disappear when clicked?

How about something like this?

<input name="myvalue" type="text" onfocus="if(this.value=='enter value')this.value='';" onblur="if(this.value=='')this.value='enter value';">

This will clear upon focusing the first time, but then won't clear on subsequent focuses after the user enters their value, when left blank it restores the given value.

Android Layout Animations from bottom to top and top to bottom on ImageView click

I have solved my issue and now my animation works fine :) if anyone needed just copy my code and xml file and have a happy coding :)

My Activity MainActivity:

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;

public class MainActivity extends Activity {

RelativeLayout rl_footer;
ImageView iv_header;
boolean isBottom = true;
Button btn1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    rl_footer = (RelativeLayout) findViewById(R.id.rl_footer);
    iv_header = (ImageView) findViewById(R.id.iv_up_arrow);
    iv_header.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            iv_header.setImageResource(R.drawable.down_arrow);
            iv_header.setPadding(0, 10, 0, 0); 
            rl_footer.setBackgroundResource(R.drawable.up_manu_bar);
            if (isBottom) {
                SlideToAbove();
                isBottom = false;
            } else {
                iv_header.setImageResource(R.drawable.up_arrow);
                iv_header.setPadding(0, 0, 0, 10);
                rl_footer.setBackgroundResource(R.drawable.down_manu_bar1);
                SlideToDown();
                isBottom = true;
            }

        }
    });

}

public void SlideToAbove() {
    Animation slide = null;
    slide = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
            Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
            0.0f, Animation.RELATIVE_TO_SELF, -5.0f);

    slide.setDuration(400);
    slide.setFillAfter(true);
    slide.setFillEnabled(true);
    rl_footer.startAnimation(slide);

    slide.setAnimationListener(new AnimationListener() {

        @Override
        public void onAnimationStart(Animation animation) {

        }

        @Override
        public void onAnimationRepeat(Animation animation) {
        }

        @Override
        public void onAnimationEnd(Animation animation) {

            rl_footer.clearAnimation();

            RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                    rl_footer.getWidth(), rl_footer.getHeight());
            // lp.setMargins(0, 0, 0, 0);
            lp.addRule(RelativeLayout.ALIGN_PARENT_TOP);
            rl_footer.setLayoutParams(lp);

        }

    });

}

public void SlideToDown() {
    Animation slide = null;
    slide = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
            Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
            0.0f, Animation.RELATIVE_TO_SELF, 5.2f);

    slide.setDuration(400);
    slide.setFillAfter(true);
    slide.setFillEnabled(true);
    rl_footer.startAnimation(slide);

    slide.setAnimationListener(new AnimationListener() {

        @Override
        public void onAnimationStart(Animation animation) {

        }

        @Override
        public void onAnimationRepeat(Animation animation) {
        }

        @Override
        public void onAnimationEnd(Animation animation) {

            rl_footer.clearAnimation();

            RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                    rl_footer.getWidth(), rl_footer.getHeight());
            lp.setMargins(0, rl_footer.getWidth(), 0, 0);
            lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
            rl_footer.setLayoutParams(lp);

        }

    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

 }

and my Xml activity_main:

 <?xml version="1.0" encoding="utf-8"?>
 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/rl_main"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:background="@drawable/autograph_bg" >

 <RelativeLayout
    android:id="@+id/rl_footer"
    android:layout_width="fill_parent"
    android:layout_height="70dp"
    android:layout_alignParentBottom="true"
    android:background="@drawable/down_manu_bar1" >

    <ImageView
        android:id="@+id/iv_new_file"
        android:layout_width="25dp"
        android:layout_height="25dp"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:layout_marginLeft="18dp"
        android:onClick="onNewFileClick"
        android:src="@drawable/file_icon" />

    <TextView
        android:id="@+id/tv_new_file"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/iv_new_file"
        android:layout_below="@+id/iv_new_file"
        android:text="New"
        android:textColor="#ffffff" />

    <ImageView
        android:id="@+id/iv_insert"
        android:layout_width="25dp"
        android:layout_height="25dp"
        android:layout_alignTop="@+id/iv_new_file"
        android:layout_marginLeft="30dp"
        android:layout_toRightOf="@+id/iv_new_file"
        android:src="@drawable/insert_icon" />

    <TextView
        android:id="@+id/tv_insert"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/iv_insert"
        android:layout_below="@+id/iv_insert"
        android:text="Insert"
        android:textColor="#ffffff" />

    <ImageView
        android:id="@+id/iv_up_arrow"
        android:layout_width="45dp"
        android:layout_height="45dp"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:paddingBottom="10dp"
        android:src="@drawable/up_arrow" />

    <ImageView
        android:id="@+id/iv_down_arrow"
        android:layout_width="45dp"
        android:layout_height="45dp"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:background="@drawable/down_arrow"
        android:paddingBottom="10dp"
        android:visibility="gone" />

    <ImageView
        android:id="@+id/iv_save"
        android:layout_width="25dp"
        android:layout_height="25dp"
        android:layout_alignTop="@+id/iv_insert"
        android:layout_marginLeft="30dp"
        android:layout_toRightOf="@+id/iv_up_arrow"
        android:src="@drawable/save" />

    <TextView
        android:id="@+id/tv_save"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/iv_save"
        android:layout_alignParentBottom="true"
        android:text="Save"
        android:textColor="#ffffff" />

    <ImageView
        android:id="@+id/iv_settings"
        android:layout_width="25dp"
        android:layout_height="25dp"
        android:layout_alignTop="@+id/iv_save"
        android:layout_marginLeft="27dp"
        android:layout_toRightOf="@+id/tv_save"
        android:paddingTop="2dp"
        android:src="@drawable/icon_settings" />

    <TextView
        android:id="@+id/tv_settings"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_marginLeft="260dp"
        android:text="Settings"
        android:textColor="#ffffff" />
 </RelativeLayout>

 </RelativeLayout>

just create new android project and copy paste my code and have fun! :) also remember in xml i have image view and his background images replace with yout own images thanks..

Delete with "Join" in Oracle sql Query

Use a subquery in the where clause. For a delete query requirig a join, this example will delete rows that are unmatched in the joined table "docx_document" and that have a create date > 120 days in the "docs_documents" table.

delete from docs_documents d
where d.id in (
    select a.id from docs_documents a
    left join docx_document b on b.id = a.document_id
    where b.id is null
        and floor(sysdate - a.create_date) > 120
 );

including parameters in OPENQUERY

DECLARE @guid varchar(36);  select @guid= convert(varchar(36), NEWID() );
/*
    The one caveat to this technique is that ##ContextSpecificGlobal__Temp should ALWAYS have the exact same columns.  
    So make up your global temp table name in the sproc you're using it in and only there!
    In this example I wanted to pass in the name of a global temporary table dynamically.  I have 1 procedure dropping 
    off temporary data in whatever @TableSrc is and another procedure picking it up but we are dynamically passing 
    in the name of our pickup table as a parameter for OPENQUERY.
*/
IF ( OBJECT_ID('tempdb..##ContextSpecificGlobal__Temp' , 'U') IS NULL )
    EXEC ('SELECT * INTO ##ContextSpecificGlobal__Temp FROM OPENQUERY(loopback, ''Select *,''''' +  @guid +''''' as tempid FROM ' + @TableSrc + ''')')
ELSE 
    EXEC ('INSERT ##ContextSpecificGlobal__Temp SELECT * FROM OPENQUERY(loopback, ''Select *,''''' +  @guid +''''' as tempid FROM ' + @TableSrc + ''')')

--If this proc is run frequently we could run into race conditions, that's why we are adding a guid and only deleting
--the data we added to ##ContextSpecificGlobal__Temp
SELECT * INTO #TableSrc FROM ##ContextSpecificGlobal__Temp WHERE tempid = @guid

BEGIN TRAN t1
    IF ( OBJECT_ID('tempdb..##ContextSpecificGlobal__Temp' , 'U') IS NOT NULL ) 
    BEGIN
        -- Here we wipe out our left overs if there if everyones done eating the data
        IF (SELECT COUNT(*) FROM ##ContextSpecificGlobal__Temp) = 0
            DROP TABLE ##ContextSpecificGlobal__Temp
    END
COMMIT TRAN t1

-- YEAH! Now I can use the data from my openquery without wrapping the whole !$#@$@ thing in a string.

'IF' in 'SELECT' statement - choose output value based on column values

Most simplest way is to use a IF(). Yes Mysql allows you to do conditional logic. IF function takes 3 params CONDITION, TRUE OUTCOME, FALSE OUTCOME.

So Logic is

if report.type = 'p' 
    amount = amount 
else 
    amount = -1*amount 

SQL

SELECT 
    id, IF(report.type = 'P', abs(amount), -1*abs(amount)) as amount
FROM  report

You may skip abs() if all no's are +ve only

What is the difference between HAVING and WHERE in SQL?

HAVING is used when you are using an aggregate such as GROUP BY.

SELECT edc_country, COUNT(*)
FROM Ed_Centers
GROUP BY edc_country
HAVING COUNT(*) > 1
ORDER BY edc_country;

Check Postgres access for a user

Use this to list Grantee too and remove (PG_monitor and Public) for Postgres PaaS Azure.

SELECT grantee,table_catalog, table_schema, table_name, privilege_type
FROM   information_schema.table_privileges 
WHERE  grantee not in ('pg_monitor','PUBLIC');

What is Cache-Control: private?

RFC 2616, section 14.9.1:

Indicates that all or part of the response message is intended for a single user and MUST NOT be cached by a shared cache...A private (non-shared) cache MAY cache the response.


Browsers could use this information. Of course, the current "user" may mean many things: OS user, a browser user (e.g. Chrome's profiles), etc. It's not specified.

For me, a more concrete example of Cache-Control: private is that proxy servers (which typically have many users) won't cache it. It is meant for the end user, and no one else.


FYI, the RFC makes clear that this does not provide security. It is about showing the correct content, not securing content.

This usage of the word private only controls where the response may be cached, and cannot ensure the privacy of the message content.

GridLayout (not GridView) how to stretch all children evenly

You can set width of every child dynamically:

GridLayout.LayoutParams params = (GridLayout.LayoutParams) child.getLayoutParams();
    params.width = (parent.getWidth()/parent.getColumnCount()) -params.rightMargin - params.leftMargin;
    child.setLayoutParams(params);

Best Practice: Software Versioning

I basically follow this pattern:

  • start from 0.1.0

  • when it's ready I branch the code in the source repo, tag 0.1.0 and create the 0.1.0 branch, the head/trunk becomes 0.2.0-snapshot or something similar

  • I add new features only to the trunk, but backport fixes to the branch and in time I release from it 0.1.1, 0.1.2, ...

  • I declare version 1.0.0 when the product is considered feature complete and doesn't have major shortcomings

  • from then on - everyone can decide when to increment the major version...

Error:attempt to apply non-function

You're missing *s in the last two terms of your expression, so R is interpreting (e.g.) 0.207 (log(DIAM93))^2 as an attempt to call a function named 0.207 ...

For example:

> 1 + 2*(3)
[1] 7
> 1 + 2 (3)

Error: attempt to apply non-function

Your (unreproducible) expression should read:

censusdata_20$AGB93 = WD * exp(-1.239 + 1.980 * log (DIAM93) + 
                              0.207* (log(DIAM93))^2  -
                              0.0281*(log(DIAM93))^3)

Mathematica is the only computer system I know of that allows juxtaposition to be used for multiplication ...

What static analysis tools are available for C#?

Axivion Bauhaus Suite is a static analysis tool that works with C# (as well as C, C++ and Java).

It provides the following capabilities:

  • Software Architecture Visualization (inlcuding dependencies)
  • Enforcement of architectural rules e.g. layering, subsystems, calling rules
  • Clone Detection - highlighting copy and pasted (and modified code)
  • Dead Code Detection
  • Cycle Detection
  • Software Metrics
  • Code Style Checks

These features can be run on a one-off basis or as part of a Continuous Integration process. Issues can be highlighted on a per project basis or per developer basis when the system is integrated with a source code control system.

TypeError: only integer scalar arrays can be converted to a scalar index with 1D numpy indices array

Another case that could cause this error is

>>> np.ndindex(np.random.rand(60,60))
TypeError: only integer scalar arrays can be converted to a scalar index

Using the actual shape will fix it.

>>> np.ndindex(np.random.rand(60,60).shape)
<numpy.ndindex object at 0x000001B887A98880>

How to exclude *AutoConfiguration classes in Spring Boot JUnit tests?

got into same kind of problem, wasn't able to exclude main spring boot class during testing. Solved it using following approach.

Instead of using @SpringBootApplication, use all three annotations which it contains and assign the name to @Configuration

@Configuration("myApp")
@EnableAutoConfiguration
@ComponentScan
public class MyApp { .. }

In your test class define configuration with exactly same name:

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
// ugly hack how to exclude main configuration
@Configuration("myApp")
@SpringApplicationConfiguration(classes = MyTest.class)
public class MyTest { ... }

This should help. Would be nice to have some better way in place how to disable auto scanning for configuration annotations...

Fixed header, footer with scrollable content

Approach 1 - flexbox

It works great for both known and unknown height elements. Make sure to set the outer div to height: 100%; and reset the default margin on body. See the browser support tables.

jsFiddle

_x000D_
_x000D_
html, body {_x000D_
  height: 100%;_x000D_
  margin: 0;_x000D_
}_x000D_
.wrapper {_x000D_
  height: 100%;_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
}_x000D_
.header, .footer {_x000D_
  background: silver;_x000D_
}_x000D_
.content {_x000D_
  flex: 1;_x000D_
  overflow: auto;_x000D_
  background: pink;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <div class="header">Header</div>_x000D_
  <div class="content">_x000D_
    <div style="height:1000px;">Content</div>_x000D_
  </div>_x000D_
  <div class="footer">Footer</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Approach 2 - CSS table

For both known and unknown height elements. It also works in legacy browsers including IE8.

jsFiddle

_x000D_
_x000D_
html, body {_x000D_
  height: 100%;_x000D_
  margin: 0;_x000D_
}_x000D_
.wrapper {_x000D_
  height: 100%;_x000D_
  width: 100%;_x000D_
  display: table;_x000D_
}_x000D_
.header, .content, .footer {_x000D_
  display: table-row;_x000D_
}_x000D_
.header, .footer {_x000D_
  background: silver;_x000D_
}_x000D_
.inner {_x000D_
  display: table-cell;_x000D_
}_x000D_
.content .inner {_x000D_
  height: 100%;_x000D_
  position: relative;_x000D_
  background: pink;_x000D_
}_x000D_
.scrollable {_x000D_
  position: absolute;_x000D_
  left: 0; right: 0;_x000D_
  top: 0; bottom: 0;_x000D_
  overflow: auto;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <div class="header">_x000D_
    <div class="inner">Header</div>_x000D_
  </div>_x000D_
  <div class="content">_x000D_
    <div class="inner">_x000D_
      <div class="scrollable">_x000D_
        <div style="height:1000px;">Content</div>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class="footer">_x000D_
    <div class="inner">Footer</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Approach 3 - calc()

If header and footer are fixed height, you can use CSS calc().

jsFiddle

_x000D_
_x000D_
html, body {_x000D_
  height: 100%;_x000D_
  margin: 0;_x000D_
}_x000D_
.wrapper {_x000D_
  height: 100%;_x000D_
}_x000D_
.header, .footer {_x000D_
  height: 50px;_x000D_
  background: silver;_x000D_
}_x000D_
.content {_x000D_
  height: calc(100% - 100px);_x000D_
  overflow: auto;_x000D_
  background: pink;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <div class="header">Header</div>_x000D_
  <div class="content">_x000D_
    <div style="height:1000px;">Content</div>_x000D_
  </div>_x000D_
  <div class="footer">Footer</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Approach 4 - % for all

If the header and footer are known height, and they are also percentage you can just do the simple math making them together of 100% height.

_x000D_
_x000D_
html, body {_x000D_
  height: 100%;_x000D_
  margin: 0;_x000D_
}_x000D_
.wrapper {_x000D_
  height: 100%;_x000D_
}_x000D_
.header, .footer {_x000D_
  height: 10%;_x000D_
  background: silver;_x000D_
}_x000D_
.content {_x000D_
  height: 80%;_x000D_
  overflow: auto;_x000D_
  background: pink;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <div class="header">Header</div>_x000D_
  <div class="content">_x000D_
    <div style="height:1000px;">Content</div>_x000D_
  </div>_x000D_
  <div class="footer">Footer</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

jsFiddle

Is there a way to represent a directory tree in a Github README.md?

Insert command tree in bash.

Also, there is a DOS comnand "tree". You can displays directory paths and files in each subdirectory with command:

tree /F

https://web.csulb.edu/~murdock/tree.html

Invert "if" statement to reduce nesting

In my opinion early return is fine if you are just returning void (or some useless return code you're never gonna check) and it might improve readability because you avoid nesting and at the same time you make explicit that your function is done.

If you are actually returning a returnValue - nesting is usually a better way to go cause you return your returnValue just in one place (at the end - duh), and it might make your code more maintainable in a whole lot of cases.

"Retrieving the COM class factory for component.... error: 80070005 Access is denied." (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))

Sometimes, you create new application pool and cann't solve it via DCOMCNFG. Then there is another method to do:

Set the Identity (Model Name) of application pool to LocalSystem.

I don't know the root cause, but it solve my problem one time.

get and set in TypeScript

You can write this

class Human {
    private firstName : string;
    private lastName : string;

    constructor (
        public FirstName?:string, 
        public LastName?:string) {

    }

    get FirstName() : string {
        console.log("Get FirstName : ", this.firstName);
        return this.firstName;
    }
    set FirstName(value : string) {
        console.log("Set FirstName : ", value);
        this.firstName = value;
    } 

    get LastName() : string {
        console.log("Get LastName : ", this.lastName);
        return this.lastName;
    }
    set LastName(value : string) {
        console.log("Set LastName : ", value);
        this.lastName = value;
    } 

}

Decrypt password created with htpasswd

.htpasswd entries are HASHES. They are not encrypted passwords. Hashes are designed not to be decryptable. Hence there is no way (unless you bruteforce for a loooong time) to get the password from the .htpasswd file.

What you need to do is apply the same hash algorithm to the password provided to you and compare it to the hash in the .htpasswd file. If the user and hash are the same then you're a go.

How do I Search/Find and Replace in a standard string?

#include <string>

using std::string;

void myReplace(string& str,
               const string& oldStr,
               const string& newStr) {
  if (oldStr.empty()) {
    return;
  }

  for (size_t pos = 0; (pos = str.find(oldStr, pos)) != string::npos;) {
    str.replace(pos, oldStr.length(), newStr);
    pos += newStr.length();
  }
}

The check for oldStr being empty is important. If for whatever reason that parameter is empty you will get stuck in an infinite loop.

But yeah use the tried and tested C++11 or Boost solution if you can.

insert echo into the specific html element like div which has an id or class

Well from your code its clear that $row['name'] is the location of the image on the file, try including the div tag like this

echo '<div>' .$row['name']. '</div>' ;

and do the same for others, let me know if it works because you said that one snippet of your code is giving the desired result so try this and if the div has some class specifier then do this

echo '<div class="whatever_it_is">' . $row['name'] . '</div'> ;

Including external HTML file to another HTML file

Another way is to use the object tag. This works on Chrome, IE, Firefox, Safari and Opera.

<object data="html/stuff_to_include.html"> 
    Your browser doesn’t support the object tag. 
</object>

more info at http://www.w3schools.com/tags/tag_object.asp

How is OAuth 2 different from OAuth 1?

OAuth 2.0 promises to simplify things in following ways:

  1. SSL is required for all the communications required to generate the token. This is a huge decrease in complexity because those complex signatures are no longer required.
  2. Signatures are not required for the actual API calls once the token has been generated -- SSL is also strongly recommended here.
  3. Once the token was generated, OAuth 1.0 required that the client send two security tokens on every API call, and use both to generate the signature. OAuth 2.0 has only one security token, and no signature is required.
  4. It is clearly specified which parts of the protocol are implemented by the "resource owner," which is the actual server that implements the API, and which parts may be implemented by a separate "authorization server." That will make it easier for products like Apigee to offer OAuth 2.0 support to existing APIs.

Source:http://blog.apigee.com/detail/oauth_differences

How to position the Button exactly in CSS

Try using absolute positioning, rather than relative positioning

this should get you close - you can adjust by tweaking margins or top/left positions

#play_button {
    position:absolute;
    transition: .5s ease;
    top: 50%;
    left: 50%;
}

http://jsfiddle.net/rolfsf/9pNqS/

Include CSS,javascript file in Yii Framework

In Yii framework, You can include js and css using below method.

Including CSS:

{Yii::app()->request->baseUrl}/css/styles.css

Including JS:

{Yii::app()->request->baseUrl}/js/script.js

Including Image:

{Yii::app()->request->baseUrl}/images/logo.jpg

Note: By using layout concept in yii, You can add css and js instead of specifying in view template.

Angular2 change detection: ngOnChanges not firing for nested object

If the data comes from an external library you might need to run the data upate statement within zone.run(...). Inject zone: NgZone for this. If you can run the instantiation of the external library within zone.run() already, then you might not need zone.run() later.

Removing elements with Array.map in JavaScript

I just wrote array intersection that correctly handles also duplicates

https://gist.github.com/gkucmierz/8ee04544fa842411f7553ef66ac2fcf0

_x000D_
_x000D_
// array intersection that correctly handles also duplicates_x000D_
_x000D_
const intersection = (a1, a2) => {_x000D_
  const cnt = new Map();_x000D_
  a2.map(el => cnt[el] = el in cnt ? cnt[el] + 1 : 1);_x000D_
  return a1.filter(el => el in cnt && 0 < cnt[el]--);_x000D_
};_x000D_
_x000D_
const l = console.log;_x000D_
l(intersection('1234'.split``, '3456'.split``)); // [ '3', '4' ]_x000D_
l(intersection('12344'.split``, '3456'.split``)); // [ '3', '4' ]_x000D_
l(intersection('1234'.split``, '33456'.split``)); // [ '3', '4' ]_x000D_
l(intersection('12334'.split``, '33456'.split``)); // [ '3', '3', '4' ]
_x000D_
_x000D_
_x000D_

SELECT list is not in GROUP BY clause and contains nonaggregated column

As @Brian Riley already said you should either remove 1 column in your select

select countrylanguage.language ,sum(country.population*countrylanguage.percentage/100)
from countrylanguage
join country on countrylanguage.countrycode = country.code
group by countrylanguage.language
order by sum(country.population*countrylanguage.percentage) desc ;

or add it to your grouping

select countrylanguage.language, country.code, sum(country.population*countrylanguage.percentage/100)
from countrylanguage
join country on countrylanguage.countrycode = country.code
group by countrylanguage.language, country.code
order by sum(country.population*countrylanguage.percentage) desc ;

File count from a folder

.NET methods Directory.GetFiles(dir) or DirectoryInfo.GetFiles() are not very fast for just getting a total file count. If you use this file count method very heavily, consider using WinAPI directly, which saves about 50% of time.

Here's the WinAPI approach where I encapsulate WinAPI calls to a C# method:

int GetFileCount(string dir, bool includeSubdirectories = false)

Complete code:

[Serializable, StructLayout(LayoutKind.Sequential)]
private struct WIN32_FIND_DATA
{
    public int dwFileAttributes;
    public int ftCreationTime_dwLowDateTime;
    public int ftCreationTime_dwHighDateTime;
    public int ftLastAccessTime_dwLowDateTime;
    public int ftLastAccessTime_dwHighDateTime;
    public int ftLastWriteTime_dwLowDateTime;
    public int ftLastWriteTime_dwHighDateTime;
    public int nFileSizeHigh;
    public int nFileSizeLow;
    public int dwReserved0;
    public int dwReserved1;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
    public string cFileName;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 14)]
    public string cAlternateFileName;
}

[DllImport("kernel32.dll")]
private static extern IntPtr FindFirstFile(string pFileName, ref WIN32_FIND_DATA pFindFileData);
[DllImport("kernel32.dll")]
private static extern bool FindNextFile(IntPtr hFindFile, ref WIN32_FIND_DATA lpFindFileData);
[DllImport("kernel32.dll")]
private static extern bool FindClose(IntPtr hFindFile);

private static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);
private const int FILE_ATTRIBUTE_DIRECTORY = 16;

private int GetFileCount(string dir, bool includeSubdirectories = false)
{
    string searchPattern = Path.Combine(dir, "*");

    var findFileData = new WIN32_FIND_DATA();
    IntPtr hFindFile = FindFirstFile(searchPattern, ref findFileData);
    if (hFindFile == INVALID_HANDLE_VALUE)
        throw new Exception("Directory not found: " + dir);

    int fileCount = 0;
    do
    {
        if (findFileData.dwFileAttributes != FILE_ATTRIBUTE_DIRECTORY)
        {
            fileCount++;
            continue;
        }

        if (includeSubdirectories && findFileData.cFileName != "." && findFileData.cFileName != "..")
        {
            string subDir = Path.Combine(dir, findFileData.cFileName);
            fileCount += GetFileCount(subDir, true);
        }
    }
    while (FindNextFile(hFindFile, ref findFileData));

    FindClose(hFindFile);

    return fileCount;
}

When I search in a folder with 13000 files on my computer - Average: 110ms

int fileCount = GetFileCount(searchDir, true); // using WinAPI

.NET built-in method: Directory.GetFiles(dir) - Average: 230ms

int fileCount = Directory.GetFiles(searchDir, "*", SearchOption.AllDirectories).Length;

Note: first run of either of the methods will be 60% - 100% slower respectively because the hard drive takes a little longer to locate the sectors. Subsequent calls will be semi-cached by Windows, I guess.

What is the difference between java and core java?

A simple step to understand what is java and core java.

  • Find a book for Java.

  • Find a book for core java.

  • Compare the content of both books.

Actual result: both have almost same content.

Result: Java and core java is same.

core java is just slang, to emphasize on deep knowledge of basic java. but if I say I know Java it doesn't mean that I don't have deep knowledge of basic java, or if I know everything in java.

How do I use Wget to download all images into a single folder, from a URL?

The proposed solutions are perfect to download the images and if it is enough for you to save all the files in the directory you are using. But if you want to save all the images in a specified directory without reproducing the entire hierarchical tree of the site, try to add "cut-dirs" to the line proposed by Jon.

wget -r -P /save/location -A jpeg,jpg,bmp,gif,png http://www.boia.de --cut-dirs=1 --cut-dirs=2 --cut-dirs=3

in this case cut-dirs will prevent wget from creating sub-directories until the 3th level of depth in the website hierarchical tree, saving all the files in the directory you specified.You can add more 'cut-dirs' with higher numbers if you are dealing with sites with a deep structure.

Relative URLs in WordPress

What i think you do is while you change domain names, the sql dump file that you have you can replace all instances of old domain name with new one. This is only option available as there are no plugins that will help you do this.

This is quickest way ..

Purpose of ESI & EDI registers?

There are a few operations you can only do with DI/SI (or their extended counterparts, if you didn't learn ASM in 1985). Among these are

REP STOSB
REP MOVSB
REP SCASB

Which are, respectively, operations for repeated (= mass) storing, loading and scanning. What you do is you set up SI and/or DI to point at one or both operands, perhaps put a count in CX and then let 'er rip. These are operations that work on a bunch of bytes at a time, and they kind of put the CPU in automatic. Because you're not explicitly coding loops, they do their thing more efficiently (usually) than a hand-coded loop.

Just in case you're wondering: Depending on how you set the operation up, repeated storing can be something simple like punching the value 0 into a large contiguous block of memory; MOVSB is used, I think, to copy data from one buffer (well, any bunch of bytes) to another; and SCASB is used to look for a byte that matches some search criterion (I'm not sure if it's only searching on equality, or what – you can look it up :) )

That's most of what those regs are for.

Eclipse will not start and I haven't changed anything

I tried the option above of moving the plugins but it didn't work. My solution was to delete the entire .metadata folder. This meant that I lost my defaults and had to import my projects again.

AngularJS: Insert HTML from a string

you can also use $sce.trustAsHtml('"<h1>" + str + "</h1>"'),if you want to know more detail, please refer to $sce

PHP Function with Optional Parameters

Make the function take one parameter: an array. Pass in the actual parameters as values in the array.


Edit: the link in Pekka's comment just about sums it up.

How can I change the default Mysql connection timeout when connecting through python?

Do:

con.query('SET GLOBAL connect_timeout=28800')
con.query('SET GLOBAL interactive_timeout=28800')
con.query('SET GLOBAL wait_timeout=28800')

Parameter meaning (taken from MySQL Workbench in Navigator: Instance > Options File > Tab "Networking" > Section "Timeout Settings")

  • connect_timeout: Number of seconds the mysqld server waits for a connect packet before responding with 'Bad handshake'
  • interactive_timeout Number of seconds the server waits for activity on an interactive connection before closing it
  • wait_timeout Number of seconds the server waits for activity on a connection before closing it

BTW: 28800 seconds are 8 hours, so for a 10 hour execution time these values should be actually higher.

How to save local data in a Swift app?

Using NSCoding and NSKeyedArchiver is another great option for data that's too complex for NSUserDefaults, but for which CoreData would be overkill. It also gives you the opportunity to manage the file structure more explicitly, which is great if you want to use encryption.

Way to create multiline comments in Bash?

Simple solution, not much smart:

Temporarily block a part of a script:

if false; then
    while you respect syntax a bit, please
    do write here (almost) whatever you want.
    but when you are
    done # write
fi

A bit sophisticated version:

time_of_debug=false # Let's set this variable at the beginning of a script

if $time_of_debug; then # in a middle of the script  
    echo I keep this code aside until there is the time of debug!
fi

jQuery pass more parameters into callback

I've made a mistake in the last my post. This is working example for how to pass additional argument in callback function:

function custom_func(p1,p2) {
    $.post(AJAX_FILE_PATH,{op:'dosomething',p1:p1},
        function(data){
            return function(){
                alert(data);
                alert(p2);
            }(data,p2)
        }
    );
    return false;
}

Angular2 - Input Field To Accept Only Numbers

You can use angular2 directives. Plunkr

import { Directive, ElementRef, HostListener, Input } from '@angular/core';

@Directive({
  selector: '[OnlyNumber]'
})
export class OnlyNumber {

  constructor(private el: ElementRef) { }

  @Input() OnlyNumber: boolean;

  @HostListener('keydown', ['$event']) onKeyDown(event) {
    let e = <KeyboardEvent> event;
    if (this.OnlyNumber) {
      if ([46, 8, 9, 27, 13, 110, 190].indexOf(e.keyCode) !== -1 ||
        // Allow: Ctrl+A
        (e.keyCode === 65 && (e.ctrlKey || e.metaKey)) ||
        // Allow: Ctrl+C
        (e.keyCode === 67 && (e.ctrlKey || e.metaKey)) ||
        // Allow: Ctrl+V
        (e.keyCode === 86 && (e.ctrlKey || e.metaKey)) ||
        // Allow: Ctrl+X
        (e.keyCode === 88 && (e.ctrlKey || e.metaKey)) ||
        // Allow: home, end, left, right
        (e.keyCode >= 35 && e.keyCode <= 39)) {
          // let it happen, don't do anything
          return;
        }
        // Ensure that it is a number and stop the keypress
        if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
            e.preventDefault();
        }
      }
  }
}

and you need to write the directive name in your input as an attribute

<input OnlyNumber="true" />

don't forget to write your directive in declarations array of your module.

By using regex you would still need functional keys

export class OnlyNumber {

  regexStr = '^[0-9]*$';
  constructor(private el: ElementRef) { }

  @Input() OnlyNumber: boolean;

  @HostListener('keydown', ['$event']) onKeyDown(event) {
    let e = <KeyboardEvent> event;
    if (this.OnlyNumber) {
        if ([46, 8, 9, 27, 13, 110, 190].indexOf(e.keyCode) !== -1 ||
        // Allow: Ctrl+A
        (e.keyCode == 65 && e.ctrlKey === true) ||
        // Allow: Ctrl+C
        (e.keyCode == 67 && e.ctrlKey === true) ||
        // Allow: Ctrl+V
        (e.keyCode == 86 && e.ctrlKey === true) ||
        // Allow: Ctrl+X
        (e.keyCode == 88 && e.ctrlKey === true) ||
        // Allow: home, end, left, right
        (e.keyCode >= 35 && e.keyCode <= 39)) {
          // let it happen, don't do anything
          return;
        }
      let ch = String.fromCharCode(e.keyCode);
      let regEx =  new RegExp(this.regexStr);    
      if(regEx.test(ch))
        return;
      else
         e.preventDefault();
      }
  }
}

lodash multi-column sortBy descending

It's worth noting that if you want to sort particular properties descending, you don't want to simply append .reverse() at the end, as this will make all of the sorts descending.

To make particular sorts descending, chain your sorts from least significant to most significant, calling .reverse() after each sort that you want to be descending.

var data = _(data).chain()
    .sort("date")
    .reverse()    // sort by date descending
    .sort("name") // sort by name ascending
    .result()

Since _'s sort is a stable sort, you can safely chain and reverse sorts because if two items have the same value for a property, their order is preserved.

More information

How can I send an email through the UNIX mailx command?

If you want to send more than two person or DL :

echo "Message Body" | mailx -s "Message Title" -r [email protected] [email protected],[email protected]

here:

  • -s = subject or mail title
  • -r = sender mail or DL

Include of non-modular header inside framework module

If you see this error in an umbrella header when building a dynamic framework, make sure you import your file as:

#import "MyFile.h"

and not as #import <MyFramework/MyFile.h>.

Resetting remote to a certain commit

Do one thing, get the commit's SHA no. such as 87c9808 and then,

  1. move yourself ,that is your head to the specified commit (by doing git reset --hard 89cef43//mention your number here )
  2. Next do some changes in a random file , so that the git will ask you to commit that locally and then remotely Thus, what you need to do now is. after applying change git commit -a -m "trial commit"
  3. Now push the following commit (if this has been committed locally) by git push origin master
  4. Now what git will ask from you is that

error: failed to push some refs to 'https://github.com/YOURREPOSITORY/AndroidExperiments.git' hint: Updates were rejected because the tip of your current branch is behind hint: its remote counterpart. Integrate the remote changes (e.g. hint: 'git pull ...') before pushing again.**

  1. Thus now what you can do is

git push --force origin master

  1. And thus, i hope it works :)

How do I detect when someone shakes an iPhone?

In iOS 8.3 (perhaps earlier) with Swift, it's as simple as overriding the motionBegan or motionEnded methods in your view controller:

class ViewController: UIViewController {
    override func motionBegan(motion: UIEventSubtype, withEvent event: UIEvent) {
        println("started shaking!")
    }

    override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent) {
        println("ended shaking!")
    }
}

Looping Over Result Sets in MySQL

Use cursors.

A cursor can be thought of like a buffered reader, when reading through a document. If you think of each row as a line in a document, then you would read the next line, perform your operations, and then advance the cursor.

How to implement my very own URI scheme on Android

As the question is asked years ago, and Android is evolved a lot on this URI scheme.
From original URI scheme, to deep link, and now Android App Links.

Android now recommends to use HTTP URLs, not define your own URI scheme. Because Android App Links use HTTP URLs that link to a website domain you own, so no other app can use your links. You can check the comparison of deep link and Android App links from here

Now you can easily add a URI scheme by using Android Studio option: Tools > App Links Assistant. Please refer the detail to Android document: https://developer.android.com/studio/write/app-link-indexing.html

What can lead to "IOError: [Errno 9] Bad file descriptor" during os.system()?

You can get this error if you use wrong mode when opening the file. For example:

    with open(output, 'wb') as output_file:
        print output_file.read()

In that code, I want to read the file, but I use mode wb instead of r or r+

How to activate an Anaconda environment

Though @Simba had a good answer at the time, a lot has changed in the conda env since 4.6. Conda activate (env-name) overthrew source activate (env-name) for good but not without it own challenges. conda activate oftentimes forces your environment to base and makes you see something like this:

(base)

and throwing loads of error back at you. This can also be because auto_activate_base is set to True.

You can check this by using the following command

conda config --set auto_activate_base False
source ~/.bashrc

And to reactivate use this

conda config --set auto_activate_base True
source ~/.bashrc