Programs & Examples On #Signal processing

AKA digital signal processing (DSP). A signal is an information-carrying changing attribute of an entity, but in the digital sense, 'signal' refers to either received or transmitted streams/blocks of data, commonly representing real-world quantities such as audio levels, luminosity, pressure etc over time or distance. 'Processing' is the act of altering, analyzing or characterizing the data to retrieve/modify information inherent in the signal in question.

Creating lowpass filter in SciPy - understanding methods and units

A few comments:

  • The Nyquist frequency is half the sampling rate.
  • You are working with regularly sampled data, so you want a digital filter, not an analog filter. This means you should not use analog=True in the call to butter, and you should use scipy.signal.freqz (not freqs) to generate the frequency response.
  • One goal of those short utility functions is to allow you to leave all your frequencies expressed in Hz. You shouldn't have to convert to rad/sec. As long as you express your frequencies with consistent units, the scaling in the utility functions takes care of the normalization for you.

Here's my modified version of your script, followed by the plot that it generates.

import numpy as np
from scipy.signal import butter, lfilter, freqz
import matplotlib.pyplot as plt


def butter_lowpass(cutoff, fs, order=5):
    nyq = 0.5 * fs
    normal_cutoff = cutoff / nyq
    b, a = butter(order, normal_cutoff, btype='low', analog=False)
    return b, a

def butter_lowpass_filter(data, cutoff, fs, order=5):
    b, a = butter_lowpass(cutoff, fs, order=order)
    y = lfilter(b, a, data)
    return y


# Filter requirements.
order = 6
fs = 30.0       # sample rate, Hz
cutoff = 3.667  # desired cutoff frequency of the filter, Hz

# Get the filter coefficients so we can check its frequency response.
b, a = butter_lowpass(cutoff, fs, order)

# Plot the frequency response.
w, h = freqz(b, a, worN=8000)
plt.subplot(2, 1, 1)
plt.plot(0.5*fs*w/np.pi, np.abs(h), 'b')
plt.plot(cutoff, 0.5*np.sqrt(2), 'ko')
plt.axvline(cutoff, color='k')
plt.xlim(0, 0.5*fs)
plt.title("Lowpass Filter Frequency Response")
plt.xlabel('Frequency [Hz]')
plt.grid()


# Demonstrate the use of the filter.
# First make some data to be filtered.
T = 5.0         # seconds
n = int(T * fs) # total number of samples
t = np.linspace(0, T, n, endpoint=False)
# "Noisy" data.  We want to recover the 1.2 Hz signal from this.
data = np.sin(1.2*2*np.pi*t) + 1.5*np.cos(9*2*np.pi*t) + 0.5*np.sin(12.0*2*np.pi*t)

# Filter the data, and plot both the original and filtered signals.
y = butter_lowpass_filter(data, cutoff, fs, order)

plt.subplot(2, 1, 2)
plt.plot(t, data, 'b-', label='data')
plt.plot(t, y, 'g-', linewidth=2, label='filtered data')
plt.xlabel('Time [sec]')
plt.grid()
plt.legend()

plt.subplots_adjust(hspace=0.35)
plt.show()

lowpass example

How do I obtain the frequencies of each value in an FFT?

I have used the following:

public static double Index2Freq(int i, double samples, int nFFT) {
  return (double) i * (samples / nFFT / 2.);
}

public static int Freq2Index(double freq, double samples, int nFFT) {
  return (int) (freq / (samples / nFFT / 2.0));
}

The inputs are:

  • i: Bin to access
  • samples: Sampling rate in Hertz (i.e. 8000 Hz, 44100Hz, etc.)
  • nFFT: Size of the FFT vector

How to smooth a curve in the right way?

Another option is to use KernelReg in statsmodels:

from statsmodels.nonparametric.kernel_regression import KernelReg
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0,2*np.pi,100)
y = np.sin(x) + np.random.random(100) * 0.2

# The third parameter specifies the type of the variable x;
# 'c' stands for continuous
kr = KernelReg(y,x,'c')
plt.plot(x, y, '+')
y_pred, y_std = kr.fit(x)

plt.plot(x, y_pred)
plt.show()

Plotting power spectrum in python

Numpy has a convenience function, np.fft.fftfreq to compute the frequencies associated with FFT components:

from __future__ import division
import numpy as np
import matplotlib.pyplot as plt

data = np.random.rand(301) - 0.5
ps = np.abs(np.fft.fft(data))**2

time_step = 1 / 30
freqs = np.fft.fftfreq(data.size, time_step)
idx = np.argsort(freqs)

plt.plot(freqs[idx], ps[idx])

enter image description here

Note that the largest frequency you see in your case is not 30 Hz, but

In [7]: max(freqs)
Out[7]: 14.950166112956811

You never see the sampling frequency in a power spectrum. If you had had an even number of samples, then you would have reached the Nyquist frequency, 15 Hz in your case (although numpy would have calculated it as -15).

Peak signal detection in realtime timeseries data

An iterative version in python/numpy for answer https://stackoverflow.com/a/22640362/6029703 is here. This code is faster than computing average and standard deviation every lag for large data (100000+).

def peak_detection_smoothed_zscore_v2(x, lag, threshold, influence):
    '''
    iterative smoothed z-score algorithm
    Implementation of algorithm from https://stackoverflow.com/a/22640362/6029703
    '''
    import numpy as np
    labels = np.zeros(len(x))
    filtered_y = np.array(x)
    avg_filter = np.zeros(len(x))
    std_filter = np.zeros(len(x))
    var_filter = np.zeros(len(x))

    avg_filter[lag - 1] = np.mean(x[0:lag])
    std_filter[lag - 1] = np.std(x[0:lag])
    var_filter[lag - 1] = np.var(x[0:lag])
    for i in range(lag, len(x)):
        if abs(x[i] - avg_filter[i - 1]) > threshold * std_filter[i - 1]:
            if x[i] > avg_filter[i - 1]:
                labels[i] = 1
            else:
                labels[i] = -1
            filtered_y[i] = influence * x[i] + (1 - influence) * filtered_y[i - 1]
        else:
            labels[i] = 0
            filtered_y[i] = x[i]
        # update avg, var, std
        avg_filter[i] = avg_filter[i - 1] + 1. / lag * (filtered_y[i] - filtered_y[i - lag])
        var_filter[i] = var_filter[i - 1] + 1. / lag * ((filtered_y[i] - avg_filter[i - 1]) ** 2 - (
            filtered_y[i - lag] - avg_filter[i - 1]) ** 2 - (filtered_y[i] - filtered_y[i - lag]) ** 2 / lag)
        std_filter[i] = np.sqrt(var_filter[i])

    return dict(signals=labels,
                avgFilter=avg_filter,
                stdFilter=std_filter)

An implementation of the fast Fourier transform (FFT) in C#

Math.NET's Iridium library provides a fast, regularly updated collection of math-related functions, including the FFT. It's licensed under the LGPL so you are free to use it in commercial products.

How to apply a low-pass or high-pass filter to an array in Matlab?

Look at the filter function.

If you just need a 1-pole low-pass filter, it's

xfilt = filter(a, [1 a-1], x);

where a = T/τ, T = the time between samples, and τ (tau) is the filter time constant.

Here's the corresponding high-pass filter:

xfilt = filter([1-a a-1],[1 a-1], x);

If you need to design a filter, and have a license for the Signal Processing Toolbox, there's a bunch of functions, look at fvtool and fdatool.

How to normalize a signal to zero mean and unit variance?

To avoid division by zero!

function x = normalize(x, eps)
    % Normalize vector `x` (zero mean, unit variance)

    % default values
    if (~exist('eps', 'var'))
        eps = 1e-6;
    end

    mu = mean(x(:));

    sigma = std(x(:));
    if sigma < eps
        sigma = 1;
    end

    x = (x - mu) / sigma;
end

How to implement band-pass Butterworth filter with Scipy.signal.butter

The filter design method in accepted answer is correct, but it has a flaw. SciPy bandpass filters designed with b, a are unstable and may result in erroneous filters at higher filter orders.

Instead, use sos (second-order sections) output of filter design.

from scipy.signal import butter, sosfilt, sosfreqz

def butter_bandpass(lowcut, highcut, fs, order=5):
        nyq = 0.5 * fs
        low = lowcut / nyq
        high = highcut / nyq
        sos = butter(order, [low, high], analog=False, btype='band', output='sos')
        return sos

def butter_bandpass_filter(data, lowcut, highcut, fs, order=5):
        sos = butter_bandpass(lowcut, highcut, fs, order=order)
        y = sosfilt(sos, data)
        return y

Also, you can plot frequency response by changing

b, a = butter_bandpass(lowcut, highcut, fs, order=order)
w, h = freqz(b, a, worN=2000)

to

sos = butter_bandpass(lowcut, highcut, fs, order=order)
w, h = sosfreqz(sos, worN=2000)

Convert absolute path into relative path given a current directory using Bash

#!/bin/sh

# Return relative path from canonical absolute dir path $1 to canonical
# absolute dir path $2 ($1 and/or $2 may end with one or no "/").
# Does only need POSIX shell builtins (no external command)
relPath () {
    local common path up
    common=${1%/} path=${2%/}/
    while test "${path#"$common"/}" = "$path"; do
        common=${common%/*} up=../$up
    done
    path=$up${path#"$common"/}; path=${path%/}; printf %s "${path:-.}"
}

# Return relative path from dir $1 to dir $2 (Does not impose any
# restrictions on $1 and $2 but requires GNU Core Utility "readlink"
# HINT: busybox's "readlink" does not support option '-m', only '-f'
#       which requires that all but the last path component must exist)
relpath () { relPath "$(readlink -m "$1")" "$(readlink -m "$2")"; }

Above shell script was inspired by pini's (Thanks!). It triggers a bug in the syntax highlighting module of Stack Overflow (at least in my preview frame). So please ignore if highlighting is incorrect.

Some notes:

  • Removed errors and improved code without significantly increasing code length and complexity
  • Put functionality into functions for easiness of use
  • Kept functions POSIX compatible so that they (should) work with all POSIX shells (tested with dash, bash, and zsh in Ubuntu Linux 12.04)
  • Used local variables only to avoid clobbering global variables and polluting the global name space
  • Both directory paths DO NOT need to exist (requirement for my application)
  • Pathnames may contain spaces, special characters, control characters, backslashes, tabs, ', ", ?, *, [, ], etc.
  • Core function "relPath" uses POSIX shell builtins only but requires canonical absolute directory paths as parameters
  • Extended function "relpath" can handle arbitrary directory paths (also relative, non-canonical) but requires external GNU core utility "readlink"
  • Avoided builtin "echo" and used builtin "printf" instead for two reasons:
  • To avoid unnecessary conversions, pathnames are used as they are returned and expected by shell and OS utilities (e.g. cd, ln, ls, find, mkdir; unlike python's "os.path.relpath" which will interpret some backslash sequences)
  • Except for the mentioned backslash sequences the last line of function "relPath" outputs pathnames compatible to python:

    path=$up${path#"$common"/}; path=${path%/}; printf %s "${path:-.}"
    

    Last line can be replaced (and simplified) by line

    printf %s "$up${path#"$common"/}"
    

    I prefer the latter because

    1. Filenames can be directly appended to dir paths obtained by relPath, e.g.:

      ln -s "$(relpath "<fromDir>" "<toDir>")<file>" "<fromDir>"
      
    2. Symbolic links in the same dir created with this method do not have the ugly "./" prepended to the filename.

  • If you find an error please contact linuxball (at) gmail.com and I'll try to fix it.
  • Added regression test suite (also POSIX shell compatible)

Code listing for regression tests (simply append it to the shell script):

############################################################################
# If called with 2 arguments assume they are dir paths and print rel. path #
############################################################################

test "$#" = 2 && {
    printf '%s\n' "Rel. path from '$1' to '$2' is '$(relpath "$1" "$2")'."
    exit 0
}

#######################################################
# If NOT called with 2 arguments run regression tests #
#######################################################

format="\t%-19s %-22s %-27s %-8s %-8s %-8s\n"
printf \
"\n\n*** Testing own and python's function with canonical absolute dirs\n\n"
printf "$format\n" \
    "From Directory" "To Directory" "Rel. Path" "relPath" "relpath" "python"
IFS=
while read -r p; do
    eval set -- $p
    case $1 in '#'*|'') continue;; esac # Skip comments and empty lines
    # q stores quoting character, use " if ' is used in path name
    q="'"; case $1$2 in *"'"*) q='"';; esac
    rPOk=passed rP=$(relPath "$1" "$2"); test "$rP" = "$3" || rPOk=$rP
    rpOk=passed rp=$(relpath "$1" "$2"); test "$rp" = "$3" || rpOk=$rp
    RPOk=passed
    RP=$(python -c "import os.path; print os.path.relpath($q$2$q, $q$1$q)")
    test "$RP" = "$3" || RPOk=$RP
    printf \
    "$format" "$q$1$q" "$q$2$q" "$q$3$q" "$q$rPOk$q" "$q$rpOk$q" "$q$RPOk$q"
done <<-"EOF"
    # From directory    To directory           Expected relative path

    '/'                 '/'                    '.'
    '/usr'              '/'                    '..'
    '/usr/'             '/'                    '..'
    '/'                 '/usr'                 'usr'
    '/'                 '/usr/'                'usr'
    '/usr'              '/usr'                 '.'
    '/usr/'             '/usr'                 '.'
    '/usr'              '/usr/'                '.'
    '/usr/'             '/usr/'                '.'
    '/u'                '/usr'                 '../usr'
    '/usr'              '/u'                   '../u'
    "/u'/dir"           "/u'/dir"              "."
    "/u'"               "/u'/dir"              "dir"
    "/u'/dir"           "/u'"                  ".."
    "/"                 "/u'/dir"              "u'/dir"
    "/u'/dir"           "/"                    "../.."
    "/u'"               "/u'"                  "."
    "/"                 "/u'"                  "u'"
    "/u'"               "/"                    ".."
    '/u"/dir'           '/u"/dir'              '.'
    '/u"'               '/u"/dir'              'dir'
    '/u"/dir'           '/u"'                  '..'
    '/'                 '/u"/dir'              'u"/dir'
    '/u"/dir'           '/'                    '../..'
    '/u"'               '/u"'                  '.'
    '/'                 '/u"'                  'u"'
    '/u"'               '/'                    '..'
    '/u /dir'           '/u /dir'              '.'
    '/u '               '/u /dir'              'dir'
    '/u /dir'           '/u '                  '..'
    '/'                 '/u /dir'              'u /dir'
    '/u /dir'           '/'                    '../..'
    '/u '               '/u '                  '.'
    '/'                 '/u '                  'u '
    '/u '               '/'                    '..'
    '/u\n/dir'          '/u\n/dir'             '.'
    '/u\n'              '/u\n/dir'             'dir'
    '/u\n/dir'          '/u\n'                 '..'
    '/'                 '/u\n/dir'             'u\n/dir'
    '/u\n/dir'          '/'                    '../..'
    '/u\n'              '/u\n'                 '.'
    '/'                 '/u\n'                 'u\n'
    '/u\n'              '/'                    '..'

    '/    a   b/å/?*/!' '/    a   b/å/?/xäå/?' '../../?/xäå/?'
    '/'                 '/A'                   'A'
    '/A'                '/'                    '..'
    '/  & /  !/*/\\/E'  '/'                    '../../../../..'
    '/'                 '/  & /  !/*/\\/E'     '  & /  !/*/\\/E'
    '/  & /  !/*/\\/E'  '/  & /  !/?/\\/E/F'   '../../../?/\\/E/F'
    '/X/Y'              '/  & /  !/C/\\/E/F'   '../../  & /  !/C/\\/E/F'
    '/  & /  !/C'       '/A'                   '../../../A'
    '/A /  !/C'         '/A /B'                '../../B'
    '/Â/  !/C'          '/Â/  !/C'             '.'
    '/  & /B / C'       '/  & /B / C/D'        'D'
    '/  & /  !/C'       '/  & /  !/C/\\/Ê'     '\\/Ê'
    '/Å/  !/C'          '/Å/  !/D'             '../D'
    '/.A /*B/C'         '/.A /*B/\\/E'         '../\\/E'
    '/  & /  !/C'       '/  & /D'              '../../D'
    '/  & /  !/C'       '/  & /\\/E'           '../../\\/E'
    '/  & /  !/C'       '/\\/E/F'              '../../../\\/E/F'
    '/home/p1/p2'       '/home/p1/p3'          '../p3'
    '/home/p1/p2'       '/home/p4/p5'          '../../p4/p5'
    '/home/p1/p2'       '/work/p6/p7'          '../../../work/p6/p7'
    '/home/p1'          '/work/p1/p2/p3/p4'    '../../work/p1/p2/p3/p4'
    '/home'             '/work/p2/p3'          '../work/p2/p3'
    '/'                 '/work/p2/p3/p4'       'work/p2/p3/p4'
    '/home/p1/p2'       '/home/p1/p2/p3/p4'    'p3/p4'
    '/home/p1/p2'       '/home/p1/p2/p3'       'p3'
    '/home/p1/p2'       '/home/p1/p2'          '.'
    '/home/p1/p2'       '/home/p1'             '..'
    '/home/p1/p2'       '/home'                '../..'
    '/home/p1/p2'       '/'                    '../../..'
    '/home/p1/p2'       '/work'                '../../../work'
    '/home/p1/p2'       '/work/p1'             '../../../work/p1'
    '/home/p1/p2'       '/work/p1/p2'          '../../../work/p1/p2'
    '/home/p1/p2'       '/work/p1/p2/p3'       '../../../work/p1/p2/p3'
    '/home/p1/p2'       '/work/p1/p2/p3/p4'    '../../../work/p1/p2/p3/p4'

    '/-'                '/-'                   '.'
    '/?'                '/?'                   '.'
    '/??'               '/??'                  '.'
    '/???'              '/???'                 '.'
    '/?*'               '/?*'                  '.'
    '/*'                '/*'                   '.'
    '/*'                '/**'                  '../**'
    '/*'                '/***'                 '../***'
    '/*.*'              '/*.**'                '../*.**'
    '/*.???'            '/*.??'                '../*.??'
    '/[]'               '/[]'                  '.'
    '/[a-z]*'           '/[0-9]*'              '../[0-9]*'
EOF


format="\t%-19s %-22s %-27s %-8s %-8s\n"
printf "\n\n*** Testing own and python's function with arbitrary dirs\n\n"
printf "$format\n" \
    "From Directory" "To Directory" "Rel. Path" "relpath" "python"
IFS=
while read -r p; do
    eval set -- $p
    case $1 in '#'*|'') continue;; esac # Skip comments and empty lines
    # q stores quoting character, use " if ' is used in path name
    q="'"; case $1$2 in *"'"*) q='"';; esac
    rpOk=passed rp=$(relpath "$1" "$2"); test "$rp" = "$3" || rpOk=$rp
    RPOk=passed
    RP=$(python -c "import os.path; print os.path.relpath($q$2$q, $q$1$q)")
    test "$RP" = "$3" || RPOk=$RP
    printf "$format" "$q$1$q" "$q$2$q" "$q$3$q" "$q$rpOk$q" "$q$RPOk$q"
done <<-"EOF"
    # From directory    To directory           Expected relative path

    'usr/p1/..//./p4'   'p3/../p1/p6/.././/p2' '../../p1/p2'
    './home/../../work' '..//././../dir///'    '../../dir'

    'home/p1/p2'        'home/p1/p3'           '../p3'
    'home/p1/p2'        'home/p4/p5'           '../../p4/p5'
    'home/p1/p2'        'work/p6/p7'           '../../../work/p6/p7'
    'home/p1'           'work/p1/p2/p3/p4'     '../../work/p1/p2/p3/p4'
    'home'              'work/p2/p3'           '../work/p2/p3'
    '.'                 'work/p2/p3'           'work/p2/p3'
    'home/p1/p2'        'home/p1/p2/p3/p4'     'p3/p4'
    'home/p1/p2'        'home/p1/p2/p3'        'p3'
    'home/p1/p2'        'home/p1/p2'           '.'
    'home/p1/p2'        'home/p1'              '..'
    'home/p1/p2'        'home'                 '../..'
    'home/p1/p2'        '.'                    '../../..'
    'home/p1/p2'        'work'                 '../../../work'
    'home/p1/p2'        'work/p1'              '../../../work/p1'
    'home/p1/p2'        'work/p1/p2'           '../../../work/p1/p2'
    'home/p1/p2'        'work/p1/p2/p3'        '../../../work/p1/p2/p3'
    'home/p1/p2'        'work/p1/p2/p3/p4'     '../../../work/p1/p2/p3/p4'
EOF

RuntimeWarning: DateTimeField received a naive datetime

If you are trying to transform a naive datetime into a datetime with timezone in django, here is my solution:

>>> import datetime
>>> from django.utils import timezone
>>> t1 = datetime.datetime.strptime("2019-07-16 22:24:00", "%Y-%m-%d %H:%M:%S")
>>> t1
    datetime.datetime(2019, 7, 16, 22, 24)
>>> current_tz = timezone.get_current_timezone()
>>> t2 = current_tz.localize(t1)
>>> t2
    datetime.datetime(2019, 7, 16, 22, 24, tzinfo=<DstTzInfo 'Asia/Shanghai' CST+8:00:00 STD>)
>>>

t1 is a naive datetime and t2 is a datetime with timezone in django's settings.

Add disabled attribute to input element using Javascript

You can get the DOM element, and set the disabled property directly.

$(".shownextrow").click(function() { 
  $(this).closest("tr").next().show()
          .find('.longboxsmall').hide()[0].disabled = 'disabled';
});

or if there's more than one, you can use each() to set all of them:

$(".shownextrow").click(function() { 
  $(this).closest("tr").next().show()
          .find('.longboxsmall').each(function() {
               this.style.display = 'none';
               this.disabled = 'disabled';
          });
});

Return a value of '1' a referenced cell is empty

If you've got a cell filled with spaces or blanks, you can use:

=Len(Trim(A2)) = 0

if the cell you were testing was A2

How to show changed file name only with git log?

Thanks for your answers, @mvp, @xero, I get what I want base on both of your answers.

git log --name-only 

or

git log --name-only --oneline

for short.

keycode 13 is for which key

The Enter key should have the keycode 13. Is it not working?

Removing duplicates from a SQL query (not just "use distinct")

Your question is kind of confusing; do you want to show only one row per user, or do you want to show a row per picture but suppress repeating values in the U.NAME field? I think you want the second; if not there are plenty of answers for the first.

Whether to display repeating values is display logic, which SQL wasn't really designed for. You can use a cursor in a loop to process the results row-by-row, but you will lose a lot of performance. If you have a "smart" frontend language like a .NET language or Java, whatever construction you put this data into can be cheaply manipulated to suppress repeating values before finally displaying it in the UI.

If you're using Microsoft SQL Server, and the transformation HAS to be done at the data layer, you may consider using a CTE (Computed Table Expression) to hold the initial query, then select values from each row of the CTE based on whether the columns in the previous row hold the same data. It'll be more performant than the cursor, but it'll be kinda messy either way. Observe:

USING CTE (Row, Name, PicID)
AS
(
    SELECT ROW_NUMBER() OVER (ORDER BY U.NAME, P.PIC_ID),
       U.NAME, P.PIC_ID
    FROM USERS U
        INNER JOIN POSTINGS P1
            ON U.EMAIL_ID = P1.EMAIL_ID
        INNER JOIN PICTURES P
            ON P1.PIC_ID = P.PIC_ID
    WHERE P.CAPTION LIKE '%car%'
    ORDER BY U.NAME, P.PIC_ID 
)
SELECT
    CASE WHEN current.Name == previous.Name THEN '' ELSE current.Name END,
    current.PicID
FROM CTE current
LEFT OUTER JOIN CTE previous
   ON current.Row = previous.Row + 1
ORDER BY current.Row

The above sample is TSQL-specific; it is not guaranteed to work in any other DBPL like PL/SQL, but I think most of the enterprise-level SQL engines have something similar.

Android Drawing Separator/Divider Line in Layout?

use this code. It will help

<LinearLayout
    android:layout_width="0dip"
    android:layout_height="match_parent"
    android:layout_gravity="center"
    android:layout_weight="1"
    android:divider="?android:dividerHorizontal"
    android:gravity="center"
    android:orientation="vertical"
    android:showDividers="middle" >

How to reset Android Studio

I only know how to do this on Windows (but it should be similar on any OS, you will just need to find the correct location yourself - google search would help with that).

On Windows:

Go to your User Folder - on Windows 7/8 this would be:

[SYSDRIVE]:\Users\[your username] (ex. C:\Users\JohnDoe\)

In this folder there should be a folder called .AndroidStudioBeta or .AndroidStudio (notice the period at the start - so on some OSes it would be hidden).

Update

Now, Android Studio settings is at:

C:\Users\<Your User>\AppData\Roaming\Google\.AndroidStudio4.X

Delete this folder (or better yet, move it to a backup location - so you can return it if something goes wrong).

This should reset your Android Studio settings to default.

How can I convert a stack trace to a string?

I wonder why no one mentioned ExceptionUtils.getStackFrames(exception)

For me it's the most convenient way to dump stacktrace with all its causes to the end:

String.join("\n", ExceptionUtils.getStackFrames(exception));

How do I implement charts in Bootstrap?

Github did this using the HTML canvas element.

This specification defines the 2D Context for the HTML canvas element. The 2D Context provides objects, methods, and properties to draw and manipulate graphics on a canvas drawing surface.

If you use a browser inspector, you see inside every list element a div with a canvas element.

<div class="participation-graph">
   <canvas class="bars" data-color-all="#F5F5F5" data-color-owner="#F5F5F5" data-source="/mxcl/homebrew/graphs/owner_participation" height="80" width="640"></canvas>
</div>

With CSS (z-index, position...) you can put that canvas in the background of a li element or table, in your case.

Do a search about jquery pluggins that fit your requirement.

Hope this pointers help you to achieve that.

How do I open the "front camera" on the Android platform?

public void surfaceCreated(SurfaceHolder holder) {
    try {
        mCamera = Camera.open();
        mCamera.setDisplayOrientation(90);
        mCamera.setPreviewDisplay(holder);

        Camera.Parameters p = mCamera.getParameters();
        p.set("camera-id",2);
        mCamera.setParameters(p);   
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

Count number of days between two dates

With the Date (and DateTime) classes you can do (end_date - start_date).to_i to get the number of days difference.

Passing an array of data as an input parameter to an Oracle procedure

If the types of the parameters are all the same (varchar2 for example), you can have a package like this which will do the following:

CREATE OR REPLACE PACKAGE testuser.test_pkg IS

   TYPE assoc_array_varchar2_t IS TABLE OF VARCHAR2(4000) INDEX BY BINARY_INTEGER;

   PROCEDURE your_proc(p_parm IN assoc_array_varchar2_t);

END test_pkg;

CREATE OR REPLACE PACKAGE BODY testuser.test_pkg IS

   PROCEDURE your_proc(p_parm IN assoc_array_varchar2_t) AS
   BEGIN
      FOR i IN p_parm.first .. p_parm.last
      LOOP
         dbms_output.put_line(p_parm(i));
      END LOOP;

   END;

END test_pkg;

Then, to call it you'd need to set up the array and pass it:

DECLARE
  l_array testuser.test_pkg.assoc_array_varchar2_t;
BEGIN
  l_array(0) := 'hello';
  l_array(1) := 'there';  

  testuser.test_pkg.your_proc(l_array);
END;
/

WPF Timer Like C# Timer

you can also use

using System.Timers;
using System.Threading;

Sass and combined child selector

Without the combined child selector you would probably do something similar to this:

foo {
  bar {
    baz {
      color: red;
    }
  }
}

If you want to reproduce the same syntax with >, you could to this:

foo {
  > bar {
    > baz {
      color: red;
    }
  }
}

This compiles to this:

foo > bar > baz {
  color: red;
}

Or in sass:

foo
  > bar
    > baz
      color: red

How to get the data-id attribute?

Accessing data attribute with its own id is bit easy for me.

$("#Id").data("attribute");

_x000D_
_x000D_
function myFunction(){_x000D_
  alert($("#button1").data("sample-id"));_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<button type="button" id="button1" data-sample-id="gotcha!" onclick="myFunction()"> Clickhere </button>
_x000D_
_x000D_
_x000D_

Best way to concatenate List of String objects?

If you are developing for Android, there is TextUtils.join provided by the SDK.

How to convert a double to long without casting?

Simply put, casting is more efficient than creating a Double object.

What is the best way to remove the first element from an array?

You can't do it at all, let alone quickly. Arrays in Java are fixed size. Two things you could do are:

  1. Shift every element up one, then set the last element to null.
  2. Create a new array, then copy it.

You can use System.arraycopy for either of these. Both of these are O(n), since they copy all but 1 element.

If you will be removing the first element often, consider using LinkedList instead. You can use LinkedList.remove, which is from the Queue interface, for convenience. With LinkedList, removing the first element is O(1). In fact, removing any element is O(1) once you have a ListIterator to that position. However, accessing an arbitrary element by index is O(n).

List all the files and folders in a Directory with PHP recursive function

@A-312's solution may cause memory problems as it may create a huge array if /xampp/htdocs/WORK contains a lot of files and folders.

If you have PHP 7 then you can use Generators and optimize PHP's memory like this:

function getDirContents($dir) {
    $files = scandir($dir);
    foreach($files as $key => $value){

        $path = realpath($dir.DIRECTORY_SEPARATOR.$value);
        if(!is_dir($path)) {
            yield $path;

        } else if($value != "." && $value != "..") {
           yield from getDirContents($path);
           yield $path;
        }
    }
}

foreach(getDirContents('/xampp/htdocs/WORK') as $value) {
    echo $value."\n";
}

yield from

Best way to encode text data for XML

In .net 3.5+

new XText("I <want> to & encode this for XML").ToString();

Gives you:

I &lt;want&gt; to &amp; encode this for XML

Turns out that this method doesn't encode some things that it should (like quotes).

SecurityElement.Escape (workmad3's answer) seems to do a better job with this and it's included in earlier versions of .net.

If you don't mind 3rd party code and want to ensure no illegal characters make it into your XML, I would recommend Michael Kropat's answer.

How do I display a text file content in CMD?

I don't think there is a built-in function for that

xxxx.txt > con

This opens the files in the default text editor in windows...

type xxxx.txt

This displays the file in the current window. Maybe this has params you can use...

There is a similar question here: CMD.EXE batch script to display last 10 lines from a txt file So there is a "more" command to display a file from the given line, or you can use the GNU Utilities for Win32 what bryanph suggested in his link.

Why is AJAX returning HTTP status code 0?

For me, the problem was caused by the hosting company (Godaddy) treating POST operations which had substantial response data (anything more than tens of kilobytes) as some sort of security threat. If more than 6 of these occurred in one minute, the host refused to execute the PHP code that responded to the POST request during the next minute. I'm not entirely sure what the host did instead, but I did see, with tcpdump, a TCP reset packet coming as the response to a POST request from the browser. This caused the http status code returned in a jqXHR object to be 0.

Changing the operations from POST to GET fixed the problem. It's not clear why Godaddy impose this limit, but changing the code was easier than changing the host.

How to commit my current changes to a different branch in Git

The other answers suggesting checking out the other branch, then committing to it, only work if the checkout is possible given the local modifications. If not, you're in the most common use case for git stash:

git stash
git checkout other-branch
git stash pop

The first stash hides away your changes (basically making a temporary commit), and the subsequent stash pop re-applies them. This lets Git use its merge capabilities.

If, when you try to pop the stash, you run into merge conflicts... the next steps depend on what those conflicts are. If all the stashed changes indeed belong on that other branch, you're simply going to have to sort through them - it's a consequence of having made your changes on the wrong branch.

On the other hand, if you've really messed up, and your work tree has a mix of changes for the two branches, and the conflicts are just in the ones you want to commit back on the original branch, you can save some work. As usual, there are a lot of ways to do this. Here's one, starting from after you pop and see the conflicts:

# Unstage everything (warning: this leaves files with conflicts in your tree)
git reset

# Add the things you *do* want to commit here
git add -p     # or maybe git add -i
git commit

# The stash still exists; pop only throws it away if it applied cleanly
git checkout original-branch
git stash pop

# Add the changes meant for this branch
git add -p
git commit

# And throw away the rest
git reset --hard

Alternatively, if you realize ahead of the time that this is going to happen, simply commit the things that belong on the current branch. You can always come back and amend that commit:

git add -p
git commit
git stash
git checkout other-branch
git stash pop

And of course, remember that this all took a bit of work, and avoid it next time, perhaps by putting your current branch name in your prompt by adding $(__git_ps1) to your PS1 environment variable in your bashrc file. (See for example the Git in Bash documentation.)

What does the ">" (greater-than sign) CSS selector mean?

> (greater-than sign) is a CSS Combinator.

A combinator is something that explains the relationship between the selectors.

A CSS selector can contain more than one simple selector. Between the simple selectors, we can include a combinator.

There are four different combinators in CSS3:

  1. descendant selector (space)
  2. child selector (>)
  3. adjacent sibling selector (+)
  4. general sibling selector (~)

Note: < is not valid in CSS selectors.

enter image description here

For example:

<!DOCTYPE html>
<html>
<head>
<style>
div > p {
    background-color: yellow;
}
</style>
</head>
<body>

<div>
  <p>Paragraph 1 in the div.</p>
  <p>Paragraph 2 in the div.</p>
  <span><p>Paragraph 3 in the div.</p></span> <!-- not Child but Descendant -->
</div>

<p>Paragraph 4. Not in a div.</p>
<p>Paragraph 5. Not in a div.</p>

</body>
</html>

Output:

enter image description here

More information about CSS Combinators

Does Arduino use C or C++?

Arduino sketches are written in C++.

Here is a typical construct you'll encounter:

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
...
lcd.begin(16, 2);
lcd.print("Hello, World!");

That's C++, not C.

Hence do yourself a favor and learn C++. There are plenty of books and online resources available.

Why my $.ajax showing "preflight is invalid redirect error"?

I received the same error when I tried to call https web service as http webservice.

e.g when I call url 'http://api.example.com/users/get'
which should be 'https://api.example.com/users/get'

This error is produced because of redirection status 302 when you try to call http instead of https.

Command line .cmd/.bat script, how to get directory of running script

This is equivalent to the path of the script:

%~dp0

This uses the batch parameter extension syntax. Parameter 0 is always the script itself.

If your script is stored at C:\example\script.bat, then %~dp0 evaluates to C:\example\.

ss64.com has more information about the parameter extension syntax. Here is the relevant excerpt:

You can get the value of any parameter using a % followed by it's numerical position on the command line.

[...]

When a parameter is used to supply a filename then the following extended syntax can be applied:

[...]

%~d1 Expand %1 to a Drive letter only - C:

[...]

%~p1 Expand %1 to a Path only e.g. \utils\ this includes a trailing \ which may be interpreted as an escape character by some commands.

[...]

The modifiers above can be combined:

%~dp1 Expand %1 to a drive letter and path only

[...]

You can get the pathname of the batch script itself with %0, parameter extensions can be applied to this so %~dp0 will return the Drive and Path to the batch script e.g. W:\scripts\

How to list all the roles existing in Oracle database?

Got the answer :

SELECT * FROM DBA_ROLES;

Drag and drop menuitems

jQuery UI draggable and droppable are the two plugins I would use to achieve this effect. As for the insertion marker, I would investigate modifying the div (or container) element that was about to have content dropped into it. It should be possible to modify the border in some way or add a JavaScript/jQuery listener that listens for the hover (element about to be dropped) event and modifies the border or adds an image of the insertion marker in the right place.

How to create a oracle sql script spool file

With spool:

  set heading off
  set arraysize 1
  set newpage 0
  set pages 0
  set feedback off
  set echo off
  set verify off

variable cd varchar2(10);
variable d number;

 declare
 ab varchar2(10) := 'Raj';
 a number := 10;
 c number;
 begin
 c := a+10;
 select ab,c into :cd,:d from dual;
 end;

 SPOOL 
 select :cd,:d from dual;
 SPOOL OFF
 EXIT;

The term 'Get-ADUser' is not recognized as the name of a cmdlet

If the ActiveDirectory module is present add

import-module activedirectory

before your code.

To check if exist try:

get-module -listavailable

ActiveDirectory module is default present in windows server 2008 R2, install it in this way:

Import-Module ServerManager
Add-WindowsFeature RSAT-AD-PowerShell

For have it to work you need at least one DC in the domain as windows 2008 R2 and have Active Directory Web Services (ADWS) installed on it.

For Windows Server 2008 read here how to install it

How to properly import a selfsigned certificate into Java keystore that is available to all Java applications by default?

install certificate in java linux

/opt/jdk(version)/bin/keytool -import -alias aliasname -file certificate.cer -keystore cacerts -storepass password

XML Error: Extra content at the end of the document

You need a root node

<?xml version="1.0" encoding="ISO-8859-1"?>    
<documents>
    <document>
        <name>Sample Document</name>
        <type>document</type>
        <url>http://nsc-component.webs.com/Office/Editor/new-doc.html?docname=New+Document&amp;titletype=Title&amp;fontsize=9&amp;fontface=Arial&amp;spacing=1.0&amp;text=&amp;wordcount3=0</url>
    </document>

    <document>
        <name>Sample</name>
        <type>document</type>
        <url>http://nsc-component.webs.com/Office/Editor/new-doc.html?docname=New+Document&amp;titletype=Title&amp;fontsize=9&amp;fontface=Arial&amp;spacing=1.0&amp;text=&amp;</url>
    </document>
</documents>

System.Drawing.Image to stream C#

Use a memory stream

using(MemoryStream ms = new MemoryStream())
{
    image.Save(ms, ...);
    return ms.ToArray();
}

Tick symbol in HTML/XHTML

Would √ (square root symbol, &#8730;) suffice?

Alternatively, ensure you're setting the Content-Type: header before sending data to the browser. Merely specifying the <meta> content-type tag may not be enough to encourage browsers to use the correct character set.

How to prevent favicon.ico requests?

Sometimes this error comes, when HTML has some commented code and browser is trying to look for something. Like in my case I had commented code for a web form in flask and I was getting this.

After spending 2 hours I fixed it in the following ways:

1) I created a new python environment and then it threw an error on the commented HTML line, before this I was only thrown error 'GET /favicon.ico HTTP/1.1" 404'

2) Sometimes, when I had a duplicate code, like python file existing with the same name, then also I saw this error, try removing those too

Concatenate text files with Windows command line, dropping leading lines

The help for copy explains that wildcards can be used to concatenate multiple files into one.

For example, to copy all .txt files in the current folder that start with "abc" into a single file named xyz.txt:

copy abc*.txt xyz.txt

Convert RGB to Black & White in OpenCV

I do something similar in one of my blog postings. A simple C++ example is shown.

The aim was to use the open source cvBlobsLib library for the detection of spot samples printed to microarray slides, but the images have to be converted from colour -> grayscale -> black + white as you mentioned, in order to achieve this.

What is the best way to determine a session variable is null or empty in C#?

This method also does not assume that the object in the Session variable is a string

if((Session["MySessionVariable"] ?? "").ToString() != "")
    //More code for the Code God

So basically replaces the null variable with an empty string before converting it to a string since ToString is part of the Object class

How do I add button on each row in datatable?

my recipe:

datatable declaration:

defaultContent: "<button type='button'....

events:

$('#usersDataTable tbody').on( 'click', '.delete-user-btn', function () { var user_data = table.row( $(this).parents('tr') ).data(); }

Example on ToggleButton

I think what are attempting is semantically same as a radio button when 1 is when one of the options is selected and 0 is the other option.

I suggest using the radio button provided by Android by default.

Here is how to use it- http://www.mkyong.com/android/android-radio-buttons-example/

and the android documentation is here-

http://developer.android.com/guide/topics/ui/controls/radiobutton.html

Thanks.

How to check if Receiver is registered in Android?

You have several options

  1. You can put a flag into your class or activity. Put a boolean variable into your class and look at this flag to know if you have the Receiver registered.

  2. Create a class that extends the Receiver and there you can use:

    1. Singleton pattern for only have one instance of this class in your project.

    2. Implement the methods for know if the Receiver is register.

SQL update fields of one table from fields of another one

This is a great help. The code

UPDATE tbl_b b
SET   (  column1,   column2,   column3)
    = (a.column1, a.column2, a.column3)
FROM   tbl_a a
WHERE  b.id = 1
AND    a.id = b.id;

works perfectly.

noted that you need a bracket "" in

From "tbl_a" a

to make it work.

How to join (merge) data frames (inner, outer, left, right)

There are some good examples of doing this over at the R Wiki. I'll steal a couple here:

Merge Method

Since your keys are named the same the short way to do an inner join is merge():

merge(df1,df2)

a full inner join (all records from both tables) can be created with the "all" keyword:

merge(df1,df2, all=TRUE)

a left outer join of df1 and df2:

merge(df1,df2, all.x=TRUE)

a right outer join of df1 and df2:

merge(df1,df2, all.y=TRUE)

you can flip 'em, slap 'em and rub 'em down to get the other two outer joins you asked about :)

Subscript Method

A left outer join with df1 on the left using a subscript method would be:

df1[,"State"]<-df2[df1[ ,"Product"], "State"]

The other combination of outer joins can be created by mungling the left outer join subscript example. (yeah, I know that's the equivalent of saying "I'll leave it as an exercise for the reader...")

Is bool a native C type?

No, there is no bool in ISO C90.

Here's a list of keywords in standard C (not C99):

  • auto
  • break
  • case
  • char
  • const
  • continue
  • default
  • do
  • double
  • else
  • enum
  • extern
  • float
  • for
  • goto
  • if
  • int
  • long
  • register
  • return
  • short
  • signed
  • static
  • struct
  • switch
  • typedef
  • union
  • unsigned
  • void
  • volatile
  • while

Here's an article discussing some other differences with C as used in the kernel and the standard: http://www.ibm.com/developerworks/linux/library/l-gcc-hacks/index.html

Finding absolute value of a number without using Math.abs()

Although this shouldn't be a bottle neck as branching issues on modern processors isn't normally a problem, but in the case of integers you could go for a branch-less solution as outlined here: http://graphics.stanford.edu/~seander/bithacks.html#IntegerAbs.

(x + (x >> 31)) ^ (x >> 31);

This does fail in the obvious case of Integer.MIN_VALUE however, so this is a use at your own risk solution.

The ScriptManager must appear before any controls that need it

It simply wants the ASP control on your ASPX page. I usually place mine right under the tag, or inside first Content area in the master's body (if your using a master page)

<body>
    <form id="form1" runat="server">
        <asp:ScriptManager ID="scriptManager" runat="server"></asp:ScriptManager>
        <div>
            [Content]
        </div>
    </form>
</body>

Python: SyntaxError: keyword can't be an expression

I guess many of us who came to this page have a problem with Scikit Learn, one way to solve it is to create a dictionary with parameters and pass it to the model:

params = {'C': 1e9, 'gamma': 1e-07}
cls = SVC(**params)    

How to create a blank/empty column with SELECT query in oracle?

I guess you will get ORA-01741: illegal zero-length identifier if you use the following

SELECT "" AS Contact  FROM Customers;

And if you use the following 2 statements, you will be getting the same null value populated in the column.

SELECT '' AS Contact FROM Customers; OR SELECT null AS Contact FROM Customers;

How can I parse a JSON file with PHP?

Try This

    $json_data = '{
    "John": {
        "status":"Wait"
    },
    "Jennifer": {
        "status":"Active"
    },
    "James": {
        "status":"Active",
        "age":56,
        "count":10,
        "progress":0.0029857,
        "bad":0
      }
     }';

    $decode_data = json_decode($json_data);
    foreach($decode_data as $key=>$value){

            print_r($value);
    }

Set transparent background using ImageMagick and commandline prompt

If you want to control the level of transparency you can use rgba. where a is the alpha. 0 for transparent and 1 for opaque. Make sure that final output file must have .png extension for transparency.

convert 
  test.png 
    -channel rgba 
    -matte 
    -fuzz 40% 
    -fill "rgba(255,255,255,0.5)" 
    -opaque "rgb(255,255,255)" 
       semi_transparent.png

ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)

I ran this on MacOS /Applications/Python\ 3.6/Install\ Certificates.command

Can't resolve module (not found) in React.js

The way we usually use import is based on relative path.

. and .. are similar to how we use to navigate in terminal like cd .. to go out of directory and mv ~/file . to move a file to current directory.

my-app/
  node_modules/
  package.json
  src/
    containers/card.js
    components/header.js
    App.js
    index.js

In your case, App.js is in src/ directory while header.js is in src/components. To import you would do import Header from './components/header'. This roughly translate to in my current directory, find the components folder that contain a header file.

Now, if from header.js, you need to import something from card, you would do this. import Card from '../containers/card'. This translate to, move out of my current directory, look for a folder name containers that have a card file.

As for import React, { Component } from 'react', this does not start with a ./ or ../ or / therefore node will start looking for the module in the node_modules in a specific order till react is found. For a more detail understanding, it can be read here.

What is "export default" in JavaScript?

In my opinion, the important thing about the default export is that it can be imported with any name!

If there is a file, foo.js, which exports default:

_x000D_
_x000D_
export default function foo(){}
_x000D_
_x000D_
_x000D_

it can be imported in bar.js using:

_x000D_
_x000D_
import bar from 'foo'
import Bar from 'foo' // Or ANY other name you wish to assign to this import
_x000D_
_x000D_
_x000D_

How to generate an openSSL key using a passphrase from the command line?

genrsa has been replaced by genpkey & when run manually in a terminal it will prompt for a password:

openssl genpkey -aes-256-cbc -algorithm RSA -out /etc/ssl/private/key.pem -pkeyopt rsa_keygen_bits:4096

However when run from a script the command will not ask for a password so to avoid the password being viewable as a process use a function in a shell script:

get_passwd() {
    local passwd=
    echo -ne "Enter passwd for private key: ? "; read -s passwd
    openssl genpkey -aes-256-cbc -pass pass:$passwd -algorithm RSA -out $PRIV_KEY -pkeyopt rsa_keygen_bits:$PRIV_KEYSIZE
}

How to access POST form fields

Update

As of Express version 4.16+, their own body-parser implementation is now included in the default Express package so there is no need for you to download another dependency.

You may have added a line to your code that looks like the following:

app.use(bodyparser.json()); //utilizes the body-parser package

If you are using Express 4.16+ you can now replace that line with:

app.use(express.json()); //Used to parse JSON bodies

This should not introduce any breaking changes into your applications since the code in express.json() is based on bodyparser.json().

If you also have the following code in your environment:

app.use(bodyParser.urlencoded({extended: true}));

You can replace that with:

app.use(express.urlencoded()); //Parse URL-encoded bodies

A final note of caution: There are still some very specific cases where body-parser might still be necessary but for the most part Express’ implementation of body-parser is all you will need for the majority of use cases.

(See the docs at expressjs/bodyparser for more details).

How do I hide anchor text without hiding the anchor?

Just need to add font-size: 0; to your element that contains text. This works well.

How to catch a click event on a button?

Change your onCreate to

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

for me this update worked

How to add a second x-axis in matplotlib

I'm forced to post this as an answer instead of a comment due to low reputation. I had a similar problem to Matteo. The difference being that I had no map from my first x-axis to my second x-axis, only the x-values themselves. So I wanted to set the data on my second x-axis directly, not the ticks, however, there is no axes.set_xdata. I was able to use Dhara's answer to do this with a modification:

ax2.lines = []

instead of using:

ax2.cla()

When in use also cleared my plot from ax1.

How do I get ASP.NET Web API to return JSON instead of XML using Chrome?

I'm astonished to see so many replies requiring coding to change a single use case (GET) in one API instead of using a proper tool what has to be installed once and can be used for any API (own or 3rd party) and all use cases.

So the good answer is:

  1. If you only want to request json or other content type install Requestly or a similar tool and modify the Accept header.
  2. If you want to use POST too and have nicely formatted json, xml, etc. use a proper API testing extension like Postman or ARC.

How to configure custom PYTHONPATH with VM and PyCharm?

For PyCharm 5 (or 2016.1), you can:

  1. select Preferences > Project Interpreter
  2. to the right of interpreter selector there is a "..." button, click it
  3. select "more..."
  4. pop up a new "Project Interpreters" window
  5. select the rightest button (named "show paths for the selected interpreter")
  6. pop up a "Interpreter Paths" window
  7. click the "+" buttom > select your desired PYTHONPATH directory (the folder which contains python modules) and click OK
  8. Done! Enjoy it!

enter image description here

enter image description here

enter image description here enter image description here

How to update /etc/hosts file in Docker image during "docker build"

If this is useful for anyone, the HOSTALIASES env variable worked for me:

echo "fakehost realhost" > /etc/host.aliases
export HOSTALIASES=/etc/host.aliases

How to create enum like type in TypeScript?

As of TypeScript 0.9 (currently an alpha release) you can use the enum definition like this:

enum TShirtSize {
  Small,
  Medium,
  Large
}

var mySize = TShirtSize.Large;

By default, these enumerations will be assigned 0, 1 and 2 respectively. If you want to explicitly set these numbers, you can do so as part of the enum declaration.

Listing 6.2 Enumerations with explicit members

enum TShirtSize {
  Small = 3,
  Medium = 5,
  Large = 8
}

var mySize = TShirtSize.Large;

Both of these examples lifted directly out of TypeScript for JavaScript Programmers.

Note that this is different to the 0.8 specification. The 0.8 specification looked like this - but it was marked as experimental and likely to change, so you'll have to update any old code:

Disclaimer - this 0.8 example would be broken in newer versions of the TypeScript compiler.

enum TShirtSize {
  Small: 3,
  Medium: 5,
  Large: 8
}

var mySize = TShirtSize.Large;

How to set TLS version on apache HttpClient

Using -Dhttps.protocols=TLSv1.2 JVM argument didn't work for me. What worked is the following code

RequestConfig.Builder requestBuilder = RequestConfig.custom();
//other configuration, for example
requestBuilder = requestBuilder.setConnectTimeout(1000);

SSLContext sslContext = SSLContextBuilder.create().useProtocol("TLSv1.2").build();

HttpClientBuilder builder = HttpClientBuilder.create();
builder.setDefaultRequestConfig(requestBuilder.build());
builder.setProxy(new HttpHost("your.proxy.com", 3333)); //if you have proxy
builder.setSSLContext(sslContext);

HttpClient client = builder.build();

Use the following JVM argument to verify

-Djavax.net.debug=all

How can I throw a general exception in Java?

Java has a large number of built-in exceptions for different scenarios.

In this case, you should throw an IllegalArgumentException, since the problem is that the caller passed a bad parameter.

How to remove square brackets from list in Python?

if you have numbers in list, you can use map to apply str to each element:

print ', '.join(map(str, LIST))

^ map is C code so it's faster than str(i) for i in LIST

How to set HTML Auto Indent format on Sublime Text 3?

This is an adaptation of the above answer, but should be more complete.

To be clear, this is to re-introduce previous auto-indent features when HTML files are open in Sublime Text. So when you finish a tag, it automatically indents for the next element.

Windows Users

Go to C:\Program Files\Sublime Text 3\Packages extract HTML.sublime-package as if it is a zip file to a directory.

Open Miscellaneous.tmPreferences and copy this contents into the file

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>name</key>
    <string>Miscellaneous</string>
    <key>scope</key>
    <string>text.html</string>
    <key>settings</key>
    <dict>
        <key>decreaseIndentPattern</key>
            <string>(?x)
            ^\s*
            (&lt;/(?!html)
              [A-Za-z0-9]+\b[^&gt;]*&gt;
            |--&gt;
            |&lt;\?(php)?\s+(else(if)?|end(if|for(each)?|while))
            |\}
            )</string>
        <key>batchDecreaseIndentPattern</key>
            <string>(?x)
            ^\s*
            (&lt;/(?!html)
              [A-Za-z0-9]+\b[^&gt;]*&gt;
            |--&gt;
            |&lt;\?(php)?\s+(else(if)?|end(if|for(each)?|while))
            |\}
            )</string>
        <key>increaseIndentPattern</key>
            <string>(?x)
            ^\s*
            &lt;(?!\?|area|base|br|col|frame|hr|html|img|input|link|meta|param|[^&gt;]*/&gt;)
              ([A-Za-z0-9]+)(?=\s|&gt;)\b[^&gt;]*&gt;(?!.*&lt;/\1&gt;)
            |&lt;!--(?!.*--&gt;)
            |&lt;\?php.+?\b(if|else(?:if)?|for(?:each)?|while)\b.*:(?!.*end\1)
            |\{[^}"']*$
            </string>
        <key>batchIncreaseIndentPattern</key>
            <string>(?x)
            ^\s*
            &lt;(?!\?|area|base|br|col|frame|hr|html|img|input|link|meta|param|[^&gt;]*/&gt;)
              ([A-Za-z0-9]+)(?=\s|&gt;)\b[^&gt;]*&gt;(?!.*&lt;/\1&gt;)
            |&lt;!--(?!.*--&gt;)
            |&lt;\?php.+?\b(if|else(?:if)?|for(?:each)?|while)\b.*:(?!.*end\1)
            |\{[^}"']*$
            </string>
        <key>bracketIndentNextLinePattern</key>
         <string>&lt;!DOCTYPE(?!.*&gt;)</string>
    </dict>
</dict>
</plist>

Then re-zip the file as HTML.sublime-package and replace the existing HTML.sublime-package with the one you just created.

Close and open Sublime Text 3 and you're done!

Remove all elements contained in another array

Now in one-liner flavor:

_x000D_
_x000D_
console.log(['a', 'b', 'c', 'd', 'e', 'f', 'g'].filter(x => !~['b', 'c', 'g'].indexOf(x)))
_x000D_
_x000D_
_x000D_

Might not work on old browsers.

How to get a list of properties with a given attribute?

var props = t.GetProperties().Where(
                prop => Attribute.IsDefined(prop, typeof(MyAttribute)));

This avoids having to materialize any attribute instances (i.e. it is cheaper than GetCustomAttribute[s]().

How to create an HTML button that acts like a link?

You could also set the buttons type-property to "button" (it makes it not submit the form), and then nest it inside a link (makes it redirect the user).

This way you could have another button in the same form that does submit the form, in case that's needed. I also think this is preferable in most cases over setting the form method and action to be a link (unless it's a search-form I guess...)

Example:

_x000D_
_x000D_
<form method="POST" action="/SomePath">_x000D_
  <input type="text" name="somefield" />_x000D_
  <a href="www.target.com"><button type="button">Go to Target!</button></a>_x000D_
  <button type="submit">submit form</button>_x000D_
</form>
_x000D_
_x000D_
_x000D_

This way the first button redirects the user, while the second submits the form.

Be careful to make sure the button doesn't trigger any action, as that will result in a conflict. Also as Arius pointed out, you should be aware that, for the above reason, this isn't strictly speaking considered valid HTML, according to the standard. It does however work as expected in Firefox and Chrome, but I haven't yet tested it for Internet Explorer.

Run all SQL files in a directory

@echo off
cd C:\Program Files (x86)\MySQL\MySQL Workbench 6.0 CE

for %%a in (D:\abc\*.sql) do (
echo %%a
mysql --host=ip --port=3306 --user=uid--password=ped < %%a
)

Step1: above lines copy into note pad save it as bat.

step2: In d drive abc folder in all Sql files in queries executed in sql server.

step3: Give your ip, user id and password.

Neatest way to remove linebreaks in Perl

Whenever I go through input and want to remove or replace characters I run it through little subroutines like this one.

sub clean {

    my $text = shift;

    $text =~ s/\n//g;
    $text =~ s/\r//g;

    return $text;
}

It may not be fancy but this method has been working flawless for me for years.

Could not create SSL/TLS secure channel, despite setting ServerCertificateValidationCallback

I came across this thread because I also had the error Could not create SSL/TLS secure channel. In my case, I was attempting to access a Siebel configuration REST API from PowerShell using Invoke-RestMethod, and none of the suggestions above helped.

Eventually I stumbled across the cause of my problem: the server I was contacting required client certificate authentication.

To make the calls work, I had to provide the client certificate (including the private key) with the -Certificate parameter:

$Pwd = 'certificatepassword'
$Pfx = New-Object -TypeName 'System.Security.Cryptography.X509Certificates.X509Certificate2'
$Pfx.Import('clientcert.p12', $Pwd, 'Exportable,PersistKeySet')
Invoke-RestMethod -Uri 'https://your.rest.host/api/' -Certificate $Pfx -OtherParam ...

Hopefully my experience might help someone else who has my particular flavour of this problem.

How can I find the current OS in Python?

https://docs.python.org/library/os.html

To complement Greg's post, if you're on a posix system, which includes MacOS, Linux, Unix, etc. you can use os.uname() to get a better feel for what kind of system it is.

How do I make an HTML button not reload the page

Use either the <button> element or use an <input type="button"/>.

Printing everything except the first field with awk

awk '{ saved = $1; $1 = ""; print substr($0, 2), saved }'

Setting the first field to "" leaves a single copy of OFS at the start of $0. Assuming that OFS is only a single character (by default, it's a single space), we can remove it with substr($0, 2). Then we append the saved copy of $1.

Windows git "warning: LF will be replaced by CRLF", is that warning tail backward?

git config --global core.autocrlf false works well for global settings.

But if you are using Visual Studio, might also need to modify .gitattributes for some type of projects (e.g c# class library application):

  • remove line * text=auto

Reliable way to convert a file to a byte[]

Not to repeat what everyone already have said but keep the following cheat sheet handly for File manipulations:

  1. System.IO.File.ReadAllBytes(filename);
  2. File.Exists(filename)
  3. Path.Combine(folderName, resOfThePath);
  4. Path.GetFullPath(path); // converts a relative path to absolute one
  5. Path.GetExtension(path);

Extracting an attribute value with beautifulsoup

You can try gazpacho:

Install it using pip install gazpacho

Get the HTML and make the Soup using:

from gazpacho import get, Soup

soup = Soup(get("http://ip.add.ress.here/"))  # get directly returns the html

inputs = soup.find('input', attrs={'name': 'stainfo'})  # Find all the input tags

if inputs:
    if type(inputs) is list:
        for input in inputs:
             print(input.attr.get('value'))
    else:
         print(inputs.attr.get('value'))
else:
     print('No <input> tag found with the attribute name="stainfo")

Should each and every table have a primary key?

Just add it, you will be sorry later when you didn't (selecting, deleting. linking, etc)

Laravel 4: how to run a raw SQL?

The best way to do this I have found so far it to side step Laravel and execute the query directly using the Pdo object.

Example

DB::connection()->getPdo()->exec( $sql );

I usually find it faster and more efficient for a one time query to simply open my database query tool and type the query with full syntax checking then execute it directly.

This becomes essential if you have to work with stored procedures or need to use any database functions

Example 2 setting created_at to a the value you need it to be and side steeping any carbon funkiness

$sql = 'UPDATE my_table SET updated_at = FROM_UNIXTIME(nonce) WHERE id = ' . strval($this->id);
DB::statement($sql);

I found this worked in a controller but not in a migration

#1227 - Access denied; you need (at least one of) the SUPER privilege(s) for this operation

remove DEFINER=root@localhost from all calls including procedures

How to determine the version of android SDK installed in computer?

If you prefer to manage from UI, type android in command windows which will open the Android SDK Manager. Or you can directly open from C:\Program Files (x86)\Android\android-sdk\SDK Manager.exe

enter image description here

Docker-Compose persistent data MySQL

The data container is a superfluous workaround. Data-volumes would do the trick for you. Alter your docker-compose.yml to:

version: '2'
services:
  mysql:
    container_name: flask_mysql
    restart: always
    image: mysql:latest
    environment:
      MYSQL_ROOT_PASSWORD: 'test_pass' # TODO: Change this
      MYSQL_USER: 'test'
      MYSQL_PASS: 'pass'
    volumes:
      - my-datavolume:/var/lib/mysql
volumes:
  my-datavolume:

Docker will create the volume for you in the /var/lib/docker/volumes folder. This volume persist as long as you are not typing docker-compose down -v

In Perl, how can I read an entire file into a string?

This is more of a suggestion on how NOT to do it. I've just had a bad time finding a bug in a rather big Perl application. Most of the modules had its own configuration files. To read the configuration files as-a-whole, I found this single line of Perl somewhere on the Internet:

# Bad! Don't do that!
my $content = do{local(@ARGV,$/)=$filename;<>};

It reassigns the line separator as explained before. But it also reassigns the STDIN.

This had at least one side effect that cost me hours to find: It does not close the implicit file handle properly (since it does not call closeat all).

For example, doing that:

use strict;
use warnings;

my $filename = 'some-file.txt';

my $content = do{local(@ARGV,$/)=$filename;<>};
my $content2 = do{local(@ARGV,$/)=$filename;<>};
my $content3 = do{local(@ARGV,$/)=$filename;<>};

print "After reading a file 3 times redirecting to STDIN: $.\n";

open (FILE, "<", $filename) or die $!;

print "After opening a file using dedicated file handle: $.\n";

while (<FILE>) {
    print "read line: $.\n";
}

print "before close: $.\n";
close FILE;
print "after close: $.\n";

results in:

After reading a file 3 times redirecting to STDIN: 3
After opening a file using dedicated file handle: 3
read line: 1
read line: 2
(...)
read line: 46
before close: 46
after close: 0

The strange thing is, that the line counter $. is increased for every file by one. It's not reset, and it does not contain the number of lines. And it is not reset to zero when opening another file until at least one line is read. In my case, I was doing something like this:

while($. < $skipLines) {<FILE>};

Because of this problem, the condition was false because the line counter was not reset properly. I don't know if this is a bug or simply wrong code... Also calling close; oder close STDIN; does not help.

I replaced this unreadable code by using open, string concatenation and close. However, the solution posted by Brad Gilbert also works since it uses an explicit file handle instead.

The three lines at the beginning can be replaced by:

my $content = do{local $/; open(my $f1, '<', $filename) or die $!; my $tmp1 = <$f1>; close $f1 or die $!; $tmp1};
my $content2 = do{local $/; open(my $f2, '<', $filename) or die $!; my $tmp2 = <$f2>; close $f2 or die $!; $tmp2};
my $content3 = do{local $/; open(my $f3, '<', $filename) or die $!; my $tmp3 = <$f3>; close $f3 or die $!; $tmp3};

which properly closes the file handle.

How to pass values arguments to modal.show() function in Bootstrap

You could do it like this:

<a class="btn btn-primary announce" data-toggle="modal" data-id="107" >Announce</a>

Then use jQuery to bind the click and send the Announce data-id as the value in the modals #cafeId:

$(document).ready(function(){
   $(".announce").click(function(){ // Click to only happen on announce links
     $("#cafeId").val($(this).data('id'));
     $('#createFormId').modal('show');
   });
});

$(document).ready equivalent without jQuery

There is a standards based replacement,DOMContentLoaded that is supported by over 98% of browsers, though not IE8:

document.addEventListener("DOMContentLoaded", function(event) { 
  //do work
});

jQuery's native function is much more complicated than just window.onload, as depicted below.

function bindReady(){
    if ( readyBound ) return;
    readyBound = true;

    // Mozilla, Opera and webkit nightlies currently support this event
    if ( document.addEventListener ) {
        // Use the handy event callback
        document.addEventListener( "DOMContentLoaded", function(){
            document.removeEventListener( "DOMContentLoaded", arguments.callee, false );
            jQuery.ready();
        }, false );

    // If IE event model is used
    } else if ( document.attachEvent ) {
        // ensure firing before onload,
        // maybe late but safe also for iframes
        document.attachEvent("onreadystatechange", function(){
            if ( document.readyState === "complete" ) {
                document.detachEvent( "onreadystatechange", arguments.callee );
                jQuery.ready();
            }
        });

        // If IE and not an iframe
        // continually check to see if the document is ready
        if ( document.documentElement.doScroll && window == window.top ) (function(){
            if ( jQuery.isReady ) return;

            try {
                // If IE is used, use the trick by Diego Perini
                // http://javascript.nwbox.com/IEContentLoaded/
                document.documentElement.doScroll("left");
            } catch( error ) {
                setTimeout( arguments.callee, 0 );
                return;
            }

            // and execute any waiting functions
            jQuery.ready();
        })();
    }

    // A fallback to window.onload, that will always work
    jQuery.event.add( window, "load", jQuery.ready );
}

Passing a 2D array to a C++ function

A modification to shengy's first suggestion, you can use templates to make the function accept a multi-dimensional array variable (instead of storing an array of pointers that have to be managed and deleted):

template <size_t size_x, size_t size_y>
void func(double (&arr)[size_x][size_y])
{
    printf("%p\n", &arr);
}

int main()
{
    double a1[10][10];
    double a2[5][5];

    printf("%p\n%p\n\n", &a1, &a2);
    func(a1);
    func(a2);

    return 0;
}

The print statements are there to show that the arrays are getting passed by reference (by displaying the variables' addresses)

How to debug an apache virtual host configuration?

Syntax check

To check configuration files for syntax errors:

# Red Hat-based (Fedora, CentOS) and OSX
httpd -t

# Debian-based (Ubuntu)
apache2ctl -t

# MacOS
apachectl -t

List virtual hosts

To list all virtual hosts, and their locations:

# Red Hat-based (Fedora, CentOS) and OSX
httpd -S

# Debian-based (Ubuntu)
apache2ctl -S

# MacOS
apachectl -S

How do I write output in same place on the console?

x="A Sting {}"
   for i in range(0,1000000):
y=list(x.format(i))
print(x.format(i),end="")

for j in range(0,len(y)):
    print("\b",end="")

Convert HTML5 into standalone Android App

Create an Android app using Eclipse.

Create a layout that has a <WebView> control.

Move your HTML code to /assets folder.

Load webview with your file:///android_asset/ file.

And you have an android app!

MVC4 DataType.Date EditorFor won't display date value in Chrome, fine in Internet Explorer

In MVC 3 I had to add:

using System.ComponentModel.DataAnnotations;

among usings when adding properties:

[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]

Especially if you are adding these properties in .edmx file like me. I found that by default .edmx files don't have this using so adding only propeties is not enough.

Datatables - Search Box outside datatable

You can use the DataTables api to filter the table. So all you need is your own input field with a keyup event that triggers the filter function to DataTables. With css or jquery you can hide/remove the existing search input field. Or maybe DataTables has a setting to remove/not-include it.

Checkout the Datatables API documentation on this.

Example:

HTML

<input type="text" id="myInputTextField">

JS

oTable = $('#myTable').DataTable();   //pay attention to capital D, which is mandatory to retrieve "api" datatables' object, as @Lionel said
$('#myInputTextField').keyup(function(){
      oTable.search($(this).val()).draw() ;
})

Python: How would you save a simple settings/config file?

Configuration files in python

There are several ways to do this depending on the file format required.

ConfigParser [.ini format]

I would use the standard configparser approach unless there were compelling reasons to use a different format.

Write a file like so:

# python 2.x
# from ConfigParser import SafeConfigParser
# config = SafeConfigParser()

# python 3.x
from configparser import ConfigParser
config = ConfigParser()

config.read('config.ini')
config.add_section('main')
config.set('main', 'key1', 'value1')
config.set('main', 'key2', 'value2')
config.set('main', 'key3', 'value3')

with open('config.ini', 'w') as f:
    config.write(f)

The file format is very simple with sections marked out in square brackets:

[main]
key1 = value1
key2 = value2
key3 = value3

Values can be extracted from the file like so:

# python 2.x
# from ConfigParser import SafeConfigParser
# config = SafeConfigParser()

# python 3.x
from configparser import ConfigParser
config = ConfigParser()

config.read('config.ini')

print config.get('main', 'key1') # -> "value1"
print config.get('main', 'key2') # -> "value2"
print config.get('main', 'key3') # -> "value3"

# getfloat() raises an exception if the value is not a float
a_float = config.getfloat('main', 'a_float')

# getint() and getboolean() also do this for their respective types
an_int = config.getint('main', 'an_int')

JSON [.json format]

JSON data can be very complex and has the advantage of being highly portable.

Write data to a file:

import json

config = {"key1": "value1", "key2": "value2"}

with open('config1.json', 'w') as f:
    json.dump(config, f)

Read data from a file:

import json

with open('config.json', 'r') as f:
    config = json.load(f)

#edit the data
config['key3'] = 'value3'

#write it back to the file
with open('config.json', 'w') as f:
    json.dump(config, f)

YAML

A basic YAML example is provided in this answer. More details can be found on the pyYAML website.

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

Add the following to your /etc/bashrc file. This script adds a resident "function" instead of an alias called "confirm".


function confirm( )
{
#alert the user what they are about to do.
echo "About to $@....";
#confirm with the user
read -r -p "Are you sure? [Y/n]" response
case "$response" in
    [yY][eE][sS]|[yY]) 
              #if yes, then execute the passed parameters
               "$@"
               ;;
    *)
              #Otherwise exit...
              echo "ciao..."
              exit
              ;;
esac
}

How to re-create database for Entity Framework?

A possible very simple fix that worked for me. After deleting any database references and connections you find in server/serverobject explorer, right click the App_Data folder (didn't show any objects within the application for me) and select open. Once open put all the database/etc. files in a backup folder or if you have the guts just delete them. Run your application and it should recreate everything from scratch.

ReactJS: Warning: setState(...): Cannot update during an existing state transition

I am giving a generic example for better understanding, In the following code

render(){
    return(
      <div>

        <h3>Simple Counter</h3>
        <Counter
          value={this.props.counter}
          onIncrement={this.props.increment()} <------ calling the function
          onDecrement={this.props.decrement()} <-----------
          onIncrementAsync={this.props.incrementAsync()} />
      </div>
    )
  }

When supplying props I am calling the function directly, this wold have a infinite loop execution and would give you that error, Remove the function call everything works normally.

render(){
    return(
      <div>

        <h3>Simple Counter</h3>
        <Counter
          value={this.props.counter}
          onIncrement={this.props.increment} <------ function call removed
          onDecrement={this.props.decrement} <-----------
          onIncrementAsync={this.props.incrementAsync} />
      </div>
    )
  }

Git push error pre-receive hook declined

In my case, my team lead to created a repo(repo was empty) and assign me as developer so when I pushed to the code directly to master the error I was facing ! [remote rejected] master -> master (pre-receive hook declined) So how it was fixed that he assigned to me as maintainer so I was able to push the code directly to the master.

Vue component event after render

updated might be what you're looking for. https://vuejs.org/v2/api/#updated

Python: How to pip install opencv2 with specific version 2.4.9?

Below Python packages are to be downloaded and installed to their default locations.

1.1. Python-2.7.x.

1.2. Numpy.

1.3. Matplotlib (Matplotlib is optional, but recommended since we use it a lot in our tutorials).

Install all packages into their default locations. Python will be installed to C:/Python27/.

After installation, open Python IDLE. Enter import numpy and make sure Numpy is working fine.

Download latest OpenCV release from sourceforge site and double-click to extract it.

Goto opencv/build/python/2.7 folder.

Copy cv2.pyd to C:/Python27/lib/site-packeges.

Open Python IDLE and type following codes in Python terminal.

import cv2 print cv2.version If the results are printed out without any errors, congratulations !!! You have installed OpenCV-Python successfully.

https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_setup/py_setup_in_windows/py_setup_in_windows.html

How can git be installed on CENTOS 5.5?

I've tried few methods from this question and they all failed on my CentOs, either because of the wrong repos or missing files.

Here is the method which works for me (when installing version 1.7.8):

    yum -y install zlib-devel openssl-devel cpio expat-devel gettext-devel
    wget http://git-core.googlecode.com/files/git-1.7.8.tar.gz
    tar -xzvf ./git-1.7.8.tar.gz
    cd ./git-1.7.8
    ./configure
    make
    make install 

You may want to download a different version from here: http://code.google.com/p/git-core/downloads/list

Better way to convert file sizes in Python

Here's a version that matches the output of ls -lh.

def human_size(num: int) -> str:
    base = 1
    for unit in ['B', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']:
        n = num / base
        if n < 9.95 and unit != 'B':
            # Less than 10 then keep 1 decimal place
            value = "{:.1f}{}".format(n, unit)
            return value
        if round(n) < 1000:
            # Less than 4 digits so use this
            value = "{}{}".format(round(n), unit)
            return value
        base *= 1024
    value = "{}{}".format(round(n), unit)
    return value

Django - filtering on foreign key properties

student_user = User.objects.get(id=user_id)
available_subjects = Subject.objects.exclude(subject_grade__student__user=student_user) # My ans
enrolled_subjects = SubjectGrade.objects.filter(student__user=student_user)
context.update({'available_subjects': available_subjects, 'student_user': student_user, 
                'request':request, 'enrolled_subjects': enrolled_subjects})

In my application above, i assume that once a student is enrolled, a subject SubjectGrade instance will be created that contains the subject enrolled and the student himself/herself.

Subject and Student User model is a Foreign Key to the SubjectGrade Model.

In "available_subjects", i excluded all the subjects that are already enrolled by the current student_user by checking all subjectgrade instance that has "student" attribute as the current student_user

PS. Apologies in Advance if you can't still understand because of my explanation. This is the best explanation i Can Provide. Thank you so much

Heroku deployment error H10 (App crashed)

this happened to me when I was listening on the wrong port

I changed my listen() to "process.env.PORT" so:

http.listen((process.env.PORT || 5000), function(){
  console.log('listening on *:5000');
});

instead of

http.listen(5000, function(){
  console.log('listening on *:5000');
});

How to do multiple arguments to map function where one remains the same in python?

Map can contain multiple arguments, the standard way is

map(add, a, b)

In your question, it should be

map(add, a, [2]*len(a))

URL encoding the space character: + or %20?

From Wikipedia (emphasis and link added):

When data that has been entered into HTML forms is submitted, the form field names and values are encoded and sent to the server in an HTTP request message using method GET or POST, or, historically, via email. The encoding used by default is based on a very early version of the general URI percent-encoding rules, with a number of modifications such as newline normalization and replacing spaces with "+" instead of "%20". The MIME type of data encoded this way is application/x-www-form-urlencoded, and it is currently defined (still in a very outdated manner) in the HTML and XForms specifications.

So, the real percent encoding uses %20 while form data in URLs is in a modified form that uses +. So you're most likely to only see + in URLs in the query string after an ?.

Set Radiobuttonlist Selected from Codebehind

We can change the item by value, here is the trick:

radio1.ClearSelection();
radio1.Items.FindByValue("1").Selected = true;// 1 is the value of option2

How do I validate a date in rails?

Here's a non-chronic answer..

class Pimping < ActiveRecord::Base

validate :valid_date?

def valid_date?
  if scheduled_on.present?
    unless scheduled_on.is_a?(Time)
      errors.add(:scheduled_on, "Is an invalid date.")
    end
  end
end

Installing Bootstrap 3 on Rails App

I actually had an easy workaround on this one in which I nearly scratch my head on how to make it work. hahah!

Well, first I downloaded Bootstrap (the compiled css and js version).

Then I pasted all the bootstrap css files to the app/assets/stylesheets/.

And then I pasted all the bootstrap js files to the app/assets/javascripts/.

I reloaded the page and wallah! I just added bootstrap in my RoR!

How to remove specific element from an array using python

Your for loop is not right, if you need the index in the for loop use:

for index, item in enumerate(emails):
    # whatever (but you can't remove element while iterating)

In your case, Bogdan solution is ok, but your data structure choice is not so good. Having to maintain these two lists with data from one related to data from the other at same index is clumsy.

A list of tupple (email, otherdata) may be better, or a dict with email as key.

How can I avoid running ActiveRecord callbacks?

I wrote a plugin that implements update_without_callbacks in Rails 3:

http://github.com/dball/skip_activerecord_callbacks

The right solution, I think, is to rewrite your models to avoid callbacks in the first place, but if that's impractical in the near term, this plugin may help.

CSS3 transform: rotate; in IE9

I also had problems with transformations in IE9, I used -ms-transform: rotate(10deg) and it didn't work. Tried everything I could, but the problem was in browser mode, to make transformations work, you need to set compatibility mode to "Standard IE9".

C++ Array of pointers: delete or delete []?

It would make sens if your code was like this:

#include <iostream>

using namespace std;

class Monster
{
public:
        Monster() { cout << "Monster!" << endl; }
        virtual ~Monster() { cout << "Monster Died" << endl; }
};

int main(int argc, const char* argv[])
{
        Monster *mon = new Monster[6];

        delete [] mon;

        return 0;
}

How to overlay one div over another div

The accepted solution works great, but IMO lacks an explanation as to why it works. The example below is boiled down to the basics and separates the important CSS from the non-relevant styling CSS. As a bonus, I've also included a detailed explanation of how CSS positioning works.

TLDR; if you only want the code, scroll down to The Result.

The Problem

There are two separate, sibling, elements and the goal is to position the second element (with an id of infoi), so it appears within the previous element (the one with a class of navi). The HTML structure cannot be changed.

Proposed Solution

To achieve the desired result we're going to move, or position, the second element, which we'll call #infoi so it appears within the first element, which we'll call .navi. Specifically, we want #infoi to be positioned in the top-right corner of .navi.

CSS Position Required Knowledge

CSS has several properties for positioning elements. By default, all elements are position: static. This means the element will be positioned according to its order in the HTML structure, with few exceptions.

The other position values are relative, absolute, sticky, and fixed. By setting an element's position to one of these other values it's now possible to use a combination of the following four properties to position the element:

  • top
  • right
  • bottom
  • left

In other words, by setting position: absolute, we can add top: 100px to position the element 100 pixels from the top of the page. Conversely, if we set bottom: 100px the element would be positioned 100 pixels from the bottom of the page.

Here's where many CSS newcomers get lost - position: absolute has a frame of reference. In the example above, the frame of reference is the body element. position: absolute with top: 100px means the element is positioned 100 pixels from the top of the body element.

The position frame of reference, or position context, can be altered by setting the position of a parent element to any value other than position: static. That is, we can create a new position context by giving a parent element:

  • position: relative;
  • position: absolute;
  • position: sticky;
  • position: fixed;

For example, if a <div class="parent"> element is given position: relative, any child elements use the <div class="parent"> as their position context. If a child element were given position: absolute and top: 100px, the element would be positioned 100 pixels from the top of the <div class="parent"> element, because the <div class="parent"> is now the position context.

The other factor to be aware of is stack order - or how elements are stacked in the z-direction. The must-know here is the stack order of elements are, by default, defined by the reverse of their order in the HTML structure. Consider the following example:

<body>
  <div>Bottom</div>
  <div>Top</div>
</body>

In this example, if the two <div> elements were positioned in the same place on the page, the <div>Top</div> element would cover the <div>Bottom</div> element. Since <div>Top</div> comes after <div>Bottom</div> in the HTML structure it has a higher stacking order.

_x000D_
_x000D_
div {_x000D_
  position: absolute;_x000D_
  width: 50%;_x000D_
  height: 50%;_x000D_
}_x000D_
_x000D_
#bottom {_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  background-color: blue;_x000D_
}_x000D_
_x000D_
#top {_x000D_
  top: 25%;_x000D_
  left: 25%;_x000D_
  background-color: red;_x000D_
}
_x000D_
<div id="bottom">Bottom</div>_x000D_
<div id="top">Top</div>
_x000D_
_x000D_
_x000D_

The stacking order can be changed with CSS using the z-index or order properties.

We can ignore the stacking order in this issue as the natural HTML structure of the elements means the element we want to appear on top comes after the other element.

So, back to the problem at hand - we'll use position context to solve this issue.

The Solution

As stated above, our goal is to position the #infoi element so it appears within the .navi element. To do this, we'll wrap the .navi and #infoi elements in a new element <div class="wrapper"> so we can create a new position context.

<div class="wrapper">
  <div class="navi"></div>
  <div id="infoi"></div>
</div>

Then create a new position context by giving .wrapper a position: relative.

.wrapper {
  position: relative;
}

With this new position context, we can position #infoi within .wrapper. First, give #infoi a position: absolute, allowing us to position #infoi absolutely in .wrapper.

Then add top: 0 and right: 0 to position the #infoi element in the top-right corner. Remember, because the #infoi element is using .wrapper as its position context, it will be in the top-right of the .wrapper element.

#infoi {
  position: absolute;
  top: 0;
  right: 0;
}

Because .wrapper is merely a container for .navi, positioning #infoi in the top-right corner of .wrapper gives the effect of being positioned in the top-right corner of .navi.

And there we have it, #infoi now appears to be in the top-right corner of .navi.

The Result

The example below is boiled down to the basics, and contains some minimal styling.

_x000D_
_x000D_
/*_x000D_
*  position: relative gives a new position context_x000D_
*/_x000D_
.wrapper {_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
/*_x000D_
*  The .navi properties are for styling only_x000D_
*  These properties can be changed or removed_x000D_
*/_x000D_
.navi {_x000D_
  background-color: #eaeaea;_x000D_
  height: 40px;_x000D_
}_x000D_
_x000D_
_x000D_
/*_x000D_
*  Position the #infoi element in the top-right_x000D_
*  of the .wrapper element_x000D_
*/_x000D_
#infoi {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  right: 0;_x000D_
_x000D_
  /*_x000D_
  *  Styling only, the below can be changed or removed_x000D_
  *  depending on your use case_x000D_
  */_x000D_
  height: 20px;_x000D_
  padding: 10px 10px;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <div class="navi"></div>_x000D_
  <div id="infoi">_x000D_
    <img src="http://via.placeholder.com/32x20/000000/ffffff?text=?" height="20" width="32"/>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

An Alternate (Grid) Solution

Here's an alternate solution using CSS Grid to position the .navi element with the #infoi element in the far right. I've used the verbose grid properties to make it as clear as possible.

_x000D_
_x000D_
:root {_x000D_
  --columns: 12;_x000D_
}_x000D_
_x000D_
/*_x000D_
*  Setup the wrapper as a Grid element, with 12 columns, 1 row_x000D_
*/_x000D_
.wrapper {_x000D_
  display: grid;_x000D_
  grid-template-columns: repeat(var(--columns), 1fr);_x000D_
  grid-template-rows: 40px;_x000D_
}_x000D_
_x000D_
/*_x000D_
*  Position the .navi element to span all columns_x000D_
*/_x000D_
.navi {_x000D_
  grid-column-start: 1;_x000D_
  grid-column-end: span var(--columns);_x000D_
  grid-row-start: 1;_x000D_
  grid-row-end: 2;_x000D_
  _x000D_
  /*_x000D_
  *  Styling only, the below can be changed or removed_x000D_
  *  depending on your use case_x000D_
  */_x000D_
  background-color: #eaeaea;_x000D_
}_x000D_
_x000D_
_x000D_
/*_x000D_
*  Position the #infoi element in the last column, and center it_x000D_
*/_x000D_
#infoi {_x000D_
  grid-column-start: var(--columns);_x000D_
  grid-column-end: span 1;_x000D_
  grid-row-start: 1;_x000D_
  place-self: center;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <div class="navi"></div>_x000D_
  <div id="infoi">_x000D_
    <img src="http://via.placeholder.com/32x20/000000/ffffff?text=?" height="20" width="32"/>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

An Alternate (No Wrapper) Solution

In the case we can't edit any HTML, meaning we can't add a wrapper element, we can still achieve the desired effect.

Instead of using position: absolute on the #infoi element, we'll use position: relative. This allows us to reposition the #infoi element from its default position below the .navi element. With position: relative we can use a negative top value to move it up from its default position, and a left value of 100% minus a few pixels, using left: calc(100% - 52px), to position it near the right-side.

_x000D_
_x000D_
/*_x000D_
*  The .navi properties are for styling only_x000D_
*  These properties can be changed or removed_x000D_
*/_x000D_
.navi {_x000D_
  background-color: #eaeaea;_x000D_
  height: 40px;_x000D_
  width: 100%;_x000D_
}_x000D_
_x000D_
_x000D_
/*_x000D_
*  Position the #infoi element in the top-right_x000D_
*  of the .wrapper element_x000D_
*/_x000D_
#infoi {_x000D_
  position: relative;_x000D_
  display: inline-block;_x000D_
  top: -40px;_x000D_
  left: calc(100% - 52px);_x000D_
_x000D_
  /*_x000D_
  *  Styling only, the below can be changed or removed_x000D_
  *  depending on your use case_x000D_
  */_x000D_
  height: 20px;_x000D_
  padding: 10px 10px;_x000D_
}
_x000D_
<div class="navi"></div>_x000D_
<div id="infoi">_x000D_
  <img src="http://via.placeholder.com/32x20/000000/ffffff?text=?" height="20" width="32"/>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Python equivalent for HashMap

You need a dict:

my_dict = {'cheese': 'cake'}

Example code (from the docs):

>>> a = dict(one=1, two=2, three=3)
>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> d = dict([('two', 2), ('one', 1), ('three', 3)])
>>> e = dict({'three': 3, 'one': 1, 'two': 2})
>>> a == b == c == d == e
True

You can read more about dictionaries here.

Oracle Not Equals Operator

They are the same (as is the third form, ^=).

Note, though, that they are still considered different from the point of view of the parser, that is a stored outline defined for a != won't match <> or ^=.

This is unlike PostgreSQL where the parser treats != and <> yet on parsing stage, so you cannot overload != and <> to be different operators.

Can we install Android OS on any Windows Phone and vice versa, and same with iPhone and vice versa?

Android needs to be compiled for every hardware plattform / every device model seperatly with the specific drivers etc. If you manage to do that you need also break the security arrangements every manufacturer implements to prevent the installation of other software - these are also different between each model / manufacturer. So it is possible at in theory, but only there :-)

Compare 2 arrays which returns difference

Array operations like this is not jQuery's strongest point. You should consider a library such as Underscorejs, specifically the difference function.

Evaluate expression given as a string

You can use the parse() function to convert the characters into an expression. You need to specify that the input is text, because parse expects a file by default:

eval(parse(text="5+5"))

Sort dataGridView columns in C# ? (Windows Form)

Use Datatable.Default.Sort property and then bind it to the datagridview.

How to use BeginInvoke C#

Action is a Type of Delegate provided by the .NET framework. The Action points to a method with no parameters and does not return a value.

() => is lambda expression syntax. Lambda expressions are not of Type Delegate. Invoke requires Delegate so Action can be used to wrap the lambda expression and provide the expected Type to Invoke()

Invoke causes said Action to execute on the thread that created the Control's window handle. Changing threads is often necessary to avoid Exceptions. For example, if one tries to set the Rtf property on a RichTextBox when an Invoke is necessary, without first calling Invoke, then a Cross-thread operation not valid exception will be thrown. Check Control.InvokeRequired before calling Invoke.

BeginInvoke is the Asynchronous version of Invoke. Asynchronous means the thread will not block the caller as opposed to a synchronous call which is blocking.

How to force reloading php.ini file?

You also can use graceful restart the apache server with service apache2 reload or apachectl -k graceful. As the apache doc says:

The USR1 or graceful signal causes the parent process to advise the children to exit after their current request (or to exit immediately if they're not serving anything). The parent re-reads its configuration files and re-opens its log files. As each child dies off the parent replaces it with a child from the new generation of the configuration, which begins serving new requests immediately.

How can I drop a table if there is a foreign key constraint in SQL Server?

You have to drop the constraint before drop your table.

You can use those queries to find all FKs in your table and find the FKs in the tables in which your table is used.

Declare @SchemaName VarChar(200) = 'Your Schema name'
Declare @TableName VarChar(200) = 'Your Table Name'

-- Find FK in This table.
SELECT 
    ' IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = 
OBJECT_ID(N''' + 
      '[' + OBJECT_SCHEMA_NAME(FK.parent_object_id) + '].[' + FK.name + ']'
+ ''') AND parent_object_id = OBJECT_ID(N''' + 
      '[' + OBJECT_SCHEMA_NAME(FK.parent_object_id) + '].[' + 
OBJECT_NAME(FK.parent_object_id) + ']' + ''')) ' +

    'ALTER TABLE ' +  OBJECT_SCHEMA_NAME(FK.parent_object_id) +
    '.[' + OBJECT_NAME(FK.parent_object_id) + 
    '] DROP CONSTRAINT ' + FK.name
    , S.name , O.name, OBJECT_NAME(FK.parent_object_id)
FROM sys.foreign_keys AS FK
INNER JOIN Sys.objects As O 
  ON (O.object_id = FK.parent_object_id )
INNER JOIN SYS.schemas AS S 
  ON (O.schema_id = S.schema_id)  
WHERE 
      O.name = @TableName
      And S.name = @SchemaName


-- Find the FKs in the tables in which this table is used
  SELECT 
    ' IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id =   
      OBJECT_ID(N''' + 
      '[' + OBJECT_SCHEMA_NAME(FK.parent_object_id) + '].[' + FK.name + ']'
  + ''') AND parent_object_id = OBJECT_ID(N''' + 
      '[' + OBJECT_SCHEMA_NAME(FK.parent_object_id) + '].[' + 
 OBJECT_NAME(FK.parent_object_id) + ']' + ''')) ' +

    ' ALTER TABLE ' +  OBJECT_SCHEMA_NAME(FK.parent_object_id) +
    '.[' + OBJECT_NAME(FK.parent_object_id) + 
    '] DROP CONSTRAINT ' + FK.name
    , S.name , O.name, OBJECT_NAME(FK.parent_object_id)
FROM sys.foreign_keys AS FK
INNER JOIN Sys.objects As O 
  ON (O.object_id = FK.referenced_object_id )
INNER JOIN SYS.schemas AS S 
  ON (O.schema_id = S.schema_id)  
WHERE 
      O.name = @TableName
      And S.name = @SchemaName 

Java code To convert byte to Hexadecimal

This is a very fast way. No external libaries needed.

final protected static char[] HEXARRAY = "0123456789abcdef".toCharArray();

    public static String encodeHexString( byte[] bytes ) {

        char[] hexChars = new char[bytes.length * 2];
        for (int j = 0; j < bytes.length; j++) {
            int v = bytes[j] & 0xFF;
            hexChars[j * 2] = HEXARRAY[v >>> 4];
            hexChars[j * 2 + 1] = HEXARRAY[v & 0x0F];
        }
        return new String(hexChars);
    }

Batch Extract path and filename from a variable

All of this works for me:

@Echo Off
Echo Directory = %~dp0
Echo Object Name With Quotations=%0
Echo Object Name Without Quotes=%~0
Echo Bat File Drive = %~d0
Echo Full File Name = %~n0%~x0
Echo File Name Without Extension = %~n0
Echo File Extension = %~x0
Pause>Nul

Output:

Directory = D:\Users\Thejordster135\Desktop\Code\BAT\

Object Name With Quotations="D:\Users\Thejordster135\Desktop\Code\BAT\Path_V2.bat"

Object Name Without Quotes=D:\Users\Thejordster135\Desktop\Code\BAT\Path_V2.bat

Bat File Drive = D:

Full File Name = Path.bat

File Name Without Extension = Path

File Extension = .bat

How can I get my Twitter Bootstrap buttons to right align?

<ul>
    <li class="span4">One <input class="btn btn-small" value="test"></li>
    <li class="span4">Two <input class="btn btn-small" value="test2"></li>
</ul>

One way would be to apply this style to your list items in order to keep them inline

or

<ul>
    <li>One <input class="btn" value="test"></li>
    <li>Two <input class="btn" value="test2"></li>
</ul>

in CSS

li {
    line-height: 20px;
    margin: 5px;
    padding: 2px;
}

Simple way to count character occurrences in a string

I believe the "one liner" that you expected to get is this:

"abdsd3$asda$asasdd$sadas".replaceAll( "[^$]*($)?", "$1" ).length();

Remember that the requirements are:

(instead of traversing manually all the string, or loop for indexOf)

and let me add: that at the heart of this question it sounds like "any loop" is not wanted and there is no requirement for speed. I believe the subtext of this question is coolness factor.

Sorting options elements alphabetically using jQuery

<select id="mSelect" >
    <option value="val1" > DEF </option>
    <option value="val4" > GRT </option>
    <option value="val2" > ABC </option>
    <option value="val3" > OPL </option>
    <option value="val5" > AWS </option>
    <option value="val9" > BTY </option>
</select>

.

$("#mSelect").append($("#mSelect option").remove().sort(function(a, b) {
    var at = $(a).text(), bt = $(b).text();
    return (at > bt)?1:((at < bt)?-1:0);
}));

Allow only numbers to be typed in a textbox

You also can use some HTML5 attributes, some browsers might already take advantage of them (type="number" min="0").

Whatever you do, remember to re-check your inputs on the server side: you can never assume the client-side validation has been performed.

What are the differences between normal and slim package of jquery?

Looking at the code I found the following differences between jquery.js and jquery.slim.js:

In the jquery.slim.js, the following features are removed:

  1. jQuery.fn.extend
  2. jquery.fn.load
  3. jquery.each // Attach a bunch of functions for handling common AJAX events
  4. jQuery.expr.filters.animated
  5. ajax settings like jQuery.ajaxSettings.xhr, jQuery.ajaxPrefilter, jQuery.ajaxSetup, jQuery.ajaxPrefilter, jQuery.ajaxTransport, jQuery.ajaxSetup
  6. xml parsing like jQuery.parseXML,
  7. animation effects like jQuery.easing, jQuery.Animation, jQuery.speed

How to loop through all elements of a form jQuery

From the jQuery :input selector page:

Because :input is a jQuery extension and not part of the CSS specification, queries using :input cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. To achieve the best performance when using :input to select elements, first select the elements using a pure CSS selector, then use .filter(":input").

This is the best choice.

$('#new_user_form *').filter(':input').each(function(){
    //your code here
});

Correct set of dependencies for using Jackson mapper

Apart from fixing the imports, do a fresh maven clean compile -U. Note the -U option, that brings in new dependencies which sometimes the editor has hard time with. Let the compilation fail due to un-imported classes, but at least you have an option to import them after the maven command.

Just doing Maven->Reimport from Intellij did not work for me.

Found shared references to a collection org.hibernate.HibernateException

Posting here because it's taken me over 2 weeks to get to the bottom of this, and I still haven't fully resolved it.

There is a chance, that you're also just running into this bug which has been around since 2017 and hasn't been addressed.

I honestly have no clue how to get around this bug. I'm posting here for my sanity and hopefully to shave a couple weeks of your googling. I'd love any input anyone may have, but my particular "answer" to this problem was not listed in any of the above answers.

MySQL JOIN ON vs USING?

Database tables

To demonstrate how the USING and ON clauses work, let's assume we have the following post and post_comment database tables, which form a one-to-many table relationship via the post_id Foreign Key column in the post_comment table referencing the post_id Primary Key column in the post table:

SQL USING vs ON clauses table relationship

The parent post table has 3 rows:

| post_id | title     |
|---------|-----------|
| 1       | Java      |
| 2       | Hibernate |
| 3       | JPA       |

and the post_comment child table has the 3 records:

| post_comment_id | review    | post_id |
|-----------------|-----------|---------|
| 1               | Good      | 1       |
| 2               | Excellent | 1       |
| 3               | Awesome   | 2       |

The JOIN ON clause using a custom projection

Traditionally, when writing an INNER JOIN or LEFT JOIN query, we happen to use the ON clause to define the join condition.

For example, to get the comments along with their associated post title and identifier, we can use the following SQL projection query:

SELECT
   post.post_id,
   title,
   review
FROM post
INNER JOIN post_comment ON post.post_id = post_comment.post_id
ORDER BY post.post_id, post_comment_id

And, we get back the following result set:

| post_id | title     | review    |
|---------|-----------|-----------|
| 1       | Java      | Good      |
| 1       | Java      | Excellent |
| 2       | Hibernate | Awesome   |

The JOIN USING clause using a custom projection

When the Foreign Key column and the column it references have the same name, we can use the USING clause, like in the following example:

SELECT
  post_id,
  title,
  review
FROM post
INNER JOIN post_comment USING(post_id)
ORDER BY post_id, post_comment_id

And, the result set for this particular query is identical to the previous SQL query that used the ON clause:

| post_id | title     | review    |
|---------|-----------|-----------|
| 1       | Java      | Good      |
| 1       | Java      | Excellent |
| 2       | Hibernate | Awesome   |

The USING clause works for Oracle, PostgreSQL, MySQL, and MariaDB. SQL Server doesn't support the USING clause, so you need to use the ON clause instead.

The USING clause can be used with INNER, LEFT, RIGHT, and FULL JOIN statements.

SQL JOIN ON clause with SELECT *

Now, if we change the previous ON clause query to select all columns using SELECT *:

SELECT *
FROM post
INNER JOIN post_comment ON post.post_id = post_comment.post_id
ORDER BY post.post_id, post_comment_id

We are going to get the following result set:

| post_id | title     | post_comment_id | review    | post_id |
|---------|-----------|-----------------|-----------|---------|
| 1       | Java      | 1               | Good      | 1       |
| 1       | Java      | 2               | Excellent | 1       |
| 2       | Hibernate | 3               | Awesome   | 2       |

As you can see, the post_id is duplicated because both the post and post_comment tables contain a post_id column.

SQL JOIN USING clause with SELECT *

On the other hand, if we run a SELECT * query that features the USING clause for the JOIN condition:

SELECT *
FROM post
INNER JOIN post_comment USING(post_id)
ORDER BY post_id, post_comment_id

We will get the following result set:

| post_id | title     | post_comment_id | review    |
|---------|-----------|-----------------|-----------|
| 1       | Java      | 1               | Good      |
| 1       | Java      | 2               | Excellent |
| 2       | Hibernate | 3               | Awesome   |

You can see that this time, the post_id column is deduplicated, so there is a single post_id column being included in the result set.

Conclusion

If the database schema is designed so that Foreign Key column names match the columns they reference, and the JOIN conditions only check if the Foreign Key column value is equal to the value of its mirroring column in the other table, then you can employ the USING clause.

Otherwise, if the Foreign Key column name differs from the referencing column or you want to include a more complex join condition, then you should use the ON clause instead.

How do I encode and decode a base64 string?

URL safe Base64 Encoding/Decoding

public static class Base64Url
{
    public static string Encode(string text)
    {
        return Convert.ToBase64String(Encoding.UTF8.GetBytes(text)).TrimEnd('=').Replace('+', '-')
            .Replace('/', '_');
    }

    public static string Decode(string text)
    {
        text = text.Replace('_', '/').Replace('-', '+');
        switch (text.Length % 4)
        {
            case 2:
                text += "==";
                break;
            case 3:
                text += "=";
                break;
        }
        return Encoding.UTF8.GetString(Convert.FromBase64String(text));
    }
}

C# List<> Sort by x then y

The trick is to implement a stable sort. I've created a Widget class that can contain your test data:

public class Widget : IComparable
{
    int x;
    int y;
    public int X
    {
        get { return x; }
        set { x = value; }
    }

    public int Y
    {
        get { return y; }
        set { y = value; }
    }

    public Widget(int argx, int argy)
    {
        x = argx;
        y = argy;
    }

    public int CompareTo(object obj)
    {
        int result = 1;
        if (obj != null && obj is Widget)
        {
            Widget w = obj as Widget;
            result = this.X.CompareTo(w.X);
        }
        return result;
    }

    static public int Compare(Widget x, Widget y)
    {
        int result = 1;
        if (x != null && y != null)                
        {                
            result = x.CompareTo(y);
        }
        return result;
    }
}

I implemented IComparable, so it can be unstably sorted by List.Sort().

However, I also implemented the static method Compare, which can be passed as a delegate to a search method.

I borrowed this insertion sort method from C# 411:

 public static void InsertionSort<T>(IList<T> list, Comparison<T> comparison)
        {           
            int count = list.Count;
            for (int j = 1; j < count; j++)
            {
                T key = list[j];

                int i = j - 1;
                for (; i >= 0 && comparison(list[i], key) > 0; i--)
                {
                    list[i + 1] = list[i];
                }
                list[i + 1] = key;
            }
    }

You would put this in the sort helpers class that you mentioned in your question.

Now, to use it:

    static void Main(string[] args)
    {
        List<Widget> widgets = new List<Widget>();

        widgets.Add(new Widget(0, 1));
        widgets.Add(new Widget(1, 1));
        widgets.Add(new Widget(0, 2));
        widgets.Add(new Widget(1, 2));

        InsertionSort<Widget>(widgets, Widget.Compare);

        foreach (Widget w in widgets)
        {
            Console.WriteLine(w.X + ":" + w.Y);
        }
    }

And it outputs:

0:1
0:2
1:1
1:2
Press any key to continue . . .

This could probably be cleaned up with some anonymous delegates, but I'll leave that up to you.

EDIT: And NoBugz demonstrates the power of anonymous methods...so, consider mine more oldschool :P

Get Environment Variable from Docker Container

You can use printenv VARIABLE instead of /bin/bash -c 'echo $VARIABLE. It's much simpler and it does not perform substitution:

docker exec container printenv VARIABLE

Add number of days to a date

Use the following code.

<?php echo date('Y-m-d', strtotime(' + 5 days')); ?>

Reference has found from here - How to Add Days to Current Date in PHP

Disable html5 video autoplay

Remove ALL attributes that say autoplay as its presence in your tag is a boolean shorthand for true.

Also, make sure you always use video or audio elements. Do not use object or embed as those elements autoplay using 3rd part plugins by default and cannot be stopped without changing settings in the browser.

How to get the selected item of a combo box to a string variable in c#

Try this:

string selected = this.ComboBox.GetItemText(this.ComboBox.SelectedItem);
MessageBox.Show(selected);

Why can't Visual Studio find my DLL?

try "configuration properties -> debugging -> environment" and set the PATH variable in run-time

Retrieving Dictionary Value Best Practices

TryGetValue is slightly faster, because FindEntry will only be called once.

How much faster? It depends on the dataset at hand. When you call the Contains method, Dictionary does an internal search to find its index. If it returns true, you need another index search to get the actual value. When you use TryGetValue, it searches only once for the index and if found, it assigns the value to your variable.

FYI: It's not actually catching an error.

It's calling:

public bool TryGetValue(TKey key, out TValue value)
{
    int index = this.FindEntry(key);
    if (index >= 0)
    {
        value = this.entries[index].value;
        return true;
    }
    value = default(TValue);
    return false;
}

ContainsKey is this:

public bool ContainsKey(TKey key)
{
    return (this.FindEntry(key) >= 0);
}

Implement Stack using Two Queues

import java.util.*;

/**
 *
 * @author Mahmood
 */
public class StackImplUsingQueues {

    Queue<Integer> q1 = new LinkedList<Integer>();
    Queue<Integer> q2 = new LinkedList<Integer>();

    public int pop() {
        if (q1.peek() == null) {
            System.out.println("The stack is empty, nothing to return");
            int i = 0;
            return i;
        } else {
            int pop = q1.remove();
            return pop;
        }
    }

    public void push(int data) {

        if (q1.peek() == null) {
            q1.add(data);
        } else {
            for (int i = q1.size(); i > 0; i--) {
                q2.add(q1.remove());
            }
            q1.add(data);
            for (int j = q2.size(); j > 0; j--) {
                q1.add(q2.remove());
            }

        }
    }

    public static void main(String[] args) {
        StackImplUsingQueues s1 = new StackImplUsingQueues();
        //       Stack s1 = new Stack();
        s1.push(1);
        s1.push(2);
        s1.push(3);
        s1.push(4);
        s1.push(5);
        s1.push(6);
        s1.push(7);
        s1.push(8);
        s1.push(9);
        s1.push(10);
        // s1.push(6);
        System.out.println("1st = " + s1.pop());
        System.out.println("2nd = " + s1.pop());
        System.out.println("3rd = " + s1.pop());
        System.out.println("4th = " + s1.pop());
        System.out.println("5th = " + s1.pop());
        System.out.println("6th = " + s1.pop());
        System.out.println("7th = " + s1.pop());
        System.out.println("8th = " + s1.pop());
        System.out.println("9th = " + s1.pop());
        System.out.println("10th= " + s1.pop());
    }
}

"installation of package 'FILE_PATH' had non-zero exit status" in R

You can try using command : install.packages('*package_name', dependencies = TRUE)

For example is you have to install 'caret' package in your R machine in linux : install.packages('caret', dependencies = TRUE)

Doing so, all the dependencies for the package will also be downloaded.

How to parse a string into a nullable int

[Updated to use modern C# as per @sblom's suggestion]

I had this problem and I ended up with this (after all, an if and 2 returns is soo long-winded!):

int? ToNullableInt (string val)
    => int.TryParse (val, out var i) ? (int?) i : null;

On a more serious note, try not to mix int, which is a C# keyword, with Int32, which is a .NET Framework BCL type - although it works, it just makes code look messy.

What are the differences between type() and isinstance()?

Differences between isinstance() and type() in Python?

Type-checking with

isinstance(obj, Base)

allows for instances of subclasses and multiple possible bases:

isinstance(obj, (Base1, Base2))

whereas type-checking with

type(obj) is Base

only supports the type referenced.


As a sidenote, is is likely more appropriate than

type(obj) == Base

because classes are singletons.

Avoid type-checking - use Polymorphism (duck-typing)

In Python, usually you want to allow any type for your arguments, treat it as expected, and if the object doesn't behave as expected, it will raise an appropriate error. This is known as polymorphism, also known as duck-typing.

def function_of_duck(duck):
    duck.quack()
    duck.swim()

If the code above works, we can presume our argument is a duck. Thus we can pass in other things are actual sub-types of duck:

function_of_duck(mallard)

or that work like a duck:

function_of_duck(object_that_quacks_and_swims_like_a_duck)

and our code still works.

However, there are some cases where it is desirable to explicitly type-check. Perhaps you have sensible things to do with different object types. For example, the Pandas Dataframe object can be constructed from dicts or records. In such a case, your code needs to know what type of argument it is getting so that it can properly handle it.

So, to answer the question:

Differences between isinstance() and type() in Python?

Allow me to demonstrate the difference:

type

Say you need to ensure a certain behavior if your function gets a certain kind of argument (a common use-case for constructors). If you check for type like this:

def foo(data):
    '''accepts a dict to construct something, string support in future'''
    if type(data) is not dict:
        # we're only going to test for dicts for now
        raise ValueError('only dicts are supported for now')

If we try to pass in a dict that is a subclass of dict (as we should be able to, if we're expecting our code to follow the principle of Liskov Substitution, that subtypes can be substituted for types) our code breaks!:

from collections import OrderedDict

foo(OrderedDict([('foo', 'bar'), ('fizz', 'buzz')]))

raises an error!

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in foo
ValueError: argument must be a dict

isinstance

But if we use isinstance, we can support Liskov Substitution!:

def foo(a_dict):
    if not isinstance(a_dict, dict):
        raise ValueError('argument must be a dict')
    return a_dict

foo(OrderedDict([('foo', 'bar'), ('fizz', 'buzz')]))

returns OrderedDict([('foo', 'bar'), ('fizz', 'buzz')])

Abstract Base Classes

In fact, we can do even better. collections provides Abstract Base Classes that enforce minimal protocols for various types. In our case, if we only expect the Mapping protocol, we can do the following, and our code becomes even more flexible:

from collections import Mapping

def foo(a_dict):
    if not isinstance(a_dict, Mapping):
        raise ValueError('argument must be a dict')
    return a_dict

Response to comment:

It should be noted that type can be used to check against multiple classes using type(obj) in (A, B, C)

Yes, you can test for equality of types, but instead of the above, use the multiple bases for control flow, unless you are specifically only allowing those types:

isinstance(obj, (A, B, C))

The difference, again, is that isinstance supports subclasses that can be substituted for the parent without otherwise breaking the program, a property known as Liskov substitution.

Even better, though, invert your dependencies and don't check for specific types at all.

Conclusion

So since we want to support substituting subclasses, in most cases, we want to avoid type-checking with type and prefer type-checking with isinstance - unless you really need to know the precise class of an instance.

How to set the text/value/content of an `Entry` widget using a button in tkinter

Your problem is that when you do this:

a = Button(win, text="plant", command=setText("plant"))

it tries to evaluate what to set for the command. So when instantiating the Button object, it actually calls setText("plant"). This is wrong, because you don't want to call the setText method yet. Then it takes the return value of this call (which is None), and sets that to the command of the button. That's why clicking the button does nothing, because there is no command set for it.

If you do as Milan Skála suggested and use a lambda expression instead, then your code will work (assuming you fix the indentation and the parentheses).

Instead of command=setText("plant"), which actually calls the function, you can set command=lambda:setText("plant") which specifies something which will call the function later, when you want to call it.

If you don't like lambdas, another (slightly more cumbersome) way would be to define a pair of functions to do what you want:

def set_to_plant():
    set_text("plant")
def set_to_animal():
    set_text("animal")

and then you can use command=set_to_plant and command=set_to_animal - these will evaluate to the corresponding functions, but are definitely not the same as command=set_to_plant() which would of course evaluate to None again.

How to open a web page automatically in full screen mode

You can go fullscreen automatically by putting this code in:

var elem = document.documentElement; if (elem.requestFullscreen) { elem.requestFullscreen() }

demo: https://codepen.io/ConfidentCoding/pen/ewLyPX

note: does not always work for security reasons. but it works for me at least. does not work when inspecting and pasting the code.

How to call a method defined in an AngularJS directive?

You can tell the method name to directive to define which you want to call from controller but without isolate scope,

_x000D_
_x000D_
angular.module("app", [])_x000D_
  .directive("palyer", [_x000D_
    function() {_x000D_
      return {_x000D_
        restrict: "A",_x000D_
        template:'<div class="player"><span ng-bind="text"></span></div>',_x000D_
        link: function($scope, element, attr) {_x000D_
          if (attr.toPlay) {_x000D_
            $scope[attr.toPlay] = function(name) {_x000D_
              $scope.text = name + " playing...";_x000D_
            }_x000D_
          }_x000D_
        }_x000D_
      };_x000D_
    }_x000D_
  ])_x000D_
  .controller("playerController", ["$scope",_x000D_
    function($scope) {_x000D_
      $scope.clickPlay = function() {_x000D_
        $scope.play('AR Song');_x000D_
      };_x000D_
    }_x000D_
  ]);
_x000D_
.player{_x000D_
  border:1px solid;_x000D_
  padding: 10px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
<div ng-app="app">_x000D_
  <div ng-controller="playerController">_x000D_
    <p>Click play button to play_x000D_
      <p>_x000D_
        <p palyer="" to-play="play"></p>_x000D_
        <button ng-click="clickPlay()">Play</button>_x000D_
_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Add a property to a JavaScript object using a variable as the name?

Related to the subject, not specifically for jquery though. I used this in ec6 react projects, maybe helps someone:

this.setState({ [`${name}`]: value}, () => {
      console.log("State updated: ", JSON.stringify(this.state[name]));
    });

PS: Please mind the quote character.

SQL Inner join 2 tables with multiple column conditions and update

You need to do

Update table_xpto
set column_xpto = x.xpto_New
    ,column2 = x.column2New
from table_xpto xpto
   inner join table_xptoNew xptoNew ON xpto.bla = xptoNew.Bla
where <clause where>

If you need a better answer, you can give us more information :)

Requests -- how to tell if you're getting a 404

Look at the r.status_code attribute:

if r.status_code == 404:
    # A 404 was issued.

Demo:

>>> import requests
>>> r = requests.get('http://httpbin.org/status/404')
>>> r.status_code
404

If you want requests to raise an exception for error codes (4xx or 5xx), call r.raise_for_status():

>>> r = requests.get('http://httpbin.org/status/404')
>>> r.raise_for_status()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "requests/models.py", line 664, in raise_for_status
    raise http_error
requests.exceptions.HTTPError: 404 Client Error: NOT FOUND
>>> r = requests.get('http://httpbin.org/status/200')
>>> r.raise_for_status()
>>> # no exception raised.

You can also test the response object in a boolean context; if the status code is not an error code (4xx or 5xx), it is considered ‘true’:

if r:
    # successful response

If you want to be more explicit, use if r.ok:.

Find specific string in a text file with VBS script

Wow, after few attempts I finally figured out how to deal with my text edits in vbs. The code works perfectly, it gives me the result I was expecting. Maybe it's not the best way to do this, but it does its job. Here's the code:

Option Explicit

Dim StdIn:  Set StdIn = WScript.StdIn
Dim StdOut: Set StdOut = WScript


Main()

Sub Main()

Dim objFSO, filepath, objInputFile, tmpStr, ForWriting, ForReading, count, text, objOutputFile, index, TSGlobalPath, foundFirstMatch
Set objFSO = CreateObject("Scripting.FileSystemObject")
TSGlobalPath = "C:\VBS\TestSuiteGlobal\Test suite Dispatch Decimal - Global.txt"
ForReading = 1
ForWriting = 2
Set objInputFile = objFSO.OpenTextFile(TSGlobalPath, ForReading, False)
count = 7
text=""
foundFirstMatch = false

Do until objInputFile.AtEndOfStream
    tmpStr = objInputFile.ReadLine
    If foundStrMatch(tmpStr)=true Then
        If foundFirstMatch = false Then
            index = getIndex(tmpStr)
            foundFirstMatch = true
            text = text & vbCrLf & textSubstitution(tmpStr,index,"true")
        End If
        If index = getIndex(tmpStr) Then
            text = text & vbCrLf & textSubstitution(tmpStr,index,"false")
        ElseIf index < getIndex(tmpStr) Then
            index = getIndex(tmpStr)
            text = text & vbCrLf & textSubstitution(tmpStr,index,"true")
        End If
    Else
        text = text & vbCrLf & textSubstitution(tmpStr,index,"false")
    End If
Loop
Set objOutputFile = objFSO.CreateTextFile("C:\VBS\NuovaProva.txt", ForWriting, true)
objOutputFile.Write(text)
End Sub


Function textSubstitution(tmpStr,index,foundMatch)
Dim strToAdd
strToAdd = "<tr><td><a href=" & chr(34) & "../../Logs/CF5.0_Features/Beginning_of_CF5.0_Features_TC" & CStr(index) & ".html" & chr(34) & ">Beginning_of_CF5.0_Features_TC" & CStr(index) & "</a></td></tr>"
If foundMatch = "false" Then
    textSubstitution = tmpStr
ElseIf foundMatch = "true" Then
    textSubstitution = strToAdd & vbCrLf & tmpStr
End If
End Function


Function getIndex(tmpStr)
Dim substrToFind, charAtPos, char1, char2
substrToFind = "<tr><td><a href=" & chr(34) & "../Test case "
charAtPos = len(substrToFind) + 1
char1 = Mid(tmpStr, charAtPos, 1)
char2 = Mid(tmpStr, charAtPos+1, 1)
If IsNumeric(char2) Then
    getIndex = CInt(char1 & char2)
Else
    getIndex = CInt(char1)
End If
End Function

Function foundStrMatch(tmpStr)
Dim substrToFind
substrToFind = "<tr><td><a href=" & chr(34) & "../Test case "
If InStr(tmpStr, substrToFind) > 0 Then
    foundStrMatch = true
Else
    foundStrMatch = false
End If
End Function

This is the original txt file

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <meta content="text/html; charset=UTF-8" http-equiv="content-type" />
  <title>Test Suite</title>
</head>
<body>
<table id="suiteTable" cellpadding="1" cellspacing="1" border="1" class="selenium"><tbody>
<tr><td><b>Test Suite</b></td></tr>
<tr><td><a href="../../Component/TC_Environment_setting">TC_Environment_setting</a></td></tr>
<tr><td><a href="../../Component/TC_Set_variables">TC_Set_variables</a></td></tr>
<tr><td><a href="../../Component/TC_Set_ID">TC_Set_ID</a></td></tr>
<tr><td><a href="../../Login/Log_in_Admin">Log_in_Admin</a></td></tr>
<tr><td><a href="../../Component/Set_Roles_Dispatch_Decimal">Set_Roles_Dispatch_Decimal</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../Test case 5 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 5 DD/contrD1">contrD1</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1B1">Log_ in_U1B1</a></td></tr>
<tr><td><a href="../../Component/Search&OpenApp">Search&OpenApp</a></td></tr>
<tr><td><a href="../Test case 5 DD/FormEND">FormEND</a></td></tr>
<tr><td><a href="../../Component/Controllo END">Controllo END</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../Test case 6 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 6 DD/contrD1">contrD1</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1B1">Log_ in_U1B1</a></td></tr>
<tr><td><a href="../../Component/Search&OpenApp">Search&OpenApp</a></td></tr>
<tr><td><a href="../Test case 5 DD/FormEND">FormEND</a></td></tr>
<tr><td><a href="../../Component/Controllo END">Controllo END</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../Test case 7 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../../Component/Controllo DeadLetter">Controllo DeadLetter</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Component/Set_Roles_Dispatch_Decimal">Set_Roles_Dispatch_Decimal</a></td></tr>
<tr><td><a href="../../Login/Logout_BAC">Logout_BAC</a></td></tr>
</tbody></table>
</body>
</html>

And this is the result I'm expecting

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <meta content="text/html; charset=UTF-8" http-equiv="content-type" />
  <title>Test Suite</title>
</head>
<body>
<table id="suiteTable" cellpadding="1" cellspacing="1" border="1" class="selenium"><tbody>
<tr><td><b>Test Suite</b></td></tr>
<tr><td><a href="../../Component/TC_Environment_setting">TC_Environment_setting</a></td></tr>
<tr><td><a href="../../Component/TC_Set_variables">TC_Set_variables</a></td></tr>
<tr><td><a href="../../Component/TC_Set_ID">TC_Set_ID</a></td></tr>
<tr><td><a href="../../Login/Log_in_Admin">Log_in_Admin</a></td></tr>
<tr><td><a href="../../Component/Set_Roles_Dispatch_Decimal">Set_Roles_Dispatch_Decimal</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../../Logs/CF5.0_Features/Beginning_of_CF5.0_Features_TC5.html">Beginning_of_CF5.0_Features_TC5</a></td></tr>
<tr><td><a href="../Test case 5 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 5 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 5 DD/contrD1">contrD1</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1B1">Log_ in_U1B1</a></td></tr>
<tr><td><a href="../../Component/Search&OpenApp">Search&OpenApp</a></td></tr>
<tr><td><a href="../Test case 5 DD/FormEND">FormEND</a></td></tr>
<tr><td><a href="../../Component/Controllo END">Controllo END</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../../Logs/CF5.0_Features/Beginning_of_CF5.0_Features_TC6.html">Beginning_of_CF5.0_Features_TC6</a></td></tr>
<tr><td><a href="../Test case 6 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 6 DD/contrD1">contrD1</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1B1">Log_ in_U1B1</a></td></tr>
<tr><td><a href="../../Component/Search&OpenApp">Search&OpenApp</a></td></tr>
<tr><td><a href="../../Component/Controllo END">Controllo END</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../../Logs/CF5.0_Features/Beginning_of_CF5.0_Features_TC7.html">Beginning_of_CF5.0_Features_TC7</a></td></tr>
<tr><td><a href="../Test case 7 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../../Component/Controllo DeadLetter">Controllo DeadLetter</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Component/Set_Roles_Dispatch_Decimal">Set_Roles_Dispatch_Decimal</a></td></tr>
<tr><td><a href="../../Login/Logout_BAC">Logout_BAC</a></td></tr>
</tbody></table>
</body>
</html>

How to Upload Image file in Retrofit 2

It is quite easy. Here is the API Interface

public interface Api {

    @Multipart
    @POST("upload")
    Call<MyResponse> uploadImage(@Part("image\"; filename=\"myfile.jpg\" ") RequestBody file, @Part("desc") RequestBody desc);

}

And you can use the following code to make a call.

private void uploadFile(File file, String desc) {

        //creating request body for file
        RequestBody requestFile = RequestBody.create(MediaType.parse(getContentResolver().getType(fileUri)), file);
        RequestBody descBody = RequestBody.create(MediaType.parse("text/plain"), desc);

        //The gson builder
        Gson gson = new GsonBuilder()
                .setLenient()
                .create();


        //creating retrofit object
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Api.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build();

        //creating our api 
        Api api = retrofit.create(Api.class);

        //creating a call and calling the upload image method 
        Call<MyResponse> call = api.uploadImage(requestFile, descBody);

        //finally performing the call 
        call.enqueue(new Callback<MyResponse>() {
            @Override
            public void onResponse(Call<MyResponse> call, Response<MyResponse> response) {
                if (!response.body().error) {
                    Toast.makeText(getApplicationContext(), "File Uploaded Successfully...", Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(getApplicationContext(), "Some error occurred...", Toast.LENGTH_LONG).show();
                }
            }

            @Override
            public void onFailure(Call<MyResponse> call, Throwable t) {
                Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_LONG).show();
            }
        });
    }

Source: Retrofit Upload File Tutorial.

Relational Database Design Patterns?

Design patterns aren't trivially reusable solutions.

Design patterns are reusable, by definition. They're patterns you detect in other good solutions.

A pattern is not trivially reusable. You can implement your down design following the pattern however.

Relational design patters include things like:

  1. One-to-Many relationships (master-detail, parent-child) relationships using a foreign key.

  2. Many-to-Many relationships with a bridge table.

  3. Optional one-to-one relationships managed with NULLs in the FK column.

  4. Star-Schema: Dimension and Fact, OLAP design.

  5. Fully normalized OLTP design.

  6. Multiple indexed search columns in a dimension.

  7. "Lookup table" that contains PK, description and code value(s) used by one or more applications. Why have code? I don't know, but when they have to be used, this is a way to manage the codes.

  8. Uni-table. [Some call this an anti-pattern; it's a pattern, sometimes it's bad, sometimes it's good.] This is a table with lots of pre-joined stuff that violates second and third normal form.

  9. Array table. This is a table that violates first normal form by having an array or sequence of values in the columns.

  10. Mixed-use database. This is a database normalized for transaction processing but with lots of extra indexes for reporting and analysis. It's an anti-pattern -- don't do this. People do it anyway, so it's still a pattern.

Most folks who design databases can easily rattle off a half-dozen "It's another one of those"; these are design patterns that they use on a regular basis.

And this doesn't include administrative and operational patterns of use and management.

PHP include relative path

function relativepath($to){
    $a=explode("/",$_SERVER["PHP_SELF"] );
    $index= array_search("$to",$a);
    $str=""; 
    for ($i = 0; $i < count($a)-$index-2; $i++) {
        $str.= "../";
    }
    return $str;
    }

Here is the best solution i made about that, you just need to specify at which level you want to stop, but the problem is that you have to use this folder name one time.

Is there a query language for JSON?

jmespath works really quite easy and well, http://jmespath.org/ It is being used by Amazon in the AWS command line interface, so it´s got to be quite stable.

How to check that a JCheckBox is checked?

Use the isSelected method.

You can also use an ItemListener so you'll be notified when it's checked or unchecked.

nvarchar(max) still being truncated

Your first problem is a limitation of the PRINT statement. I'm not sure why sp_executesql is failing. It should support pretty much any length of input.

Perhaps the reason the query is malformed is something other than truncation.

Number of processors/cores in command line

The lscpu(1) command provided by the util-linux project might also be useful:

$ lscpu
Architecture:          x86_64
CPU op-mode(s):        32-bit, 64-bit
Byte Order:            Little Endian
CPU(s):                4
On-line CPU(s) list:   0-3
Thread(s) per core:    2
Core(s) per socket:    2
Socket(s):             1
NUMA node(s):          1
Vendor ID:             GenuineIntel
CPU family:            6
Model:                 58
Model name:            Intel(R) Core(TM) i7-3520M CPU @ 2.90GHz
Stepping:              9
CPU MHz:               3406.253
CPU max MHz:           3600.0000
CPU min MHz:           1200.0000
BogoMIPS:              5787.10
Virtualization:        VT-x
L1d cache:             32K
L1i cache:             32K
L2 cache:              256K
L3 cache:              4096K
NUMA node0 CPU(s):     0-3

How to display a JSON representation and not [Object Object] on the screen

We can use angular pipe json

{{ jsonObject | json }}

Getting the exception value in Python

If you don't know the type/origin of the error, you can try:

import sys
try:
    doSomethingWrongHere()
except:
    print('Error: {}'.format(sys.exc_info()[0]))

But be aware, you'll get pep8 warning:

[W] PEP 8 (E722): do not use bare except

python how to pad numpy array with zeros

NumPy 1.7.0 (when numpy.pad was added) is pretty old now (it was released in 2013) so even though the question asked for a way without using that function I thought it could be useful to know how that could be achieved using numpy.pad.

It's actually pretty simple:

>>> import numpy as np
>>> a = np.array([[ 1.,  1.,  1.,  1.,  1.],
...               [ 1.,  1.,  1.,  1.,  1.],
...               [ 1.,  1.,  1.,  1.,  1.]])
>>> np.pad(a, [(0, 1), (0, 1)], mode='constant')
array([[ 1.,  1.,  1.,  1.,  1.,  0.],
       [ 1.,  1.,  1.,  1.,  1.,  0.],
       [ 1.,  1.,  1.,  1.,  1.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.]])

In this case I used that 0 is the default value for mode='constant'. But it could also be specified by passing it in explicitly:

>>> np.pad(a, [(0, 1), (0, 1)], mode='constant', constant_values=0)
array([[ 1.,  1.,  1.,  1.,  1.,  0.],
       [ 1.,  1.,  1.,  1.,  1.,  0.],
       [ 1.,  1.,  1.,  1.,  1.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.]])

Just in case the second argument ([(0, 1), (0, 1)]) seems confusing: Each list item (in this case tuple) corresponds to a dimension and item therein represents the padding before (first element) and after (second element). So:

[(0, 1), (0, 1)]
         ^^^^^^------ padding for second dimension
 ^^^^^^-------------- padding for first dimension

  ^------------------ no padding at the beginning of the first axis
     ^--------------- pad with one "value" at the end of the first axis.

In this case the padding for the first and second axis are identical, so one could also just pass in the 2-tuple:

>>> np.pad(a, (0, 1), mode='constant')
array([[ 1.,  1.,  1.,  1.,  1.,  0.],
       [ 1.,  1.,  1.,  1.,  1.,  0.],
       [ 1.,  1.,  1.,  1.,  1.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.]])

In case the padding before and after is identical one could even omit the tuple (not applicable in this case though):

>>> np.pad(a, 1, mode='constant')
array([[ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  1.,  1.,  1.,  1.,  1.,  0.],
       [ 0.,  1.,  1.,  1.,  1.,  1.,  0.],
       [ 0.,  1.,  1.,  1.,  1.,  1.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.]])

Or if the padding before and after is identical but different for the axis, you could also omit the second argument in the inner tuples:

>>> np.pad(a, [(1, ), (2, )], mode='constant')
array([[ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  1.,  1.,  1.,  1.,  1.,  0.,  0.],
       [ 0.,  0.,  1.,  1.,  1.,  1.,  1.,  0.,  0.],
       [ 0.,  0.,  1.,  1.,  1.,  1.,  1.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.]])

However I tend to prefer to always use the explicit one, because it's just to easy to make mistakes (when NumPys expectations differ from your intentions):

>>> np.pad(a, [1, 2], mode='constant')
array([[ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  1.,  1.,  1.,  1.,  1.,  0.,  0.],
       [ 0.,  1.,  1.,  1.,  1.,  1.,  0.,  0.],
       [ 0.,  1.,  1.,  1.,  1.,  1.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.]])

Here NumPy thinks you wanted to pad all axis with 1 element before and 2 elements after each axis! Even if you intended it to pad with 1 element in axis 1 and 2 elements for axis 2.

I used lists of tuples for the padding, note that this is just "my convention", you could also use lists of lists or tuples of tuples, or even tuples of arrays. NumPy just checks the length of the argument (or if it doesn't have a length) and the length of each item (or if it has a length)!

Altering user-defined table types in SQL Server

As of my knowledge it is impossible to alter/modify a table type.You can create the type with a different name and then drop the old type and modify it to the new name

Credits to jkrajes

As per msdn, it is like 'The user-defined table type definition cannot be modified after it is created'.

JAX-WS - Adding SOAP Headers

Adding an object to header we use the examples used here,yet i will complete

  ObjectFactory objectFactory = new ObjectFactory();
        CabeceraCR cabeceraCR =objectFactory.createCabeceraCR();
        cabeceraCR.setUsuario("xxxxx");
        cabeceraCR.setClave("xxxxx");

With object factory we create the object asked to pass on the header. The to add to the header

  WSBindingProvider bp = (WSBindingProvider)wsXXXXXXSoap;
        bp.setOutboundHeaders(
                // Sets a simple string value as a header
                Headers.create(jaxbContext,objectFactory.createCabeceraCR(cabeceraCR))
                );

We used the WSBindingProvider to add the header. The object will have some error if used directly so we use the method

objectFactory.createCabeceraCR(cabeceraCR)

This method will create a JAXBElement like this on the object Factory

  @XmlElementDecl(namespace = "http://www.creditreport.ec/", name = "CabeceraCR")
    public JAXBElement<CabeceraCR> createCabeceraCR(CabeceraCR value) {
        return new JAXBElement<CabeceraCR>(_CabeceraCR_QNAME, CabeceraCR.class, null, value);
    }

And the jaxbContext we obtained like this:

  jaxbContext = (JAXBRIContext) JAXBContext.newInstance(CabeceraCR.class.getPackage().getName());

This will add the object to the header.

What are Covering Indexes and Covered Queries in SQL Server?

A covering query is on where all the predicates can be matched using the indices on the underlying tables.

This is the first step towards improving the performance of the sql under consideration.

Spring @Autowired and @Qualifier

You can use @Qualifier along with @Autowired. In fact spring will ask you explicitly select the bean if ambiguous bean type are found, in which case you should provide the qualifier

For Example in following case it is necessary provide a qualifier

@Component
@Qualifier("staff") 
public Staff implements Person {}

@Component
@Qualifier("employee") 
public Manager implements Person {}


@Component
public Payroll {

    private Person person;

    @Autowired
    public Payroll(@Qualifier("employee") Person person){
          this.person = person;
    }

}

EDIT:

In Lombok 1.18.4 it is finally possible to avoid the boilerplate on constructor injection when you have @Qualifier, so now it is possible to do the following:

@Component
@Qualifier("staff") 
public Staff implements Person {}

@Component
@Qualifier("employee") 
public Manager implements Person {}


@Component
@RequiredArgsConstructor
public Payroll {
   @Qualifier("employee") private final Person person;
}

provided you are using the new lombok.config rule copyableAnnotations (by placing the following in lombok.config in the root of your project):

# Copy the Qualifier annotation from the instance variables to the constructor
# see https://github.com/rzwitserloot/lombok/issues/745
lombok.copyableAnnotations += org.springframework.beans.factory.annotation.Qualifier

This was recently introduced in latest lombok 1.18.4.

NOTE

If you are using field or setter injection then you have to place the @Autowired and @Qualifier on top of the field or setter function like below(any one of them will work)

public Payroll {
   @Autowired @Qualifier("employee") private final Person person;
}

or

public Payroll {
   private final Person person;
   @Autowired
   @Qualifier("employee")
   public void setPerson(Person person) {
     this.person = person;
   } 
}

If you are using constructor injection then the annotations should be placed on constructor, else the code would not work. Use it like below -

public Payroll {

    private Person person;

    @Autowired
    public Payroll(@Qualifier("employee") Person person){
          this.person = person;
    }

}

How do I round to the nearest 0.5?

Multiply your rating by 2, then round using Math.Round(rating, MidpointRounding.AwayFromZero), then divide that value by 2.

Math.Round(value * 2, MidpointRounding.AwayFromZero) / 2

How to make PDF file downloadable in HTML link?

Here's a different approach. I prefer rather than to rely on browser support, or address this at the application layer, to use web server logic.

If you are using Apache, and can put an .htaccess file in the relevant directory you could use the code below. Of course, you could put this in httpd.conf as well, if you have access to that.

<FilesMatch "\.(?i:pdf)$">
  Header set Content-Disposition attachment
</FilesMatch>

The FilesMatch directive is just a regex so it could be set as granularly as you want, or you could add in other extensions.

The Header line does the same thing as the first line in the PHP scripts above. If you need to set the Content-Type lines as well, you could do so in the same manner, but I haven't found that necessary.

What does ENABLE_BITCODE do in xcode 7?

Update

Apple has clarified that slicing occurs independent of enabling bitcode. I've observed this in practice as well where a non-bitcode enabled app will only be downloaded as the architecture appropriate for the target device.

Original

More specifically:

Bitcode. Archive your app for submission to the App Store in an intermediate representation, which is compiled into 64- or 32-bit executables for the target devices when delivered.

Slicing. Artwork incorporated into the Asset Catalog and tagged for a platform allows the App Store to deliver only what is needed for installation.

The way I read this, if you support bitcode, downloaders of your app will only get the compiled architecture needed for their own device.

How to get a pixel's x,y coordinate color from an image?

The two previous answers demonstrate how to use Canvas and ImageData. I would like to propose an answer with runnable example and using an image processing framework, so you don't need to handle the pixel data manually.

MarvinJ provides the method image.getAlphaComponent(x,y) which simply returns the transparency value for the pixel in x,y coordinate. If this value is 0, pixel is totally transparent, values between 1 and 254 are transparency levels, finally 255 is opaque.

For demonstrating I've used the image below (300x300) with transparent background and two pixels at coordinates (0,0) and (150,150).

enter image description here

Console output:

(0,0): TRANSPARENT
(150,150): NOT_TRANSPARENT

_x000D_
_x000D_
image = new MarvinImage();_x000D_
image.load("https://i.imgur.com/eLZVbQG.png", imageLoaded);_x000D_
_x000D_
function imageLoaded(){_x000D_
  console.log("(0,0): "+(image.getAlphaComponent(0,0) > 0 ? "NOT_TRANSPARENT" : "TRANSPARENT"));_x000D_
  console.log("(150,150): "+(image.getAlphaComponent(150,150) > 0 ? "NOT_TRANSPARENT" : "TRANSPARENT"));_x000D_
}
_x000D_
<script src="https://www.marvinj.org/releases/marvinj-0.7.js"></script>
_x000D_
_x000D_
_x000D_

How do you enable auto-complete functionality in Visual Studio C++ express edition?

Have you tried Visual Assist X ? Sort of lights up the VS editor.

.gitignore after commit

However, will it automatically remove these committed files from the repository?

No. Even with an existing .gitignore you are able to stage "ignored" files with the -f (force) flag. If they files are already commited, they don't get removed automatically.

git rm --cached path/to/ignored.exe

GridView - Show headers on empty data source

You can use HeaderTemplate property to setup the head programatically or use ListView instead if you are using .NET 3.5.

Personally, I prefer ListView over GridView and DetailsView if possible, it gives you more control over your html.

can't start MySql in Mac OS 10.6 Snow Leopard

First of all can I just say that I really really love the Internet community for all that it does in providing answers to everybody. I don't post a lot but everybody's posting here and on so many boards helped me so much! None of them gave me the right answer mind you, but here is my unique solution to this nightmare of a spending 2 solid days trying to install MySQL 5.5.9 on Snow Leopard 10.6. Skip to bottom for resolution.

Here's what happened.

I had a server crash recently. The server was rebuilt and of course MySQL 5.5.8 didn't work. What a worthless piece. I had 5.1.54 on my other machine. That had been a pain to install as well but not like this.

I had all sorts of issues installing with the dmg from mysql.org, installing mysql5 using macports, uninstalling trying to revert to 5.1.54 (couldn't because I couldn't find the receipt file with that info even though I followed the directions). After rming everything I could find related to mysql and then reinstalling 5.5.8 everything worked! Until I rebooted... ? I looked in my system preference mysql pane and found mysql server wasn't starting. (skip to end for resolution)

My first error (super common) included: ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysql.sock' and numerous other EXTREMELY common issues related to mysql.sock http://forums.mysql.com/read.php?11,9689,13272

Here were things I tried: 1)Create /etc/my.cnf file with the proper paths to mysql.sock. I even tried modifying mysql.server with vi directly. Modifying the php.ini was worthless. Nothing worked because MySQL wasn't starting, therefore it wasn't creating mysql.sock in the first place. Maybe you can point to the directory it is being created, and not the actual full file path i.e. not /tmp/mysql.sock but /tmp It was suggested but wasn't working because there was no mysql.sock because mysqld wasn't spawning.

2)Basedir and datadir modifications didn't work because there was no mysql.sock to point too.

Why? Because the mysql daemon wasn't starting. Without anything to start mysqld and thereby create mysql.sock I was doomed. They are an important part of the solution but if you try them and still get errors, you will know why.

3)sudo chown -R root:wheel /Library/StartupItems/MySQLCOM/

didn't solve my problem. I ended up having that folder and all items set to root:wheel though in the end, because it was one of the many things recommended and its working. Maybe it could remain _mysql but wheel works.

4)Copy mysql.sock from another machine. Doesn't work. I had searched and searched my new machine and couldn't find mysql.sock. I was using find / | grep mysql.sock because locate mysql wasn't finding anything. Besides I was trying so many different things it wasn't updating enough to find my new installs. I now like find much more than locate, even though you can update the locate db. Anyhow you can't copy mysql.sock, even if you tar it because its a 0 byte file.

THE RESOLUTION: I finally stumbled onto the solution. I finally just typed mysqld from command line while I was in the proper bin directory. It said another process was running. _mysql was spawning a process that I could see in the Activity Monitor. I killed the active mysql process and when I typed mysqld again I found it was creating my mysql.sock file in the /private/tmp/mysql.sock

The mysql pref pane wouldn't start the right process on login, so I just disabled that for being worthless. It wouldn't start mysql because no mysql.sock was being created.

By then I had figured out that mysqld creates mysql.sock. I then found /opt/local/mysql/ and typed "open bin" in the terminal window. This opened the directory with mysqld in it.

I went to login items in the system preferences in my account settings and dragged and dropped the mysqld file onto the startup items there. THAT worked. Finally!

It works flawlessly because mysqld is starting up at login, which means mysql.sock is being created so no more errors about not being able to find mysql.sock.

web.xml is missing and <failOnMissingWebXml> is set to true

Remove files from -web/.setting&-admin/.setting

1

How to convert column with string type to int form in pyspark data frame?

You could use cast(as int) after replacing NaN with 0,

data_df = df.withColumn("Plays", df.call_time.cast('float'))

A html space is showing as %2520 instead of %20

For some - possibly valid - reason the url was encoded twice. %25 is the urlencoded % sign. So the original url looked like:

http://server.com/my path/

Then it got urlencoded once:

http://server.com/my%20path/

and twice:

http://server.com/my%2520path/

So you should do no urlencoding - in your case - as other components seems to to that already for you. Use simply a space

MD5 is 128 bits but why is it 32 characters?

I wanted summerize some of the answers into one post.

First, don't think of the MD5 hash as a character string but as a hex number. Therefore, each digit is a hex digit (0-15 or 0-F) and represents four bits, not eight.

Taking that further, one byte or eight bits are represented by two hex digits, e.g. b'1111 1111' = 0xFF = 255.

MD5 hashes are 128 bits in length and generally represented by 32 hex digits.

SHA-1 hashes are 160 bits in length and generally represented by 40 hex digits.

For the SHA-2 family, I think the hash length can be one of a pre-determined set. So SHA-512 can be represented by 128 hex digits.

Again, this post is just based on previous answers.

Generate random numbers following a normal distribution in C/C++

Take a look at what I found.

This library uses the Ziggurat algorithm.

Clear ComboBox selected text

all depend on the configuration. for me works

comboBox.SelectedIndex = -1;

my configuration

DropDownStyle: DropDownList

(text can't be changed for the user)

Using LIMIT within GROUP BY to get N results per group?

SELECT year, id, rate
FROM (SELECT
  year, id, rate, row_number() over (partition by id order by rate DESC)
  FROM h
  WHERE year BETWEEN 2000 AND 2009
  AND id IN (SELECT rid FROM table2)
  GROUP BY id, year
  ORDER BY id, rate DESC) as subquery
WHERE row_number <= 5

The subquery is almost identical to your query. Only change is adding

row_number() over (partition by id order by rate DESC)

Force re-download of release dependency using Maven

When you added it to X, you should have incremented X's version number i.e X-1.2
Then X-1.2 should have been installed/deployed and you should have changed your projects dependency on X to be dependent on the new version X-1.2

How to trigger an event in input text after I stop typing/writing?

SOLUTION:

Here is the solution. Executing a function after the user has stopped typing for a specified amount of time:

var delay = (function(){
  var timer = 0;
  return function(callback, ms){
  clearTimeout (timer);
  timer = setTimeout(callback, ms);
 };
})();

Usage

$('input').keyup(function() {
  delay(function(){
    alert('Hi, func called');
  }, 1000 );
});

Is there an easy way to attach source in Eclipse?

When you add a jar file to a classpath you can attach a source directory or zip or jar file to that jar. In the Java Build Path properties, on the Libraries tab, expand the entry for the jar and you'll see there's an item for the source attachment. Select this item and then click the Edit button. This lets you select the folder, jar or zip that contains the source.

Additionally, if you select a class or a method in the jar and CTRL+CLICK on it (or press F3) then you'll go into the bytecode view which has an option to attach the source code.

Doing these things will give you all the parameter names as well as full javadoc.

If you don't have the source but do have the javadoc, you can attach the javadoc via the first method. It can even reference an external URL if you don't have it downloaded.

How can I get the value of a registry key from within a batch script?

@echo off
setlocal ENABLEEXTENSIONS
set KEY_NAME=HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\awhost32.exe
set VALUE_NAME=Path
for /F "usebackq tokens=3" %%A IN (`reg query "%KEY_NAME%" /v "%VALUE_NAME%" 2^>nul ^| find "%VALUE_NAME%"`) do (
  echo %%A
)

How do you handle a space in the %%A variable? This results in C:\Program. The actual path is C:\Program Files\Symantec\pcAnywhere.

Secure hash and salt for PHP passwords

Google says SHA256 is available to PHP.

You should definitely use a salt. I'd recommend using random bytes (and not restrict yourself to characters and numbers). As usually, the longer you choose, the safer, slower it gets. 64 bytes ought to be fine, i guess.

How to change a nullable column to not nullable in a Rails migration?

In Rails 4.02+ according to the docs there is no method like update_all with 2 arguments. Instead one can use this code:

# Make sure no null value exist
MyModel.where(date_column: nil).update_all(date_column: Time.now)

# Change the column to not allow null
change_column :my_models, :date_column, :datetime, null: false

How to safely upgrade an Amazon EC2 instance from t1.micro to large?

From my experience, the way I do it is create a snapshot of your current image, then once its done you'll see it as an option when launching new instances. Simply launch it as a large instance at that point.

This is my approach if I do not want any downtime(i.e. production server) because this solution only takes a server offline only after the new one is up and running(I also use it to add new machines to my clusters by using this approach to only add new machines). If Downtime is acceptable then see Marcel Castilho's answer.

Error Code: 1290. The MySQL server is running with the --secure-file-priv option so it cannot execute this statement

If you changed my.ini and restarted mysql and you still get this error please check your file path and replace "\" to "/". I solved my proplem after replacing.

Aliases in Windows command prompt

If you'd like to enable aliases on per-directory/per-project basis, try the following:

  1. First, create a batch file that will look for a file named aliases in the current directory and initialize aliases from it, let’s call it make-aliases.cmd

    @echo off
    if not exist aliases goto:eof
    echo [Loading aliases...]
    for /f "tokens=1* delims=^=" %%i in (aliases) do (
       echo   %%i ^<^=^> %%j
       doskey %%i=%%j
    )
    doskey aliases=doskey /macros
    echo   --------------------
    echo   aliases ^=^> list  all
    echo   alt+F10 ^=^> clear all
    echo [Done]
    
  2. Then, create aliases wherever you need them using the following format:

    alias1 = command1
    alias2 = command2
    ...
    

    for example:

    b = nmake
    c = nmake clean
    r = nmake rebuild
    
  3. Then, add the location of make-aliases.cmd to your %PATH% variable to make it system-wide or just keep it in a known place.

  4. Make it start automatically with cmd.

    • I would definitely advise against using HKEY_CURRENT_USER\Software\Microsoft\Command Processor\AutoRun for this, because some development tools would trigger the autorun script multiple times per session.

    • If you use ConEmu you could go another way and start the script from the startup task (Settings > Startup > Tasks), for example, I created an entry called {MSVC}:

      cmd.exe /k "vcvars64 && make-aliases",

      and then registered it in Explorer context menu via Settings > Integration> with Command: {MSVC} -cur_console:n, so that now I can right-click a folder and launch a VS developer prompt inside it with my aliases loaded automatically, if they happen to be in that folder.

      Without ConEmu, you may just want to create a shortcut to cmd.exe with the corresponding command or simply run make-aliases manually every time.

Should you happen to forget your aliases, use the aliases macro, and if anything goes wrong, just reset the current session by pressing Alt+F10, which is a built-in command in cmd.

pandas unique values multiple columns

for those of us that love all things pandas, apply, and of course lambda functions:

df['Col3'] = df[['Col1', 'Col2']].apply(lambda x: ''.join(x), axis=1)

How to Validate Google reCaptcha on Form Submit

when using JavaScript it will work for me

_x000D_
_x000D_
<script src='https://www.google.com/recaptcha/api.js'></script>_x000D_
<script>_x000D_
function submitUserForm() {_x000D_
    var response = grecaptcha.getResponse();_x000D_
    if(response.length == 0) {_x000D_
        document.getElementById('g-recaptcha-error').innerHTML = '<span style="color:red;">This field is required.</span>';_x000D_
        return false;_x000D_
    }_x000D_
    return true;_x000D_
}_x000D_
 _x000D_
function verifyCaptcha() {_x000D_
    document.getElementById('g-recaptcha-error').innerHTML = '';_x000D_
}_x000D_
</script>
_x000D_
<form method="post" onsubmit="return submitUserForm();">_x000D_
    <div class="g-recaptcha" data-sitekey="YOUR_SITE_KEY" data-callback="verifyCaptcha"></div>_x000D_
    <div id="g-recaptcha-error"></div>_x000D_
    <input type="submit" name="submit" value="Submit" />_x000D_
</form>
_x000D_
_x000D_
_x000D_

How can my iphone app detect its own version number?

A succinct way to obtain a version string in X.Y.Z format is:

[NSBundle mainBundle].infoDictionary[@"CFBundleVersion"]

Or, for just X.Y:

[NSBundle mainBundle].infoDictionary[@"CFBundleShortVersionString"]

Both of these snippets returns strings that you would assign to your label object's text property, e.g.

myLabel.text = [NSBundle mainBundle].infoDictionary[@"CFBundleVersion"];

What is PEP8's E128: continuation line under-indented for visual indent?

This goes also for statements like this (auto-formatted by PyCharm):

    return combine_sample_generators(sample_generators['train']), \
           combine_sample_generators(sample_generators['dev']), \
           combine_sample_generators(sample_generators['test'])

Which will give the same style-warning. In order to get rid of it I had to rewrite it to:

    return \
        combine_sample_generators(sample_generators['train']), \
        combine_sample_generators(sample_generators['dev']), \
        combine_sample_generators(sample_generators['test'])